ocr_mkcontent.py 2.1 KB
Newer Older
赵小蒙's avatar
赵小蒙 committed
1
2
3
from magic_pdf.libs.ocr_content_type import ContentType


赵小蒙's avatar
赵小蒙 committed
4
def ocr_mk_nlp_markdown(pdf_info_dict: dict):
赵小蒙's avatar
赵小蒙 committed
5
6
7
8
9
10
11
12
13
14
    markdown = []

    for _, page_info in pdf_info_dict.items():
        blocks = page_info.get("preproc_blocks")
        if not blocks:
            continue
        for block in blocks:
            for line in block['lines']:
                line_text = ''
                for span in line['spans']:
15
16
                    if not span.get('content'):
                        continue
赵小蒙's avatar
赵小蒙 committed
17
                    content = span['content'].replace('$', '\$')  # 转义$
赵小蒙's avatar
赵小蒙 committed
18
                    if span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
19
                        content = f"${content}$"
赵小蒙's avatar
赵小蒙 committed
20
                    elif span['type'] == ContentType.InterlineEquation:
赵小蒙's avatar
赵小蒙 committed
21
22
23
24
25
                        content = f"$$\n{content}\n$$"
                    line_text += content + ' '
                # 在行末添加两个空格以强制换行
                markdown.append(line_text.strip() + '  ')
    return '\n'.join(markdown)
26

赵小蒙's avatar
赵小蒙 committed
27

赵小蒙's avatar
赵小蒙 committed
28
def ocr_mk_mm_markdown(pdf_info_dict: dict):
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

    markdown = []

    for _, page_info in pdf_info_dict.items():
        blocks = page_info.get("preproc_blocks")
        if not blocks:
            continue
        for block in blocks:
            for line in block['lines']:
                line_text = ''
                for span in line['spans']:
                    if not span.get('content'):
                        if not span.get('image_path'):
                            continue
                        else:
                            content = f"![]({span['image_path']})"
                    else:
                        content = span['content'].replace('$', '\$')  # 转义$
赵小蒙's avatar
赵小蒙 committed
47
                        if span['type'] == ContentType.InlineEquation:
48
                            content = f"${content}$"
赵小蒙's avatar
赵小蒙 committed
49
                        elif span['type'] == ContentType.InterlineEquation:
50
51
52
53
54
                            content = f"$$\n{content}\n$$"
                    line_text += content + ' '
                # 在行末添加两个空格以强制换行
                markdown.append(line_text.strip() + '  ')
    return '\n'.join(markdown)