ocr_mkcontent.py 7.95 KB
Newer Older
赵小蒙's avatar
赵小蒙 committed
1
2
from loguru import logger

3
from magic_pdf.libs.commons import join_path
4
from magic_pdf.libs.language import detect_lang
赵小蒙's avatar
赵小蒙 committed
5
from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
赵小蒙's avatar
赵小蒙 committed
6
from magic_pdf.libs.ocr_content_type import ContentType
7
8
9
10
11
12
13
14
15
16
17
18
19
import wordninja
import re


def split_long_words(text):
    segments = text.split(' ')
    for i in range(len(segments)):
        words = re.findall(r'\w+|[^\w\s]', segments[i], re.UNICODE)
        for j in range(len(words)):
            if len(words[j]) > 15:
                words[j] = ' '.join(wordninja.split(words[j]))
        segments[i] = ''.join(words)
    return ' '.join(segments)
赵小蒙's avatar
赵小蒙 committed
20
21


赵小蒙's avatar
赵小蒙 committed
22
def ocr_mk_mm_markdown_with_para(pdf_info_list: list, img_buket_path):
xuchao's avatar
xuchao committed
23
    markdown = []
赵小蒙's avatar
赵小蒙 committed
24
    for page_info in pdf_info_list:
25
        paras_of_layout = page_info.get("para_blocks")
赵小蒙's avatar
赵小蒙 committed
26
        page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm", img_buket_path)
27
        markdown.extend(page_markdown)
28
    return '\n\n'.join(markdown)
29
30


赵小蒙's avatar
赵小蒙 committed
31
def ocr_mk_nlp_markdown_with_para(pdf_info_dict: list):
32
    markdown = []
赵小蒙's avatar
赵小蒙 committed
33
    for page_info in pdf_info_dict:
34
        paras_of_layout = page_info.get("para_blocks")
35
        page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "nlp")
36
37
38
        markdown.extend(page_markdown)
    return '\n\n'.join(markdown)

赵小蒙's avatar
赵小蒙 committed
39
def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list, img_buket_path):
40
    markdown_with_para_and_pagination = []
赵小蒙's avatar
赵小蒙 committed
41
42
    page_no = 0
    for page_info in pdf_info_dict:
43
44
        paras_of_layout = page_info.get("para_blocks")
        if not paras_of_layout:
45
            continue
赵小蒙's avatar
赵小蒙 committed
46
        page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm", img_buket_path)
47
48
        markdown_with_para_and_pagination.append({
            'page_no': page_no,
49
            'md_content': '\n\n'.join(page_markdown)
50
        })
赵小蒙's avatar
赵小蒙 committed
51
        page_no += 1
52
53
54
    return markdown_with_para_and_pagination


赵小蒙's avatar
赵小蒙 committed
55
def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=""):
56
57
58
59
60
61
62
    page_markdown = []
    for paras in paras_of_layout:
        for para in paras:
            para_text = ''
            for line in para:
                for span in line['spans']:
                    span_type = span.get('type')
63
                    content = ''
64
                    language = ''
65
                    if span_type == ContentType.Text:
66
67
68
69
70
71
                        content = span['content']
                        language = detect_lang(content)
                        if language == 'en':  # 只对英文长词进行分词处理,中文分词会丢失文本
                            content = ocr_escape_special_markdown_char(split_long_words(content))
                        else:
                            content = ocr_escape_special_markdown_char(content)
72
                    elif span_type == ContentType.InlineEquation:
73
                        content = f"${span['content']}$"
74
                    elif span_type == ContentType.InterlineEquation:
75
                        content = f"\n$$\n{span['content']}\n$$\n"
76
                    elif span_type in [ContentType.Image, ContentType.Table]:
77
                        if mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
78
                            content = f"\n![]({join_path(img_buket_path, span['image_path'])})\n"
79
80
                        elif mode == 'nlp':
                            pass
81
                    if content != '':
82
83
84
85
                        if language == 'en':  # 英文语境下 content间需要空格分隔
                            para_text += content + ' '
                        else:  # 中文语境下,content间不需要空格分隔
                            para_text += content
86
87
88
89
            if para_text.strip() == '':
                continue
            else:
                page_markdown.append(para_text.strip() + '  ')
90
91
92
    return page_markdown


93
def para_to_standard_format(para, img_buket_path):
94
95
    para_content = {}
    if len(para) == 1:
96
        para_content = line_to_standard_format(para[0], img_buket_path)
97
98
99
100
101
    elif len(para) > 1:
        para_text = ''
        inline_equation_num = 0
        for line in para:
            for span in line['spans']:
