ocr_mkcontent.py 14.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
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':
赵小蒙's avatar
赵小蒙 committed
73
                for block in para_block['blocks']:  # 1st.拼image_body
赵小蒙's avatar
赵小蒙 committed
74
75
                    if block['type'] == BlockType.ImageBody:
                        for line in block['lines']:
76
                            for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
77
                                if span['type'] == ContentType.Image:
78
79
                                    if span.get('image_path', ''):
                                        para_text += f"\n![]({join_path(img_buket_path, span['image_path'])})  \n"
赵小蒙's avatar
赵小蒙 committed
80
                for block in para_block['blocks']:  # 2nd.拼image_caption
赵小蒙's avatar
赵小蒙 committed
81
                    if block['type'] == BlockType.ImageCaption:
82
                        para_text += merge_para_with_text(block) + '  \n'
83
                for block in para_block['blocks']:  # 3rd.拼image_footnote
84
                    if block['type'] == BlockType.ImageFootnote:
85
                        para_text += merge_para_with_text(block) + '  \n'
86
87
88
89
        elif para_type == BlockType.Table:
            if mode == 'nlp':
                continue
            elif mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
90
91
                for block in para_block['blocks']:  # 1st.拼table_caption
                    if block['type'] == BlockType.TableCaption:
92
                        para_text += merge_para_with_text(block) + '  \n'
赵小蒙's avatar
赵小蒙 committed
93
                for block in para_block['blocks']:  # 2nd.拼table_body
赵小蒙's avatar
赵小蒙 committed
94
95
                    if block['type'] == BlockType.TableBody:
                        for line in block['lines']:
96
                            for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
97
                                if span['type'] == ContentType.Table:
98
99
100
                                    # if processed by table model
                                    if span.get('latex', ''):
                                        para_text += f"\n\n$\n {span['latex']}\n$\n\n"
101
102
                                    elif span.get('html', ''):
                                        para_text += f"\n\n{span['html']}\n\n"
103
                                    elif span.get('image_path', ''):
104
                                        para_text += f"\n![]({join_path(img_buket_path, span['image_path'])})  \n"
赵小蒙's avatar
赵小蒙 committed
105
106
                for block in para_block['blocks']:  # 3rd.拼table_footnote
                    if block['type'] == BlockType.TableFootnote:
107
                        para_text += merge_para_with_text(block) + '  \n'
108
109
110
111
112

        if para_text.strip() == '':
            continue
        else:
            page_markdown.append(para_text.strip() + '  ')
赵小蒙's avatar
赵小蒙 committed
113
114
115
116

    return page_markdown


117
118
119
120
121
122
123
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'
124
        else:
125
126
127
128
            return 'unknown'
    else:
        return 'empty'

129

130
131
132
133
134
135
136
137
138
139
140
141
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)
142
143
        # 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):
144
145
146
147
148
            result.append(chr(code - 0xFEE0))  # Shift to ASCII range
        else:
            result.append(char)
    return ''.join(result)

149
150
151
152
153
154
155
156
157
158
159
160
161
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']
162

163
def merge_para_with_text(para_block):
164
165
166
167
    block_text = ''
    for line in para_block['lines']:
        for span in line['spans']:
            if span['type'] in [ContentType.Text]:
168
                span['content'] = full_to_half(span['content'])
169
170
171
                block_text += span['content']
    block_lang = detect_lang(block_text)

赵小蒙's avatar
赵小蒙 committed
172
    para_text = ''
173
174
175
176
177
    for i, line in enumerate(para_block['lines']):

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

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

赵小蒙's avatar
赵小蒙 committed
180
            span_type = span['type']
赵小蒙's avatar
赵小蒙 committed
181
182
            content = ''
            if span_type == ContentType.Text:
183
                content = ocr_escape_special_markdown_char(span['content'])
赵小蒙's avatar
赵小蒙 committed
184
            elif span_type == ContentType.InlineEquation:
185
                content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
赵小蒙's avatar
赵小蒙 committed
186
            elif span_type == ContentType.InterlineEquation:
187
                content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
188

189
            content = content.strip()
190
191
192

            if content:
                langs = ['zh', 'ja', 'ko']
193
                # logger.info(f'block_lang: {block_lang}, content: {content}')
194
195
                if block_lang in langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
                    if j == len(line['spans']) - 1 and span_type not in [ContentType.InlineEquation]:
196
197
198
                        para_text += content
                    else:
                        para_text += f'{content} '
199
200
201
                else:
                    if span_type in [ContentType.Text, ContentType.InlineEquation]:
                        # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
202
                        if j == len(line['spans'])-1 and span_type == ContentType.Text and __is_hyphen_at_line_end(content):
203
204
205
206
207
                            para_text += content[:-1]
                        else:  # 西方文本语境下 content间需要空格分隔
                            para_text += f'{content} '
                    elif span_type == ContentType.InterlineEquation:
                        para_text += content
208
209
            else:
                continue
210
    # 连写字符拆分
211
    # para_text = __replace_ligatures(para_text)
212

赵小蒙's avatar
赵小蒙 committed
213
214
215
    return para_text


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

272
273
274
275
276
    para_content['page_idx'] = page_idx

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

赵小蒙's avatar
赵小蒙 committed
277
278
279
    return para_content


280
281
282
def union_make(pdf_info_dict: list,
               make_mode: str,
               drop_mode: str,
283
               img_buket_path: str = '',
284
               ):
赵小蒙's avatar
赵小蒙 committed
285
286
    output_content = []
    for page_info in pdf_info_dict:
287
288
        drop_reason_flag = False
        drop_reason = None
289
        if page_info.get('need_drop', False):
290
291
            drop_reason = page_info.get('drop_reason')
            if drop_mode == DropMode.NONE:
赵小蒙's avatar
赵小蒙 committed
292
                pass
293
294
            elif drop_mode == DropMode.NONE_WITH_REASON:
                drop_reason_flag = True
赵小蒙's avatar
赵小蒙 committed
295
            elif drop_mode == DropMode.WHOLE_PDF:
296
297
                raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
                                 f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
298
            elif drop_mode == DropMode.SINGLE_PAGE:
299
300
                logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
                                f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
301
302
                continue
            else:
303
                raise Exception('drop_mode can not be null')
赵小蒙's avatar
赵小蒙 committed
304

305
306
        paras_of_layout = page_info.get('para_blocks')
        page_idx = page_info.get('page_idx')
赵小蒙's avatar
赵小蒙 committed
307
308
309
        if not paras_of_layout:
            continue
        if make_mode == MakeMode.MM_MD:
310
            page_markdown = ocr_mk_markdown_with_para_core_v2(
311
                paras_of_layout, 'mm', img_buket_path)
赵小蒙's avatar
赵小蒙 committed
312
313
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.NLP_MD:
314
            page_markdown = ocr_mk_markdown_with_para_core_v2(
315
                paras_of_layout, 'nlp')
赵小蒙's avatar
赵小蒙 committed
316
317
318
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.STANDARD_FORMAT:
            for para_block in paras_of_layout:
319
                if drop_reason_flag:
320
                    para_content = para_to_standard_format_v2(
321
                        para_block, img_buket_path, page_idx)
322
323
                else:
                    para_content = para_to_standard_format_v2(
324
                        para_block, img_buket_path, page_idx)
赵小蒙's avatar
赵小蒙 committed
325
326
327
328
329
                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
330
331
332
333
334
335
336


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