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

赵小蒙's avatar
赵小蒙 committed
3
from magic_pdf.libs.MakeContentConfig import DropMode, MakeMode
4
from magic_pdf.libs.commons import join_path
5
from magic_pdf.libs.language import detect_lang
赵小蒙's avatar
赵小蒙 committed
6
from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
赵小蒙's avatar
赵小蒙 committed
7
from magic_pdf.libs.ocr_content_type import ContentType, BlockType
8
9
10
11
import wordninja
import re


12
13
14
15
16
17
18
19
20
21
22
23
24
25
def __is_hyphen_at_line_end(line):
    """
    Check if a line ends with one or more letters followed by a hyphen.
    
    Args:
    line (str): The line of text to check.
    
    Returns:
    bool: True if the line ends with one or more letters followed by a hyphen, False otherwise.
    """
    # Use regex to check if the line ends with one or more letters followed by a hyphen
    return bool(re.search(r'[A-Za-z]+-\s*$', line))


26
27
28
def split_long_words(text):
    segments = text.split(' ')
    for i in range(len(segments)):
liukaiwen's avatar
liukaiwen committed
29
        words = re.findall(r'\w+|[^\w]', segments[i], re.UNICODE)
30
        for j in range(len(words)):
31
            if len(words[j]) > 10:
32
33
34
                words[j] = ' '.join(wordninja.split(words[j]))
        segments[i] = ''.join(words)
    return ' '.join(segments)
赵小蒙's avatar
赵小蒙 committed
35
36


赵小蒙's avatar
赵小蒙 committed
37
def ocr_mk_mm_markdown_with_para(pdf_info_list: list, img_buket_path):
xuchao's avatar
xuchao committed
38
    markdown = []
赵小蒙's avatar
赵小蒙 committed
39
    for page_info in pdf_info_list:
40
        paras_of_layout = page_info.get("para_blocks")
赵小蒙's avatar
赵小蒙 committed
41
        page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)
42
        markdown.extend(page_markdown)
43
    return '\n\n'.join(markdown)
44
45


赵小蒙's avatar
赵小蒙 committed
46
def ocr_mk_nlp_markdown_with_para(pdf_info_dict: list):
47
    markdown = []
赵小蒙's avatar
赵小蒙 committed
48
    for page_info in pdf_info_dict:
49
        paras_of_layout = page_info.get("para_blocks")
50
        page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "nlp")
51
52
53
        markdown.extend(page_markdown)
    return '\n\n'.join(markdown)

赵小蒙's avatar
赵小蒙 committed
54

赵小蒙's avatar
赵小蒙 committed
55
def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list, img_buket_path):
56
    markdown_with_para_and_pagination = []
赵小蒙's avatar
赵小蒙 committed
57
58
    page_no = 0
    for page_info in pdf_info_dict:
59
60
        paras_of_layout = page_info.get("para_blocks")
        if not paras_of_layout:
61
            continue
62
        page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)
63
64
        markdown_with_para_and_pagination.append({
            'page_no': page_no,
65
            'md_content': '\n\n'.join(page_markdown)
66
        })
赵小蒙's avatar
赵小蒙 committed
67
        page_no += 1
68
69
70
    return markdown_with_para_and_pagination


赵小蒙's avatar
赵小蒙 committed
71
def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=""):
72
73
74
75
76
77
78
    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')
79
                    content = ''
80
                    language = ''
81
                    if span_type == ContentType.Text:
82
83
84
85
86
87
                        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)
88
                    elif span_type == ContentType.InlineEquation:
89
                        content = f"${span['content']}$"
90
                    elif span_type == ContentType.InterlineEquation:
91
                        content = f"\n$$\n{span['content']}\n$$\n"
92
                    elif span_type in [ContentType.Image, ContentType.Table]:
93
                        if mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
94
                            content = f"\n![]({join_path(img_buket_path, span['image_path'])})\n"
95
96
                        elif mode == 'nlp':
                            pass
97
                    if content != '':
98
99
100
101
                        if language == 'en':  # 英文语境下 content间需要空格分隔
                            para_text += content + ' '
                        else:  # 中文语境下,content间不需要空格分隔
                            para_text += content
102
103
104
105
            if para_text.strip() == '':
                continue
            else:
                page_markdown.append(para_text.strip() + '  ')
106
107
108
    return page_markdown


赵小蒙's avatar
赵小蒙 committed
109
110
def ocr_mk_markdown_with_para_core_v2(paras_of_layout, mode, img_buket_path=""):
    page_markdown = []
111
    for para_block in paras_of_layout:
赵小蒙's avatar
赵小蒙 committed
112
        para_text = ''
