ocr_mkcontent.py 11.9 KB
Newer Older
1
2
import re

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

5
from magic_pdf.libs.commons import join_path
6
from magic_pdf.libs.language import detect_lang
7
from magic_pdf.libs.MakeContentConfig import DropMode, MakeMode
赵小蒙's avatar
赵小蒙 committed
8
from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
9
from magic_pdf.libs.ocr_content_type import BlockType, ContentType
10
from magic_pdf.para.para_split_v3 import ListLineTag
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
def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list,
                                                img_buket_path):
29
    markdown_with_para_and_pagination = []
赵小蒙's avatar
赵小蒙 committed
30
31
    page_no = 0
    for page_info in pdf_info_dict:
32
        paras_of_layout = page_info.get('para_blocks')
33
        if not paras_of_layout:
34
            continue
35
36
        page_markdown = ocr_mk_markdown_with_para_core_v2(
            paras_of_layout, 'mm', img_buket_path)
37
        markdown_with_para_and_pagination.append({
38
39
40
41
            'page_no':
            page_no,
            'md_content':
            '\n\n'.join(page_markdown)
42
        })
赵小蒙's avatar
赵小蒙 committed
43
        page_no += 1
44
45
46
    return markdown_with_para_and_pagination


47
48
def ocr_mk_markdown_with_para_core_v2(paras_of_layout,
                                      mode,
49
50
51
52
                                      img_buket_path='',
                                      parse_type="auto",
                                      lang=None
                                      ):
赵小蒙's avatar
赵小蒙 committed
53
    page_markdown = []
54
    for para_block in paras_of_layout:
赵小蒙's avatar
赵小蒙 committed
55
        para_text = ''
赵小蒙's avatar
赵小蒙 committed
56
        para_type = para_block['type']
57
        if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
58
            para_text = merge_para_with_text(para_block, parse_type=parse_type, lang=lang)
59
        elif para_type == BlockType.Title:
60
            para_text = f'# {merge_para_with_text(para_block, parse_type=parse_type, lang=lang)}'
61
        elif para_type == BlockType.InterlineEquation:
62
            para_text = merge_para_with_text(para_block, parse_type=parse_type, lang=lang)
63
64
        elif para_type == BlockType.Image:
            if mode == 'nlp':
赵小蒙's avatar
赵小蒙 committed
65
                continue
66
            elif mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
67
                for block in para_block['blocks']:  # 1st.拼image_body
赵小蒙's avatar
赵小蒙 committed
68
69
                    if block['type'] == BlockType.ImageBody:
                        for line in block['lines']:
70
                            for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
71
                                if span['type'] == ContentType.Image:
72
                                    para_text += f"\n![]({join_path(img_buket_path, span['image_path'])})  \n"
赵小蒙's avatar
赵小蒙 committed
73
                for block in para_block['blocks']:  # 2nd.拼image_caption
赵小蒙's avatar
赵小蒙 committed
74
                    if block['type'] == BlockType.ImageCaption:
75
                        para_text += merge_para_with_text(block, parse_type=parse_type, lang=lang)
76
77
                for block in para_block['blocks']:  # 2nd.拼image_caption
                    if block['type'] == BlockType.ImageFootnote:
78
                        para_text += merge_para_with_text(block, parse_type=parse_type, lang=lang)
79
80
81
82
        elif para_type == BlockType.Table:
            if mode == 'nlp':
                continue
            elif mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
83
84
                for block in para_block['blocks']:  # 1st.拼table_caption
                    if block['type'] == BlockType.TableCaption:
85
                        para_text += merge_para_with_text(block, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
86
                for block in para_block['blocks']:  # 2nd.拼table_body
赵小蒙's avatar
赵小蒙 committed
87
88
                    if block['type'] == BlockType.TableBody:
                        for line in block['lines']:
89
                            for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
90
                                if span['type'] == ContentType.Table:
91
92
93
                                    # if processed by table model
                                    if span.get('latex', ''):
                                        para_text += f"\n\n$\n {span['latex']}\n$\n\n"
94
95
                                    elif span.get('html', ''):
                                        para_text += f"\n\n{span['html']}\n\n"
96
                                    else:
97
                                        para_text += f"\n![]({join_path(img_buket_path, span['image_path'])})  \n"
赵小蒙's avatar
赵小蒙 committed
98
99
                for block in para_block['blocks']:  # 3rd.拼table_footnote
                    if block['type'] == BlockType.TableFootnote:
100
                        para_text += merge_para_with_text(block, parse_type=parse_type, lang=lang)
101
102
103
104
105

        if para_text.strip() == '':
            continue
        else:
            page_markdown.append(para_text.strip() + '  ')
赵小蒙's avatar
赵小蒙 committed
106
107
108
109

    return page_markdown


110
111
112
113
114
115
116
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'
117
        else:
118
119
120
121
            return 'unknown'
    else:
        return 'empty'

122

123
def merge_para_with_text(para_block, parse_type="auto", lang=None):
赵小蒙's avatar
赵小蒙 committed
124
    para_text = ''
125
126
127
128
129
    for i, line in enumerate(para_block['lines']):

        if i >= 1 and line.get(ListLineTag.IS_LIST_START_LINE, False):
            para_text += '  \n'

130
131
        line_text = ''
        line_lang = ''
132
133
134
135
        for span in line['spans']:
            span_type = span['type']
            if span_type == ContentType.Text:
                line_text += span['content'].strip()
136
        if line_text != '':
137
            line_lang = detect_lang(line_text)
赵小蒙's avatar
赵小蒙 committed
138
        for span in line['spans']:
139

赵小蒙's avatar
赵小蒙 committed
140
            span_type = span['type']
赵小蒙's avatar
赵小蒙 committed
141
142
            content = ''
            if span_type == ContentType.Text:
143
                content = ocr_escape_special_markdown_char(span['content'])
赵小蒙's avatar
赵小蒙 committed
144
            elif span_type == ContentType.InlineEquation:
145
                content = f" ${span['content']}$ "
赵小蒙's avatar
赵小蒙 committed
146
147
            elif span_type == ContentType.InterlineEquation:
                content = f"\n$$\n{span['content']}\n$$\n"
148

赵小蒙's avatar
赵小蒙 committed
149
            if content != '':
150
151
152
                langs = ['zh', 'ja', 'ko']
                if line_lang in langs:  # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断
                    para_text += content  # 中文/日语/韩文语境下,content间不需要空格分隔
153
154
                elif line_lang == 'en':
                    # 如果是前一行带有-连字符,那么末尾不应该加空格
drunkpig's avatar
drunkpig committed
155
156
                    if __is_hyphen_at_line_end(content):
                        para_text += content[:-1]
157
158
                    else:
                        para_text += content + ' '
159
                else:
160
                    para_text += content + ' '  # 西方文本语境下 content间需要空格分隔
赵小蒙's avatar
赵小蒙 committed
161
162
163
    return para_text


164
def para_to_standard_format_v2(para_block, img_buket_path, page_idx, parse_type="auto", lang=None, drop_reason=None):
赵小蒙's avatar
赵小蒙 committed
165
    para_type = para_block['type']
166
    para_content = {}
赵小蒙's avatar
赵小蒙 committed
167
168
169
    if para_type == BlockType.Text:
        para_content = {
            'type': 'text',
170
            'text': merge_para_with_text(para_block, parse_type=parse_type, lang=lang),
赵小蒙's avatar
赵小蒙 committed
171
172
173
174
        }
    elif para_type == BlockType.Title:
        para_content = {
            'type': 'text',
175
            'text': merge_para_with_text(para_block, parse_type=parse_type, lang=lang),
176
            'text_level': 1,
赵小蒙's avatar
赵小蒙 committed
177
178
179
180
        }
    elif para_type == BlockType.InterlineEquation:
        para_content = {
            'type': 'equation',
181
            'text': merge_para_with_text(para_block, parse_type=parse_type, lang=lang),
182
            'text_format': 'latex',
赵小蒙's avatar
赵小蒙 committed
183
184
        }
    elif para_type == BlockType.Image:
185
        para_content = {'type': 'image'}
赵小蒙's avatar
赵小蒙 committed
186
187
        for block in para_block['blocks']:
            if block['type'] == BlockType.ImageBody:
188
189
190
                para_content['img_path'] = join_path(
                    img_buket_path,
                    block['lines'][0]['spans'][0]['image_path'])
赵小蒙's avatar
赵小蒙 committed
191
            if block['type'] == BlockType.ImageCaption:
192
                para_content['img_caption'] = merge_para_with_text(block, parse_type=parse_type, lang=lang)
193
            if block['type'] == BlockType.ImageFootnote:
194
                para_content['img_footnote'] = merge_para_with_text(block, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
195
    elif para_type == BlockType.Table:
196
        para_content = {'type': 'table'}
赵小蒙's avatar
赵小蒙 committed
197
198
        for block in para_block['blocks']:
            if block['type'] == BlockType.TableBody:
199
                if block["lines"][0]["spans"][0].get('latex', ''):
liukaiwen's avatar
liukaiwen committed
200
                    para_content['table_body'] = f"\n\n$\n {block['lines'][0]['spans'][0]['latex']}\n$\n\n"
201
202
                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
203
204
                para_content['img_path'] = join_path(img_buket_path, block["lines"][0]["spans"][0]['image_path'])
            if block['type'] == BlockType.TableCaption:
205
                para_content['table_caption'] = merge_para_with_text(block, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
206
            if block['type'] == BlockType.TableFootnote:
207
                para_content['table_footnote'] = merge_para_with_text(block, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
208

209
210
211
212
213
    para_content['page_idx'] = page_idx

    if drop_reason is not None:
        para_content['drop_reason'] = drop_reason

赵小蒙's avatar
赵小蒙 committed
214
215
216
    return para_content


217
218
219
def union_make(pdf_info_dict: list,
               make_mode: str,
               drop_mode: str,
220
221
222
               img_buket_path: str = '',
               parse_type: str = "auto",
               lang=None):
赵小蒙's avatar
赵小蒙 committed
223
224
    output_content = []
    for page_info in pdf_info_dict:
225
226
        drop_reason_flag = False
        drop_reason = None
227
        if page_info.get('need_drop', False):
228
229
            drop_reason = page_info.get('drop_reason')
            if drop_mode == DropMode.NONE:
赵小蒙's avatar
赵小蒙 committed
230
                pass
231
232
            elif drop_mode == DropMode.NONE_WITH_REASON:
                drop_reason_flag = True
赵小蒙's avatar
赵小蒙 committed
233
            elif drop_mode == DropMode.WHOLE_PDF:
234
235
                raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
                                 f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
236
            elif drop_mode == DropMode.SINGLE_PAGE:
237
238
                logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
                                f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
239
240
                continue
            else:
241
                raise Exception('drop_mode can not be null')
赵小蒙's avatar
赵小蒙 committed
242

243
244
        paras_of_layout = page_info.get('para_blocks')
        page_idx = page_info.get('page_idx')
赵小蒙's avatar
赵小蒙 committed
245
246
247
        if not paras_of_layout:
            continue
        if make_mode == MakeMode.MM_MD:
248
            page_markdown = ocr_mk_markdown_with_para_core_v2(
249
                paras_of_layout, 'mm', img_buket_path, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
250
251
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.NLP_MD:
252
            page_markdown = ocr_mk_markdown_with_para_core_v2(
253
                paras_of_layout, 'nlp', parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
254
255
256
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.STANDARD_FORMAT:
            for para_block in paras_of_layout:
257
                if drop_reason_flag:
258
                    para_content = para_to_standard_format_v2(
259
                        para_block, img_buket_path, page_idx, parse_type=parse_type, lang=lang, drop_reason=drop_reason)
260
261
                else:
                    para_content = para_to_standard_format_v2(
262
                        para_block, img_buket_path, page_idx, parse_type=parse_type, lang=lang)
赵小蒙's avatar
赵小蒙 committed
263
264
265
266
267
                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