"scripts/ci/ci_install_dependency.sh" did not exist on "b5be56944b6eb61b44866011f157e8df0e563bd7"
ocr_mkcontent.py 12.7 KB
Newer Older
1
2
import re

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

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


13
14
15
16
17
18
19
20
21
22
23
24
25
26
def __is_hyphen_at_line_end(line):
    """
    Check if a line ends with one or more letters followed by a hyphen.
    
    Args:
    line (str): The line of text to check.
    
    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
            continue
35
36
        page_markdown = ocr_mk_markdown_with_para_core_v2(
            paras_of_layout, 'mm', img_buket_path)
37
        markdown_with_para_and_pagination.append({
38
            'page_no':
39
                page_no,
40
            'md_content':
41
                '\n\n'.join(page_markdown)
42
        })
赵小蒙's avatar
赵小蒙 committed
43
        page_no += 1
44
45
46
    return markdown_with_para_and_pagination


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

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

    return page_markdown


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

121

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


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

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

139
140
        line_text = ''
        line_lang = ''
141
142
143
144
        for span in line['spans']:
            span_type = span['type']
            if span_type == ContentType.Text:
                line_text += span['content'].strip()
145
        if line_text != '':
146
            line_lang = detect_lang(line_text)
赵小蒙's avatar
赵小蒙 committed
147
        for span in line['spans']:
148

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

158
159
            content = content.strip()
            if content != '':
160
161
                langs = ['zh', 'ja', 'ko']
                if line_lang in langs:  # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断
162
163
164
165
                    if span_type in [ContentType.Text, ContentType.InterlineEquation]:
                        para_text += content  # 中文/日语/韩文语境下,content间不需要空格分隔
                    elif span_type == ContentType.InlineEquation:
                        para_text += f" {content} "
166
                else:
167
                    if span_type in [ContentType.Text, ContentType.InlineEquation]:
168
169
170
                        # 如果是前一行带有-连字符,那么末尾不应该加空格
                        if __is_hyphen_at_line_end(content):
                            para_text += content[:-1]
171
                        elif len(content) == 1 and content not in ['A', 'I', 'a', 'i'] and not content.isdigit():
172
                            para_text += content
173
                        else:  # 西方文本语境下 content间需要空格分隔
174
                            para_text += f"{content} "
175
176
177
178
                    elif span_type == ContentType.InterlineEquation:
                        para_text += content
            else:
                continue
179
180
    # 连写字符拆分
    para_text = __replace_ligatures(para_text)
181

赵小蒙's avatar
赵小蒙 committed
182
183
184
    return para_text


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

239
240
241
242
243
    para_content['page_idx'] = page_idx

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

赵小蒙's avatar
赵小蒙 committed
244
245
246
    return para_content


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

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