赵小蒙's avatar
赵小蒙 committed
113
        para_type = para_block['type']
114
115
116
117
118
119
120
121
        if para_type == BlockType.Text:
            para_text = merge_para_with_text(para_block)
        elif para_type == BlockType.Title:
            para_text = f"# {merge_para_with_text(para_block)}"
        elif para_type == BlockType.InterlineEquation:
            para_text = merge_para_with_text(para_block)
        elif para_type == BlockType.Image:
            if mode == 'nlp':
赵小蒙's avatar
赵小蒙 committed
122
                continue
123
            elif mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
124
                for block in para_block['blocks']:  # 1st.拼image_body
赵小蒙's avatar
赵小蒙 committed
125
126
                    if block['type'] == BlockType.ImageBody:
                        for line in block['lines']:
127
                            for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
128
                                if span['type'] == ContentType.Image:
129
                                    para_text += f"\n![]({join_path(img_buket_path, span['image_path'])})  \n"
赵小蒙's avatar
赵小蒙 committed
130
                for block in para_block['blocks']:  # 2nd.拼image_caption
赵小蒙's avatar
赵小蒙 committed
131
132
                    if block['type'] == BlockType.ImageCaption:
                        para_text += merge_para_with_text(block)
133
134
135
136
        elif para_type == BlockType.Table:
            if mode == 'nlp':
                continue
            elif mode == 'mm':
137
                table_caption = ''
赵小蒙's avatar
赵小蒙 committed
138
139
                for block in para_block['blocks']:  # 1st.拼table_caption
                    if block['type'] == BlockType.TableCaption:
140
                        para_text += merge_para_with_text(block)
赵小蒙's avatar
赵小蒙 committed
141
                for block in para_block['blocks']:  # 2nd.拼table_body
赵小蒙's avatar
赵小蒙 committed
142
143
                    if block['type'] == BlockType.TableBody:
                        for line in block['lines']:
144
                            for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
145
                                if span['type'] == ContentType.Table:
146
147
148
                                    # if processed by table model
                                    if span.get('latex', ''):
                                        para_text += f"\n\n$\n {span['latex']}\n$\n\n"
149
150
                                    elif span.get('html', ''):
                                        para_text += f"\n\n{span['html']}\n\n"
151
                                    else:
152
                                        para_text += f"\n![]({join_path(img_buket_path, span['image_path'])})  \n"
赵小蒙's avatar
赵小蒙 committed
153
154
                for block in para_block['blocks']:  # 3rd.拼table_footnote
                    if block['type'] == BlockType.TableFootnote:
赵小蒙's avatar
赵小蒙 committed
155
                        para_text += merge_para_with_text(block)
156
157
158
159
160

        if para_text.strip() == '':
            continue
        else:
            page_markdown.append(para_text.strip() + '  ')
赵小蒙's avatar
赵小蒙 committed
161
162
163
164

    return page_markdown


赵小蒙's avatar
赵小蒙 committed
165
def merge_para_with_text(para_block):
166
167
168
169
170
171
172
173
174
175
176
177
    def detect_language(text):
        en_pattern = r'[a-zA-Z]+'
        en_matches = re.findall(en_pattern, text)
        en_length = sum(len(match) for match in en_matches)
        if len(text) > 0:
            if en_length / len(text) >= 0.5:
                return 'en'
            else:
                return "unknown"
        else:
            return "empty"

赵小蒙's avatar
赵小蒙 committed
178
    para_text = ''
赵小蒙's avatar
赵小蒙 committed
179
    for line in para_block['lines']:
180
181
182
183
184
185
186
187
        line_text = ""
        line_lang = ""
        for span in line['spans']:
            span_type = span['type']
            if span_type == ContentType.Text:
                line_text += span['content'].strip()
        if line_text != "":
            line_lang = detect_lang(line_text)
赵小蒙's avatar
赵小蒙 committed
188
        for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
189
            span_type = span['type']
赵小蒙's avatar
赵小蒙 committed
190
191
192
            content = ''
            if span_type == ContentType.Text:
                content = span['content']
193
194
                # language = detect_lang(content)
                language = detect_language(content)
赵小蒙's avatar
赵小蒙 committed
195
196
197
198
199
                if language == 'en':  # 只对英文长词进行分词处理,中文分词会丢失文本
                    content = ocr_escape_special_markdown_char(split_long_words(content))
                else:
                    content = ocr_escape_special_markdown_char(content)
            elif span_type == ContentType.InlineEquation:
200
                content = f" ${span['content']}$ "
