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


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

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

20
21
22
23
24
25
26
    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
35
36
37
38
39
40
            markdown_with_para_and_pagination.append({
                'page_no':
                    page_no,
                'md_content':
                    '',
            })
            page_no += 1
41
            continue
42
43
        page_markdown = ocr_mk_markdown_with_para_core_v2(
            paras_of_layout, 'mm', img_buket_path)
44
        markdown_with_para_and_pagination.append({
45
            'page_no':
46
                page_no,
47
            'md_content':
48
                '\n\n'.join(page_markdown)
49
        })
赵小蒙's avatar
赵小蒙 committed
50
        page_no += 1
51
52
53
    return markdown_with_para_and_pagination


54
55
def ocr_mk_markdown_with_para_core_v2(paras_of_layout,
                                      mode,
56
57
                                      img_buket_path='',
                                      ):
赵小蒙's avatar
赵小蒙 committed
58
    page_markdown = []
59
    for para_block in paras_of_layout:
赵小蒙's avatar
赵小蒙 committed
60
        para_text = ''
赵小蒙's avatar
赵小蒙 committed
61
        para_type = para_block['type']
62
        if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
63
            para_text = merge_para_with_text(para_block)
64
        elif para_type == BlockType.Title:
65
66
            title_level = get_title_level(para_block)
            para_text = f'{"#" * title_level} {merge_para_with_text(para_block)}'
67
        elif para_type == BlockType.InterlineEquation:
68
            para_text = merge_para_with_text(para_block)
69
70
        elif para_type == BlockType.Image:
            if mode == 'nlp':
赵小蒙's avatar
赵小蒙 committed
71
                continue
72
            elif mode == 'mm':
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
                # 检测是否存在图片脚注
                has_image_footnote = any(block['type'] == BlockType.ImageFootnote for block in para_block['blocks'])
                # 如果存在图片脚注,则将图片脚注拼接到图片正文后面
                if has_image_footnote:
                    for block in para_block['blocks']:  # 1st.拼image_caption
                        if block['type'] == BlockType.ImageCaption:
                            para_text += merge_para_with_text(block) + '  \n'
                    for block in para_block['blocks']:  # 2nd.拼image_body
                        if block['type'] == BlockType.ImageBody:
                            for line in block['lines']:
                                for span in line['spans']:
                                    if span['type'] == ContentType.Image:
                                        if span.get('image_path', ''):
                                            para_text += f"![]({img_buket_path}/{span['image_path']})"
                    for block in para_block['blocks']:  # 3rd.拼image_footnote
                        if block['type'] == BlockType.ImageFootnote:
                            para_text += '  \n' + merge_para_with_text(block)
                else:
                    for block in para_block['blocks']:  # 1st.拼image_body
                        if block['type'] == BlockType.ImageBody:
                            for line in block['lines']:
                                for span in line['spans']:
                                    if span['type'] == ContentType.Image:
                                        if span.get('image_path', ''):
                                            para_text += f"![]({img_buket_path}/{span['image_path']})"
                    for block in para_block['blocks']:  # 2nd.拼image_caption
                        if block['type'] == BlockType.ImageCaption:
                            para_text += '  \n' + merge_para_with_text(block)
101
102
103
104
        elif para_type == BlockType.Table:
            if mode == 'nlp':
                continue
            elif mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
105
106
                for block in para_block['blocks']:  # 1st.拼table_caption
                    if block['type'] == BlockType.TableCaption:
107
                        para_text += merge_para_with_text(block) + '  \n'
赵小蒙's avatar
赵小蒙 committed
108
                for block in para_block['blocks']:  # 2nd.拼table_body
赵小蒙's avatar
赵小蒙 committed
109
110
                    if block['type'] == BlockType.TableBody:
                        for line in block['lines']:
111
                            for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
112
                                if span['type'] == ContentType.Table:
113
                                    # if processed by table model
114
115
                                    if span.get('html', ''):
                                        para_text += f"\n{span['html']}\n"
116
                                    elif span.get('image_path', ''):
117
                                        para_text += f"![]({img_buket_path}/{span['image_path']})"
赵小蒙's avatar
赵小蒙 committed
118
119
                for block in para_block['blocks']:  # 3rd.拼table_footnote
                    if block['type'] == BlockType.TableFootnote:
120
                        para_text += '\n' + merge_para_with_text(block) + '  '
121
122
123
124

        if para_text.strip() == '':
            continue
        else:
125
126
            # page_markdown.append(para_text.strip() + '  ')
            page_markdown.append(para_text.strip())
赵小蒙's avatar
赵小蒙 committed
127
128
129
130

    return page_markdown


131
132
133
134
135
136
137
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'
138
        else:
139
140
141
142
            return 'unknown'
    else:
        return 'empty'

143

144
145
146
147
148
149
150
151
152
153
154
155
def full_to_half(text: str) -> str:
    """Convert full-width characters to half-width characters using code point manipulation.

    Args:
        text: String containing full-width characters

    Returns:
        String with full-width characters converted to half-width
    """
    result = []
    for char in text:
        code = ord(char)
156
157
        # Full-width letters and numbers (FF21-FF3A for A-Z, FF41-FF5A for a-z, FF10-FF19 for 0-9)
        if (0xFF21 <= code <= 0xFF3A) or (0xFF41 <= code <= 0xFF5A) or (0xFF10 <= code <= 0xFF19):
158
159
160
161
162
            result.append(chr(code - 0xFEE0))  # Shift to ASCII range
        else:
            result.append(char)
    return ''.join(result)

163
164
165
166
167
168
169
170
171
172
173
174
175
latex_delimiters_config = get_latex_delimiter_config()

default_delimiters = {
    'display': {'left': '$$', 'right': '$$'},
    'inline': {'left': '$', 'right': '$'}
}

delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters

display_left_delimiter = delimiters['display']['left']
display_right_delimiter = delimiters['display']['right']
inline_left_delimiter = delimiters['inline']['left']
inline_right_delimiter = delimiters['inline']['right']
176

177
def merge_para_with_text(para_block):
178
179
180
181
    block_text = ''
    for line in para_block['lines']:
        for span in line['spans']:
            if span['type'] in [ContentType.Text]:
182
                span['content'] = full_to_half(span['content'])
183
184
185
                block_text += span['content']
    block_lang = detect_lang(block_text)

赵小蒙's avatar
赵小蒙 committed
186
    para_text = ''
187
188
189
190
191
    for i, line in enumerate(para_block['lines']):

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

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

赵小蒙's avatar
赵小蒙 committed
194
            span_type = span['type']
赵小蒙's avatar
赵小蒙 committed
195
196
            content = ''
            if span_type == ContentType.Text:
197
                content = ocr_escape_special_markdown_char(span['content'])
赵小蒙's avatar
赵小蒙 committed
198
            elif span_type == ContentType.InlineEquation:
199
                content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
赵小蒙's avatar
赵小蒙 committed
200
            elif span_type == ContentType.InterlineEquation:
201
                content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
202

203
            content = content.strip()
204
205
206

            if content:
                langs = ['zh', 'ja', 'ko']
207
                # logger.info(f'block_lang: {block_lang}, content: {content}')
208
209
                if block_lang in langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
                    if j == len(line['spans']) - 1 and span_type not in [ContentType.InlineEquation]:
210
211
212
                        para_text += content
                    else:
                        para_text += f'{content} '
213
214
215
                else:
                    if span_type in [ContentType.Text, ContentType.InlineEquation]:
                        # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
216
                        if j == len(line['spans'])-1 and span_type == ContentType.Text and __is_hyphen_at_line_end(content):
217
218
219
220
221
                            para_text += content[:-1]
                        else:  # 西方文本语境下 content间需要空格分隔
                            para_text += f'{content} '
                    elif span_type == ContentType.InterlineEquation:
                        para_text += content
222
223
            else:
                continue
224
    # 连写字符拆分
225
    # para_text = __replace_ligatures(para_text)
226

赵小蒙's avatar
赵小蒙 committed
227
228
229
    return para_text


230
def para_to_standard_format_v2(para_block, img_buket_path, page_idx, drop_reason=None):
赵小蒙's avatar
赵小蒙 committed
231
    para_type = para_block['type']
232
    para_content = {}
233
    if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
赵小蒙's avatar
赵小蒙 committed
234
235
        para_content = {
            'type': 'text',
236
            'text': merge_para_with_text(para_block),
赵小蒙's avatar
赵小蒙 committed
237
238
239
240
        }
    elif para_type == BlockType.Title:
        para_content = {
            'type': 'text',
241
            'text': merge_para_with_text(para_block),
赵小蒙's avatar
赵小蒙 committed
242
        }
