ocr_mkcontent.py 11.9 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
8
from magic_pdf.libs.language import detect_lang
赵小蒙's avatar
赵小蒙 committed
9
from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
10
from magic_pdf.para.para_split_v3 import ListLineTag
11
12


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

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

19
20
21
22
23
24
25
    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
def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list,
                                                img_buket_path):
28
    markdown_with_para_and_pagination = []
赵小蒙's avatar
赵小蒙 committed
29
30
    page_no = 0
    for page_info in pdf_info_dict:
31
        paras_of_layout = page_info.get('para_blocks')
32
        if not paras_of_layout:
33
            continue
34
35
        page_markdown = ocr_mk_markdown_with_para_core_v2(
            paras_of_layout, 'mm', img_buket_path)
36
        markdown_with_para_and_pagination.append({
37
            'page_no':
38
                page_no,
39
            'md_content':
40
                '\n\n'.join(page_markdown)
41
        })
赵小蒙's avatar
赵小蒙 committed
42
        page_no += 1
43
44
45
    return markdown_with_para_and_pagination


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

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

    return page_markdown


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

120

121
122
123
124
125
126
127
128
129
130
# 连写字符拆分
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


131
def merge_para_with_text(para_block):
赵小蒙's avatar
赵小蒙 committed
132
    para_text = ''
133
134
135
136
137
    for i, line in enumerate(para_block['lines']):

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

138
        line_text = ''
139
140
141
142
        for span in line['spans']:
            span_type = span['type']
            if span_type == ContentType.Text:
                line_text += span['content'].strip()
143
144

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

赵小蒙's avatar
赵小蒙 committed
146
            span_type = span['type']
赵小蒙's avatar
赵小蒙 committed
147
148
            content = ''
            if span_type == ContentType.Text:
149
                content = ocr_escape_special_markdown_char(span['content'])
赵小蒙's avatar
赵小蒙 committed
150
            elif span_type == ContentType.InlineEquation:
151
                content = f"${span['content']}$"
赵小蒙's avatar
赵小蒙 committed
152
153
            elif span_type == ContentType.InterlineEquation:
                content = f"\n$$\n{span['content']}\n$$\n"
154

155
156
            content = content.strip()
            if content != '':
157
158
159
160
161
162
163
164
                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
165
166
            else:
                continue
167
    # 连写字符拆分
168
    # para_text = __replace_ligatures(para_text)
169

赵小蒙's avatar
赵小蒙 committed
170
171
172
    return para_text


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

227
228
229
230
231
    para_content['page_idx'] = page_idx

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

赵小蒙's avatar
赵小蒙 committed
232
233
234
    return para_content


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

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