赵小蒙's avatar
赵小蒙 committed
201
202
            elif span_type == ContentType.InterlineEquation:
                content = f"\n$$\n{span['content']}\n$$\n"
203

赵小蒙's avatar
赵小蒙 committed
204
            if content != '':
205
206
207
                langs = ['zh', 'ja', 'ko']
                if line_lang in langs:  # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断
                    para_text += content  # 中文/日语/韩文语境下,content间不需要空格分隔
208
209
                elif line_lang == 'en':
                    # 如果是前一行带有-连字符,那么末尾不应该加空格
drunkpig's avatar
drunkpig committed
210
211
                    if __is_hyphen_at_line_end(content):
                        para_text += content[:-1]
212
213
                    else:
                        para_text += content + ' '
214
                else:
215
                    para_text += content + ' '  # 西方文本语境下 content间需要空格分隔
赵小蒙's avatar
赵小蒙 committed
216
217
218
    return para_text


219
def para_to_standard_format(para, img_buket_path):
220
221
    para_content = {}
    if len(para) == 1:
222
        para_content = line_to_standard_format(para[0], img_buket_path)
223
224
225
226
227
    elif len(para) > 1:
        para_text = ''
        inline_equation_num = 0
        for line in para:
            for span in line['spans']:
228
                language = ''
229
                span_type = span.get('type')
赵小蒙's avatar
赵小蒙 committed
230
                content = ""
231
                if span_type == ContentType.Text:
232
233
234
235
236
237
                    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)
238
                elif span_type == ContentType.InlineEquation:
239
                    content = f"${span['content']}$"
240
                    inline_equation_num += 1
241
242
243
244
                if language == 'en':  # 英文语境下 content间需要空格分隔
                    para_text += content + ' '
                else:  # 中文语境下,content间不需要空格分隔
                    para_text += content
245
246
247
248
249
250
251
        para_content = {
            'type': 'text',
            'text': para_text,
            'inline_equation_num': inline_equation_num
        }
    return para_content

赵小蒙's avatar
赵小蒙 committed
252

253
def para_to_standard_format_v2(para_block, img_buket_path, page_idx):
赵小蒙's avatar
赵小蒙 committed
254
255
256
257
258
    para_type = para_block['type']
    if para_type == BlockType.Text:
        para_content = {
            'type': 'text',
            'text': merge_para_with_text(para_block),
259
            'page_idx': page_idx
赵小蒙's avatar
赵小蒙 committed
260
261
262
263
264
        }
    elif para_type == BlockType.Title:
        para_content = {
            'type': 'text',
            'text': merge_para_with_text(para_block),
265
266
            'text_level': 1,
            'page_idx': page_idx
赵小蒙's avatar
赵小蒙 committed
267
268
269
270
271
        }
    elif para_type == BlockType.InterlineEquation:
        para_content = {
            'type': 'equation',
            'text': merge_para_with_text(para_block),
272
273
            'text_format': "latex",
            'page_idx': page_idx
赵小蒙's avatar
赵小蒙 committed
274
275
276
277
        }
    elif para_type == BlockType.Image:
        para_content = {
            'type': 'image',
278
            'page_idx': page_idx
赵小蒙's avatar
赵小蒙 committed
279
280
281
282
283
284
285
286
287
        }
        for block in para_block['blocks']:
            if block['type'] == BlockType.ImageBody:
                para_content['img_path'] = join_path(img_buket_path, block["lines"][0]["spans"][0]['image_path'])
            if block['type'] == BlockType.ImageCaption:
                para_content['img_caption'] = merge_para_with_text(block)
    elif para_type == BlockType.Table:
        para_content = {
            'type': 'table',
288
            'page_idx': page_idx
赵小蒙's avatar
赵小蒙 committed
289
290
291
        }
        for block in para_block['blocks']:
            if block['type'] == BlockType.TableBody:
292
                if block["lines"][0]["spans"][0].get('latex', ''):
liukaiwen's avatar
liukaiwen committed
293
                    para_content['table_body'] = f"\n\n$\n {block['lines'][0]['spans'][0]['latex']}\n$\n\n"
294
295
                elif block["lines"][0]["spans"][0].get('html', ''):
                    para_content['table_body'] = f"\n\n{block['lines'][0]['spans'][0]['html']}\n\n"
赵小蒙's avatar
赵小蒙 committed
296
297
298
299
300
301
302
303
304
                para_content['img_path'] = join_path(img_buket_path, block["lines"][0]["spans"][0]['image_path'])
            if block['type'] == BlockType.TableCaption:
                para_content['table_caption'] = merge_para_with_text(block)
            if block['type'] == BlockType.TableFootnote:
                para_content['table_footnote'] = merge_para_with_text(block)

    return para_content


