ocr_mkcontent.py 12.1 KB
Newer Older
1
2
import re

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

5
6
from magic_pdf.config.make_content_config import DropMode, MakeMode
from magic_pdf.config.ocr_content_type import BlockType, ContentType
7
from magic_pdf.libs.commons import join_path
赵小蒙's avatar
赵小蒙 committed
8
from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
9
from magic_pdf.para.para_split_v3 import ListLineTag
10
11


12
def __is_hyphen_at_line_end(line):
13
14
    """Check if a line ends with one or more letters followed by a hyphen.

15
16
    Args:
    line (str): The line of text to check.
17

18
19
20
21
22
23
24
    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))


25
26
def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list,
                                                img_buket_path):
27
    markdown_with_para_and_pagination = []
赵小蒙's avatar
赵小蒙 committed
28
29
    page_no = 0
    for page_info in pdf_info_dict:
30
        paras_of_layout = page_info.get('para_blocks')
31
        if not paras_of_layout:
32
33
34
35
36
37
38
            markdown_with_para_and_pagination.append({
                'page_no':
                    page_no,
                'md_content':
                    '',
            })
            page_no += 1
39
            continue
40
41
        page_markdown = ocr_mk_markdown_with_para_core_v2(
            paras_of_layout, 'mm', img_buket_path)
42
        markdown_with_para_and_pagination.append({
43
            'page_no':
44
                page_no,
45
            'md_content':
46
                '\n\n'.join(page_markdown)
47
        })
赵小蒙's avatar
赵小蒙 committed
48
        page_no += 1
49
50
51
    return markdown_with_para_and_pagination


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

        if para_text.strip() == '':
            continue
        else:
            page_markdown.append(para_text.strip() + '  ')
赵小蒙's avatar
赵小蒙 committed
110
111
112
113

    return page_markdown


114
115
116
117
118
119
120
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'
121
        else:
122
123
124
125
            return 'unknown'
    else:
        return 'empty'

126

127
128
129
130
131
132
133
134
135
136
# 连写字符拆分
def __replace_ligatures(text: str):
    text = re.sub(r'fi', 'fi', text)  # 替换 fi 连写符
    text = re.sub(r'fl', 'fl', text)  # 替换 fl 连写符
    text = re.sub(r'ff', 'ff', text)  # 替换 ff 连写符
    text = re.sub(r'ffi', 'ffi', text)  # 替换 ffi 连写符
    text = re.sub(r'ffl', 'ffl', text)  # 替换 ffl 连写符
    return text


137
def merge_para_with_text(para_block):
赵小蒙's avatar
赵小蒙 committed
138
    para_text = ''
139
140
141
142
143
    for i, line in enumerate(para_block['lines']):

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

144
        line_text = ''
145
146
147
148
        for span in line['spans']:
            span_type = span['type']
            if span_type == ContentType.Text:
                line_text += span['content'].strip()
149
150

        for j, span in enumerate(line['spans']):
151

赵小蒙's avatar
赵小蒙 committed
152
            span_type = span['type']
赵小蒙's avatar
赵小蒙 committed
153
154
            content = ''
            if span_type == ContentType.Text:
155
                content = ocr_escape_special_markdown_char(span['content'])
赵小蒙's avatar
赵小蒙 committed
156
            elif span_type == ContentType.InlineEquation:
157
                content = f"${span['content']}$"
赵小蒙's avatar
赵小蒙 committed
158
159
            elif span_type == ContentType.InterlineEquation:
                content = f"\n$$\n{span['content']}\n$$\n"
160

161
162
            content = content.strip()
            if content != '':
163
164
165
166
167
168
169
170
                if span_type in [ContentType.Text, ContentType.InlineEquation]:
                    # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
                    if j == len(line['spans'])-1 and __is_hyphen_at_line_end(content):
                        para_text += content[:-1]
                    else:  # content间需要空格分隔
                        para_text += f'{content} '
                elif span_type == ContentType.InterlineEquation:
                    para_text += content
171
172
            else:
                continue
173
    # 连写字符拆分
174
    # para_text = __replace_ligatures(para_text)
175

赵小蒙's avatar
赵小蒙 committed
176
177
178
    return para_text


179
def para_to_standard_format_v2(para_block, img_buket_path, page_idx, drop_reason=None):
赵小蒙's avatar
赵小蒙 committed
180
    para_type = para_block['type']
181
    para_content = {}
182
    if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
赵小蒙's avatar
赵小蒙 committed
183
184
        para_content = {
            'type': 'text',
185
            'text': merge_para_with_text(para_block),
赵小蒙's avatar
赵小蒙 committed
186
187
188
189
        }
    elif para_type == BlockType.Title:
        para_content = {
            'type': 'text',
190
            'text': merge_para_with_text(para_block),
191
            'text_level': 1,
赵小蒙's avatar
赵小蒙 committed
192
193
194
195
        }
    elif para_type == BlockType.InterlineEquation:
        para_content = {
            'type': 'equation',
196
            'text': merge_para_with_text(para_block),
197
            'text_format': 'latex',
赵小蒙's avatar
赵小蒙 committed
198
199
        }
    elif para_type == BlockType.Image:
200
        para_content = {'type': 'image', 'img_path': '', 'img_caption': [], 'img_footnote': []}
赵小蒙's avatar
赵小蒙 committed
201
202
        for block in para_block['blocks']:
            if block['type'] == BlockType.ImageBody:
203
204
205
206
207
                for line in block['lines']:
                    for span in line['spans']:
                        if span['type'] == ContentType.Image:
                            if span.get('image_path', ''):
                                para_content['img_path'] = join_path(img_buket_path, span['image_path'])
赵小蒙's avatar
赵小蒙 committed
208
            if block['type'] == BlockType.ImageCaption:
209
                para_content['img_caption'].append(merge_para_with_text(block))
210
            if block['type'] == BlockType.ImageFootnote:
211
                para_content['img_footnote'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
212
    elif para_type == BlockType.Table:
213
        para_content = {'type': 'table', 'img_path': '', 'table_caption': [], 'table_footnote': []}
赵小蒙's avatar
赵小蒙 committed
214
215
        for block in para_block['blocks']:
            if block['type'] == BlockType.TableBody:
216
217
218
219
220
221
222
223
224
225
226
227
                for line in block['lines']:
                    for span in line['spans']:
                        if span['type'] == ContentType.Table:

                            if span.get('latex', ''):
                                para_content['table_body'] = f"\n\n$\n {span['latex']}\n$\n\n"
                            elif span.get('html', ''):
                                para_content['table_body'] = f"\n\n{span['html']}\n\n"

                            if span.get('image_path', ''):
                                para_content['img_path'] = join_path(img_buket_path, span['image_path'])

赵小蒙's avatar
赵小蒙 committed
228
            if block['type'] == BlockType.TableCaption:
229
                para_content['table_caption'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
230
            if block['type'] == BlockType.TableFootnote:
231
                para_content['table_footnote'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
232

233
234
235
236
237
    para_content['page_idx'] = page_idx

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

赵小蒙's avatar
赵小蒙 committed
238
239
240
    return para_content


241
242
243
def union_make(pdf_info_dict: list,
               make_mode: str,
               drop_mode: str,
244
               img_buket_path: str = '',
245
               ):
赵小蒙's avatar
赵小蒙 committed
246
247
    output_content = []
    for page_info in pdf_info_dict:
248
249
        drop_reason_flag = False
        drop_reason = None
250
        if page_info.get('need_drop', False):
251
252
            drop_reason = page_info.get('drop_reason')
            if drop_mode == DropMode.NONE:
赵小蒙's avatar
赵小蒙 committed
253
                pass
254
255
            elif drop_mode == DropMode.NONE_WITH_REASON:
                drop_reason_flag = True
赵小蒙's avatar
赵小蒙 committed
256
            elif drop_mode == DropMode.WHOLE_PDF:
257
258
                raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
                                 f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
259
            elif drop_mode == DropMode.SINGLE_PAGE:
260
261
                logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
                                f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
262
263
                continue
            else:
264
                raise Exception('drop_mode can not be null')
赵小蒙's avatar
赵小蒙 committed
265

266
267
        paras_of_layout = page_info.get('para_blocks')
        page_idx = page_info.get('page_idx')
赵小蒙's avatar
赵小蒙 committed
268
269
270
        if not paras_of_layout:
            continue
        if make_mode == MakeMode.MM_MD:
271
            page_markdown = ocr_mk_markdown_with_para_core_v2(
272
                paras_of_layout, 'mm', img_buket_path)
赵小蒙's avatar
赵小蒙 committed
273
274
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.NLP_MD:
275
            page_markdown = ocr_mk_markdown_with_para_core_v2(
276
                paras_of_layout, 'nlp')
赵小蒙's avatar
赵小蒙 committed
277
278
279
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.STANDARD_FORMAT:
            for para_block in paras_of_layout:
280
                if drop_reason_flag:
281
                    para_content = para_to_standard_format_v2(
282
                        para_block, img_buket_path, page_idx)
283
284
                else:
                    para_content = para_to_standard_format_v2(
285
                        para_block, img_buket_path, page_idx)
赵小蒙's avatar
赵小蒙 committed
286
287
288
289
290
                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