102
                language = ''
103
                span_type = span.get('type')
赵小蒙's avatar
赵小蒙 committed
104
                content = ""
105
                if span_type == ContentType.Text:
106
107
108
109
110
111
                    content = span['content']
                    language = detect_lang(content)
                    if language == 'en':  # 只对英文长词进行分词处理,中文分词会丢失文本
                        content = ocr_escape_special_markdown_char(split_long_words(content))
                    else:
                        content = ocr_escape_special_markdown_char(content)
112
                elif span_type == ContentType.InlineEquation:
113
                    content = f"${span['content']}$"
114
                    inline_equation_num += 1
115
116
117
118
119

                if language == 'en':  # 英文语境下 content间需要空格分隔
                    para_text += content + ' '
                else:  # 中文语境下,content间不需要空格分隔
                    para_text += content
120
121
122
123
124
125
126
        para_content = {
            'type': 'text',
            'text': para_text,
            'inline_equation_num': inline_equation_num
        }
    return para_content

赵小蒙's avatar
赵小蒙 committed
127
def make_standard_format_with_para(pdf_info_dict: list, img_buket_path: str):
赵小蒙's avatar
赵小蒙 committed
128
    content_list = []
赵小蒙's avatar
赵小蒙 committed
129
    for page_info in pdf_info_dict:
130
131
        paras_of_layout = page_info.get("para_blocks")
        if not paras_of_layout:
赵小蒙's avatar
赵小蒙 committed
132
            continue
133
134
        for paras in paras_of_layout:
            for para in paras:
135
                para_content = para_to_standard_format(para, img_buket_path)
136
                content_list.append(para_content)
赵小蒙's avatar
赵小蒙 committed
137
138
139
    return content_list


140
def line_to_standard_format(line, img_buket_path):
赵小蒙's avatar
赵小蒙 committed
141
142
143
144
145
146
147
148
149
150
    line_text = ""
    inline_equation_num = 0
    for span in line['spans']:
        if not span.get('content'):
            if not span.get('image_path'):
                continue
            else:
                if span['type'] == ContentType.Image:
                    content = {
                        'type': 'image',
151
                        'img_path': join_path(img_buket_path, span['image_path'])
赵小蒙's avatar
赵小蒙 committed
152
153
154
155
156
                    }
                    return content
                elif span['type'] == ContentType.Table:
                    content = {
                        'type': 'table',
157
                        'img_path': join_path(img_buket_path, span['image_path'])
赵小蒙's avatar
赵小蒙 committed
158
159
160
161
                    }
                    return content
        else:
            if span['type'] == ContentType.InterlineEquation:
赵小蒙's avatar
赵小蒙 committed
162
                interline_equation = span['content']
赵小蒙's avatar
赵小蒙 committed
163
164
165
166
167
168
                content = {
                    'type': 'equation',
                    'latex': f"$$\n{interline_equation}\n$$"
                }
                return content
            elif span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
169
                inline_equation = span['content']
赵小蒙's avatar
赵小蒙 committed
170
171
172
                line_text += f"${inline_equation}$"
                inline_equation_num += 1
            elif span['type'] == ContentType.Text:
173
174
                text_content = ocr_escape_special_markdown_char(span['content'])  # 转义特殊符号
                line_text += text_content
赵小蒙's avatar
赵小蒙 committed
175
176
177
178
179
180
181
182
    content = {
        'type': 'text',
        'text': line_text,
        'inline_equation_num': inline_equation_num
    }
    return content


赵小蒙's avatar
赵小蒙 committed
183
def ocr_mk_mm_standard_format(pdf_info_dict: list):
赵小蒙's avatar
update  
赵小蒙 committed
184
    """
185
    content_list
赵小蒙's avatar
赵小蒙 committed
186
187
188
189
190
    type         string      image/text/table/equation(行间的单独拿出来,行内的和text合并)
    latex        string      latex文本字段。
    text         string      纯文本格式的文本数据。
    md           string      markdown格式的文本数据。
    img_path     string      s3://full/path/to/img.jpg
赵小蒙's avatar
update  
赵小蒙 committed
191
    """
赵小蒙's avatar
赵小蒙 committed
192
    content_list = []
赵小蒙's avatar
赵小蒙 committed
193
    for page_info in pdf_info_dict:
赵小蒙's avatar
赵小蒙 committed
194
195
196
197
198
199
200
201
        blocks = page_info.get("preproc_blocks")
        if not blocks:
            continue
        for block in blocks:
            for line in block['lines']:
                content = line_to_standard_format(line)
                content_list.append(content)
    return content_list