243
244
245
        title_level = get_title_level(para_block)
        if title_level != 0:
            para_content['text_level'] = title_level
赵小蒙's avatar
赵小蒙 committed
246
247
248
    elif para_type == BlockType.InterlineEquation:
        para_content = {
            'type': 'equation',
249
            'text': merge_para_with_text(para_block),
250
            'text_format': 'latex',
赵小蒙's avatar
赵小蒙 committed
251
252
        }
    elif para_type == BlockType.Image:
253
        para_content = {'type': 'image', 'img_path': '', 'img_caption': [], 'img_footnote': []}
赵小蒙's avatar
赵小蒙 committed
254
255
        for block in para_block['blocks']:
            if block['type'] == BlockType.ImageBody:
256
257
258
259
260
                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
261
            if block['type'] == BlockType.ImageCaption:
262
                para_content['img_caption'].append(merge_para_with_text(block))
263
            if block['type'] == BlockType.ImageFootnote:
264
                para_content['img_footnote'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
265
    elif para_type == BlockType.Table:
266
        para_content = {'type': 'table', 'img_path': '', 'table_caption': [], 'table_footnote': []}
赵小蒙's avatar
赵小蒙 committed
267
268
        for block in para_block['blocks']:
            if block['type'] == BlockType.TableBody:
269
270
271
272
273
                for line in block['lines']:
                    for span in line['spans']:
                        if span['type'] == ContentType.Table:

                            if span.get('latex', ''):
274
                                para_content['table_body'] = f"{span['latex']}"
275
                            elif span.get('html', ''):
276
                                para_content['table_body'] = f"{span['html']}"
277
278
279
280

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

赵小蒙's avatar
赵小蒙 committed
281
            if block['type'] == BlockType.TableCaption:
282
                para_content['table_caption'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
283
            if block['type'] == BlockType.TableFootnote:
284
                para_content['table_footnote'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
285

286
287
288
289
290
    para_content['page_idx'] = page_idx

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

赵小蒙's avatar
赵小蒙 committed
291
292
293
    return para_content


294
295
296
def union_make(pdf_info_dict: list,
               make_mode: str,
               drop_mode: str,
297
               img_buket_path: str = '',
298
               ):
赵小蒙's avatar
赵小蒙 committed
299
300
    output_content = []
    for page_info in pdf_info_dict:
301
302
        drop_reason_flag = False
        drop_reason = None
303
        if page_info.get('need_drop', False):
304
305
            drop_reason = page_info.get('drop_reason')
            if drop_mode == DropMode.NONE:
赵小蒙's avatar
赵小蒙 committed
306
                pass
307
308
            elif drop_mode == DropMode.NONE_WITH_REASON:
                drop_reason_flag = True
赵小蒙's avatar
赵小蒙 committed
309
            elif drop_mode == DropMode.WHOLE_PDF:
310
311
                raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
                                 f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
312
            elif drop_mode == DropMode.SINGLE_PAGE:
313
314
                logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
                                f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
315
316
                continue
            else:
317
                raise Exception('drop_mode can not be null')
赵小蒙's avatar
赵小蒙 committed
318

319
320
        paras_of_layout = page_info.get('para_blocks')
        page_idx = page_info.get('page_idx')
赵小蒙's avatar
赵小蒙 committed
321
322
323
        if not paras_of_layout:
            continue
        if make_mode == MakeMode.MM_MD:
324
            page_markdown = ocr_mk_markdown_with_para_core_v2(
325
                paras_of_layout, 'mm', img_buket_path)
赵小蒙's avatar
赵小蒙 committed
326
327
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.NLP_MD:
328
            page_markdown = ocr_mk_markdown_with_para_core_v2(
329
                paras_of_layout, 'nlp')
赵小蒙's avatar
赵小蒙 committed
330
331
332
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.STANDARD_FORMAT:
            for para_block in paras_of_layout:
333
                if drop_reason_flag:
334
                    para_content = para_to_standard_format_v2(
335
                        para_block, img_buket_path, page_idx)
336
337
                else:
                    para_content = para_to_standard_format_v2(
338
                        para_block, img_buket_path, page_idx)
赵小蒙's avatar
赵小蒙 committed
339
340
341
342
343
                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
344
345
346
347
348
349
350


def get_title_level(block):
    title_level = block.get('level', 1)
    if title_level > 4:
        title_level = 4
    elif title_level < 1:
351
        title_level = 0
352
    return title_level