ocr_mkcontent.py 19.2 KB
Newer Older
1
2
3
import re

import wordninja
赵小蒙's avatar
赵小蒙 committed
4
5
from loguru import logger

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


13
14
15
16
17
18
19
20
21
22
23
24
25
26
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))


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


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


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

赵小蒙's avatar
赵小蒙 committed
57

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


78
def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path=''):
79
80
81
82
83
84
85
    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')
86
                    content = ''
87
                    language = ''
88
                    if span_type == ContentType.Text:
89
90
                        content = span['content']
                        language = detect_lang(content)
91
92
93
                        if (language == 'en'):  # 只对英文长词进行分词处理,中文分词会丢失文本
                            content = ocr_escape_special_markdown_char(
                                split_long_words(content))
94
95
                        else:
                            content = ocr_escape_special_markdown_char(content)
96
                    elif span_type == ContentType.InlineEquation:
97
                        content = f"${span['content']}$"
98
                    elif span_type == ContentType.InterlineEquation:
99
                        content = f"\n$$\n{span['content']}\n$$\n"
100
                    elif span_type in [ContentType.Image, ContentType.Table]:
101
                        if mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
102
                            content = f"\n![]({join_path(img_buket_path, span['image_path'])})\n"
103
104
                        elif mode == 'nlp':
                            pass
105
                    if content != '':
106
107
108
109
                        if language == 'en':  # 英文语境下 content间需要空格分隔
                            para_text += content + ' '
                        else:  # 中文语境下,content间不需要空格分隔
                            para_text += content
110
111
112
113
            if para_text.strip() == '':
                continue
            else:
                page_markdown.append(para_text.strip() + '  ')
114
115
116
    return page_markdown


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

        if para_text.strip() == '':
            continue
        else:
            page_markdown.append(para_text.strip() + '  ')
赵小蒙's avatar
赵小蒙 committed
176
177
178
179

    return page_markdown


180
def merge_para_with_text(para_block, parse_type="auto", lang=None):
181

182
183
184
185
186
187
188
189
    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:
190
                return 'unknown'
191
        else:
192
            return 'empty'
193

赵小蒙's avatar
赵小蒙 committed
194
    para_text = ''
赵小蒙's avatar
赵小蒙 committed
195
    for line in para_block['lines']:
196
197
        line_text = ''
        line_lang = ''
198
199
200
201
        for span in line['spans']:
            span_type = span['type']
            if span_type == ContentType.Text:
                line_text += span['content'].strip()
202
        if line_text != '':
203
            line_lang = detect_lang(line_text)
赵小蒙's avatar
赵小蒙 committed
204
        for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
205
            span_type = span['type']
赵小蒙's avatar
赵小蒙 committed
206
207
208
            content = ''
            if span_type == ContentType.Text:
                content = span['content']
209
210
                # language = detect_lang(content)
                language = detect_language(content)
211
212
                # 判断是否小语种
                if lang is not None and lang != 'en':
赵小蒙's avatar
赵小蒙 committed
213
                    content = ocr_escape_special_markdown_char(content)
214
215
216
217
218
219
                else:  # 非小语种逻辑
                    if language == 'en' and parse_type == 'ocr':  # 只对英文长词进行分词处理,中文分词会丢失文本
                        content = ocr_escape_special_markdown_char(
                            split_long_words(content))
                    else:
                        content = ocr_escape_special_markdown_char(content)
赵小蒙's avatar
赵小蒙 committed
220
            elif span_type == ContentType.InlineEquation:
221
                content = f" ${span['content']}$ "
赵小蒙's avatar
赵小蒙 committed
222
223
            elif span_type == ContentType.InterlineEquation:
                content = f"\n$$\n{span['content']}\n$$\n"
224

赵小蒙's avatar
赵小蒙 committed
225
            if content != '':
226
227
228
                langs = ['zh', 'ja', 'ko']
                if line_lang in langs:  # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断
                    para_text += content  # 中文/日语/韩文语境下,content间不需要空格分隔
229
230
                elif line_lang == 'en':
                    # 如果是前一行带有-连字符,那么末尾不应该加空格
drunkpig's avatar
drunkpig committed
231
232
                    if __is_hyphen_at_line_end(content):
                        para_text += content[:-1]
233
234
                    else:
                        para_text += content + ' '
235
                else:
236
                    para_text += content + ' '  # 西方文本语境下 content间需要空格分隔
赵小蒙's avatar
赵小蒙 committed
237
238
239
    return para_text