赵小蒙's avatar
赵小蒙 committed
305
def make_standard_format_with_para(pdf_info_dict: list, img_buket_path: str):
赵小蒙's avatar
赵小蒙 committed
306
    content_list = []
赵小蒙's avatar
赵小蒙 committed
307
    for page_info in pdf_info_dict:
308
309
        paras_of_layout = page_info.get("para_blocks")
        if not paras_of_layout:
赵小蒙's avatar
赵小蒙 committed
310
            continue
赵小蒙's avatar
赵小蒙 committed
311
312
313
        for para_block in paras_of_layout:
            para_content = para_to_standard_format_v2(para_block, img_buket_path)
            content_list.append(para_content)
赵小蒙's avatar
赵小蒙 committed
314
315
316
    return content_list


317
def line_to_standard_format(line, img_buket_path):
赵小蒙's avatar
赵小蒙 committed
318
319
320
321
322
323
324
325
326
327
    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',
328
                        'img_path': join_path(img_buket_path, span['image_path'])
赵小蒙's avatar
赵小蒙 committed
329
330
331
332
333
                    }
                    return content
                elif span['type'] == ContentType.Table:
                    content = {
                        'type': 'table',
334
                        'img_path': join_path(img_buket_path, span['image_path'])
赵小蒙's avatar
赵小蒙 committed
335
336
337
338
                    }
                    return content
        else:
            if span['type'] == ContentType.InterlineEquation:
赵小蒙's avatar
赵小蒙 committed
339
                interline_equation = span['content']
赵小蒙's avatar
赵小蒙 committed
340
341
342
343
344
345
                content = {
                    'type': 'equation',
                    'latex': f"$$\n{interline_equation}\n$$"
                }
                return content
            elif span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
346
                inline_equation = span['content']
赵小蒙's avatar
赵小蒙 committed
347
348
349
                line_text += f"${inline_equation}$"
                inline_equation_num += 1
            elif span['type'] == ContentType.Text:
350
351
                text_content = ocr_escape_special_markdown_char(span['content'])  # 转义特殊符号
                line_text += text_content
赵小蒙's avatar
赵小蒙 committed
352
353
354
355
356
357
358
359
    content = {
        'type': 'text',
        'text': line_text,
        'inline_equation_num': inline_equation_num
    }
    return content


赵小蒙's avatar
赵小蒙 committed
360
def ocr_mk_mm_standard_format(pdf_info_dict: list):
赵小蒙's avatar
update  
赵小蒙 committed
361
    """
362
    content_list
赵小蒙's avatar
赵小蒙 committed
363
364
365
366
367
    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
368
    """
赵小蒙's avatar
赵小蒙 committed
369
    content_list = []
赵小蒙's avatar
赵小蒙 committed
370
    for page_info in pdf_info_dict:
赵小蒙's avatar
赵小蒙 committed
371
372
373
374
375
376
377
378
        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
赵小蒙's avatar
赵小蒙 committed
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396


def union_make(pdf_info_dict: list, make_mode: str, drop_mode: str, img_buket_path: str = ""):
    output_content = []
    for page_info in pdf_info_dict:
        if page_info.get("need_drop", False):
            drop_reason = page_info.get("drop_reason")
            if drop_mode == DropMode.NONE:
                pass
            elif drop_mode == DropMode.WHOLE_PDF:
                raise Exception(f"drop_mode is {DropMode.WHOLE_PDF} , drop_reason is {drop_reason}")
            elif drop_mode == DropMode.SINGLE_PAGE:
                logger.warning(f"drop_mode is {DropMode.SINGLE_PAGE} , drop_reason is {drop_reason}")
                continue
            else:
                raise Exception(f"drop_mode can not be null")

        paras_of_layout = page_info.get("para_blocks")
397
        page_idx = page_info.get("page_idx")
赵小蒙's avatar
赵小蒙 committed
398
399
400
401
402
403
404
405
406
407
        if not paras_of_layout:
            continue
        if make_mode == MakeMode.MM_MD:
            page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "mm", img_buket_path)
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.NLP_MD:
            page_markdown = ocr_mk_markdown_with_para_core_v2(paras_of_layout, "nlp")
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.STANDARD_FORMAT:
            for para_block in paras_of_layout:
408
                para_content = para_to_standard_format_v2(para_block, img_buket_path, page_idx)
赵小蒙's avatar
赵小蒙 committed
409
410
411
412
413
                output_content.append(para_content)
    if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
        return '\n\n'.join(output_content)
    elif make_mode == MakeMode.STANDARD_FORMAT:
        return output_content