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


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

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

    return page_markdown


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

128

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


149
def merge_para_with_text(para_block):
150
151
152
153
    block_text = ''
    for line in para_block['lines']:
        for span in line['spans']:
            if span['type'] in [ContentType.Text]:
154
                span['content'] = full_to_half(span['content'])
155
156
157
                block_text += span['content']
    block_lang = detect_lang(block_text)

赵小蒙's avatar
赵小蒙 committed
158
    para_text = ''
159
160
161
162
163
    for i, line in enumerate(para_block['lines']):

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

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

赵小蒙's avatar
赵小蒙 committed
166
            span_type = span['type']
赵小蒙's avatar
赵小蒙 committed
167
168
            content = ''
            if span_type == ContentType.Text:
169
                content = ocr_escape_special_markdown_char(span['content'])
赵小蒙's avatar
赵小蒙 committed
170
            elif span_type == ContentType.InlineEquation:
171
                content = f"${span['content']}$"
赵小蒙's avatar
赵小蒙 committed
172
173
            elif span_type == ContentType.InterlineEquation:
                content = f"\n$$\n{span['content']}\n$$\n"
174

175
            content = content.strip()
176
177
178

            if content:
                langs = ['zh', 'ja', 'ko']
179
                # logger.info(f'block_lang: {block_lang}, content: {content}')
180
181
                if block_lang in langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
                    if j == len(line['spans']) - 1 and span_type not in [ContentType.InlineEquation]:
182
183
184
                        para_text += content
                    else:
                        para_text += f'{content} '
185
186
187
                else:
                    if span_type in [ContentType.Text, ContentType.InlineEquation]:
                        # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
188
                        if j == len(line['spans'])-1 and span_type == ContentType.Text and __is_hyphen_at_line_end(content):
189
190
191
192
193
                            para_text += content[:-1]
                        else:  # 西方文本语境下 content间需要空格分隔
                            para_text += f'{content} '
                    elif span_type == ContentType.InterlineEquation:
                        para_text += content
194
195
            else:
                continue
196
    # 连写字符拆分
197
    # para_text = __replace_ligatures(para_text)
198

赵小蒙's avatar
赵小蒙 committed
199
200
201
    return para_text


202
def para_to_standard_format_v2(para_block, img_buket_path, page_idx, drop_reason=None):
赵小蒙's avatar
赵小蒙 committed
203
    para_type = para_block['type']
204
    para_content = {}
205
    if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
赵小蒙's avatar
赵小蒙 committed
206
207
        para_content = {
            'type': 'text',
208
            'text': merge_para_with_text(para_block),
赵小蒙's avatar
赵小蒙 committed
209
210
        }
    elif para_type == BlockType.Title:
211
        title_level = get_title_level(para_block)
赵小蒙's avatar
赵小蒙 committed
212
213
        para_content = {
            'type': 'text',
214
            'text': merge_para_with_text(para_block),
215
            'text_level': title_level,
赵小蒙's avatar
赵小蒙 committed
216
217
218
219
        }
    elif para_type == BlockType.InterlineEquation:
        para_content = {
            'type': 'equation',
220
            'text': merge_para_with_text(para_block),
221
            'text_format': 'latex',
赵小蒙's avatar
赵小蒙 committed
222
223
        }
    elif para_type == BlockType.Image:
224
        para_content = {'type': 'image', 'img_path': '', 'img_caption': [], 'img_footnote': []}
赵小蒙's avatar
赵小蒙 committed
225
226
        for block in para_block['blocks']:
            if block['type'] == BlockType.ImageBody:
227
228
229
230
231
                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
232
            if block['type'] == BlockType.ImageCaption:
233
                para_content['img_caption'].append(merge_para_with_text(block))
234
            if block['type'] == BlockType.ImageFootnote:
235
                para_content['img_footnote'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
236
    elif para_type == BlockType.Table:
237
        para_content = {'type': 'table', 'img_path': '', 'table_caption': [], 'table_footnote': []}
赵小蒙's avatar
赵小蒙 committed
238
239
        for block in para_block['blocks']:
            if block['type'] == BlockType.TableBody:
240
241
242
243
244
245
246
247
248
249
250
251
                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
252
            if block['type'] == BlockType.TableCaption:
253
                para_content['table_caption'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
254
            if block['type'] == BlockType.TableFootnote:
255
                para_content['table_footnote'].append(merge_para_with_text(block))
赵小蒙's avatar
赵小蒙 committed
256

257
258
259
260
261
    para_content['page_idx'] = page_idx

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

赵小蒙's avatar
赵小蒙 committed
262
263
264
    return para_content


265
266
267
def union_make(pdf_info_dict: list,
               make_mode: str,
               drop_mode: str,
268
               img_buket_path: str = '',
269
               ):
赵小蒙's avatar
赵小蒙 committed
270
271
    output_content = []
    for page_info in pdf_info_dict:
272
273
        drop_reason_flag = False
        drop_reason = None
274
        if page_info.get('need_drop', False):
275
276
            drop_reason = page_info.get('drop_reason')
            if drop_mode == DropMode.NONE:
赵小蒙's avatar
赵小蒙 committed
277
                pass
278
279
            elif drop_mode == DropMode.NONE_WITH_REASON:
                drop_reason_flag = True
赵小蒙's avatar
赵小蒙 committed
280
            elif drop_mode == DropMode.WHOLE_PDF:
281
282
                raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
                                 f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
283
            elif drop_mode == DropMode.SINGLE_PAGE:
284
285
                logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
                                f'drop_reason is {drop_reason}'))
赵小蒙's avatar
赵小蒙 committed
286
287
                continue
            else:
288
                raise Exception('drop_mode can not be null')
赵小蒙's avatar
赵小蒙 committed
289

290
291
        paras_of_layout = page_info.get('para_blocks')
        page_idx = page_info.get('page_idx')
赵小蒙's avatar
赵小蒙 committed
292
293
294
        if not paras_of_layout:
            continue
        if make_mode == MakeMode.MM_MD:
295
            page_markdown = ocr_mk_markdown_with_para_core_v2(
296
                paras_of_layout, 'mm', img_buket_path)
赵小蒙's avatar
赵小蒙 committed
297
298
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.NLP_MD:
299
            page_markdown = ocr_mk_markdown_with_para_core_v2(
300
                paras_of_layout, 'nlp')
赵小蒙's avatar
赵小蒙 committed
301
302
303
            output_content.extend(page_markdown)
        elif make_mode == MakeMode.STANDARD_FORMAT:
            for para_block in paras_of_layout:
304
                if drop_reason_flag:
305
                    para_content = para_to_standard_format_v2(
306
                        para_block, img_buket_path, page_idx)
307
308
                else:
                    para_content = para_to_standard_format_v2(
309
                        para_block, img_buket_path, page_idx)
赵小蒙's avatar
赵小蒙 committed
310
311
312
313
314
                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
315
316
317
318
319
320
321
322
323


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