240
def para_to_standard_format(para, img_buket_path):
241
242
    para_content = {}
    if len(para) == 1:
243
        para_content = line_to_standard_format(para[0], img_buket_path)
244
245
246
247
248
    elif len(para) > 1:
        para_text = ''
        inline_equation_num = 0
        for line in para:
            for span in line['spans']:
249
                language = ''
250
                span_type = span.get('type')
251
                content = ''
252
                if span_type == ContentType.Text:
253
254
255
                    content = span['content']
                    language = detect_lang(content)
                    if language == 'en':  # 只对英文长词进行分词处理,中文分词会丢失文本
256
257
                        content = ocr_escape_special_markdown_char(
                            split_long_words(content))
258
259
                    else:
                        content = ocr_escape_special_markdown_char(content)
260
                elif span_type == ContentType.InlineEquation:
261
                    content = f"${span['content']}$"
262
                    inline_equation_num += 1
263
264
265
266
                if language == 'en':  # 英文语境下 content间需要空格分隔
                    para_text += content + ' '
                else:  # 中文语境下,content间不需要空格分隔
                    para_text += content
267
268
269
        para_content = {
            'type': 'text',
            'text': para_text,
270
            'inline_equation_num': inline_equation_num,
271
272
273
        }
    return para_content

赵小蒙's avatar
赵小蒙 committed
274

275
def para_to_standard_format_v2(para_block, img_buket_path, page_idx, parse_type="auto", lang=None):
赵小蒙's avatar
赵小蒙 committed
276
277
278
279
    para_type = para_block['type']
    if para_type == BlockType.Text:
        para_content = {
            'type': 'text',
280
            'text': merge_para_with_text(para_block, parse_type=parse_type, lang=lang),
281
            'page_idx': page_idx,
赵小蒙's avatar
赵小蒙 committed
282
283
284
285
        }
    elif para_type == BlockType.Title:
        para_content = {
            'type': 'text',
286
            'text': merge_para_with_text(para_block, parse_type=parse_type, lang=lang),
287
            'text_level': 1,
288
            'page_idx': page_idx,
赵小蒙's avatar
赵小蒙 committed
289
290
291
292
        }
    elif para_type == BlockType.InterlineEquation:
        para_content = {
            'type': 'equation',
293
            'text': merge_para_with_text(para_block, parse_type=parse_type, lang=lang),
294
295
            'text_format': 'latex',
            'page_idx': page_idx,
赵小蒙's avatar
赵小蒙 committed
296
297
        }
    elif para_type == BlockType.Image:
298
        para_content = {'type': 'image', 'page_idx': page_idx}
赵小蒙's avatar
赵小蒙 committed
299
300
        for block in para_block['blocks']:
            if block['type'] == BlockType.ImageBody:
301
302
303
                para_content['img_path'] = join_path(
                    img_buket_path,
                    block['lines'][0]['spans'][0]['image_path'])
赵小蒙's avatar
赵小蒙 committed
304
            if block['type'] == BlockType.ImageCaption:
305
                para_content['img_caption'] = merge_para_with_text(block, parse_type=parse_type, lang=lang)
306
            if block['type'] == BlockType.ImageFootnote:
307
                para_content['img_footnote'] = merge_para_with_text(block, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
308
    elif para_type == BlockType.Table:
309
        para_content = {'type': 'table', 'page_idx': page_idx}
赵小蒙's avatar
赵小蒙 committed
310
311
        for block in para_block['blocks']:
            if block['type'] == BlockType.TableBody:
312
                if block["lines"][0]["spans"][0].get('latex', ''):
liukaiwen's avatar
liukaiwen committed
313
                    para_content['table_body'] = f"\n\n$\n {block['lines'][0]['spans'][0]['latex']}\n$\n\n"
314
315
                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
316
317
                para_content['img_path'] = join_path(img_buket_path, block["lines"][0]["spans"][0]['image_path'])
            if block['type'] == BlockType.TableCaption:
318
                para_content['table_caption'] = merge_para_with_text(block, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
319
            if block['type'] == BlockType.TableFootnote:
320
                para_content['table_footnote'] = merge_para_with_text(block, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
321
322
323
324

    return para_content


赵小蒙's avatar
赵小蒙 committed
325
def make_standard_format_with_para(pdf_info_dict: list, img_buket_path: str):
赵小蒙's avatar
赵小蒙 committed
326
    content_list = []
赵小蒙's avatar
赵小蒙 committed
327
    for page_info in pdf_info_dict:
328
        paras_of_layout = page_info.get('para_blocks')
329
        if not paras_of_layout:
赵小蒙's avatar
赵小蒙 committed
330
            continue
赵小蒙's avatar
赵小蒙 committed
331
        for para_block in paras_of_layout:
332
333
            para_content = para_to_standard_format_v2(para_block,
                                                      img_buket_path)
赵小蒙's avatar
赵小蒙 committed
334
            content_list.append(para_content)
赵小蒙's avatar
赵小蒙 committed
335
336
337
    return content_list


338
def line_to_standard_format(line, img_buket_path):
339
    line_text = ''
赵小蒙's avatar
赵小蒙 committed
340
341
342
343
344
345
346
347
348
    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',
349
350
                        'img_path': join_path(img_buket_path,
                                              span['image_path']),
赵小蒙's avatar
赵小蒙 committed
351
352
353
354
355
                    }
                    return content
                elif span['type'] == ContentType.Table:
                    content = {
                        'type': 'table',
356
357
                        'img_path': join_path(img_buket_path,
                                              span['image_path']),
赵小蒙's avatar
赵小蒙 committed
358
359
360
361
                    }
                    return content
        else:
            if span['type'] == ContentType.InterlineEquation:
赵小蒙's avatar
赵小蒙 committed
362
                interline_equation = span['content']
赵小蒙's avatar
赵小蒙 committed
363
364
                content = {
                    'type': 'equation',
365
                    'latex': f'$$\n{interline_equation}\n$$'
赵小蒙's avatar
赵小蒙 committed
366
367
368
                }
                return content
            elif span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
369
                inline_equation = span['content']
370
                line_text += f'${inline_equation}$'
赵小蒙's avatar
赵小蒙 committed
371
372
                inline_equation_num += 1
            elif span['type'] == ContentType.Text:
373
374
                text_content = ocr_escape_special_markdown_char(
                    span['content'])  # 转义特殊符号
375
                line_text += text_content
赵小蒙's avatar
赵小蒙 committed
376
377
378
    content = {
        'type': 'text',
        'text': line_text,
379
        'inline_equation_num': inline_equation_num,
赵小蒙's avatar
赵小蒙 committed
380
381
382
383
    }
    return content


赵小蒙's avatar
赵小蒙 committed
384
def ocr_mk_mm_standard_format(pdf_info_dict: list):
385
386
387
388
    """content_list 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
赵小蒙 committed
389
    content_list = []
赵小蒙's avatar
赵小蒙 committed
390
    for page_info in pdf_info_dict:
391
        blocks = page_info.get('preproc_blocks')
赵小蒙's avatar
赵小蒙 committed
392
393
394
395
396
397
398
        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
399
400


401
402
403
def union_make(pdf_info_dict: list,
               make_mode: str,
               drop_mode: str,
404
405
406
               img_buket_path: str = '',
               parse_type: str = "auto",
               lang=None):
赵小蒙's avatar
赵小蒙 committed
407
408
    output_content = []
    for page_info in pdf_info_dict:
409
410
        if page_info.get('need_drop', False):
            drop_reason = page_info.get('drop_reason')
赵小蒙's avatar
赵小蒙 committed
411
412
413
            if drop_mode == DropMode.NONE:
                pass
            elif drop_mode == DropMode.WHOLE_PDF:
414
415
                raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
                                 f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
416
            elif drop_mode == DropMode.SINGLE_PAGE:
417
418
                logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
                                f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
419
420
                continue
            else:
421
                raise Exception('drop_mode can not be null')
赵小蒙's avatar
赵小蒙 committed
422

423
424
        paras_of_layout = page_info.get('para_blocks')
        page_idx = page_info.get('page_idx')
赵小蒙's avatar
赵小蒙 committed
425
426
427
        if not paras_of_layout:
            continue
        if make_mode == MakeMode.MM_MD:
428
            page_markdown = ocr_mk_markdown_with_para_core_v2(
429
                paras_of_layout, 'mm', img_buket_path, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
430
431
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.NLP_MD:
432
            page_markdown = ocr_mk_markdown_with_para_core_v2(
433
                paras_of_layout, 'nlp', parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
434
435
436
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.STANDARD_FORMAT:
            for para_block in paras_of_layout:
437
                para_content = para_to_standard_format_v2(
438
                    para_block, img_buket_path, page_idx, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
439
440
441
442
443
                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