ocr_mkcontent.py 9.93 KB
Newer Older
1
from magic_pdf.libs.commons import join_path
2
from magic_pdf.libs.language import detect_lang
赵小蒙's avatar
赵小蒙 committed
3
from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
赵小蒙's avatar
赵小蒙 committed
4
from magic_pdf.libs.ocr_content_type import ContentType
5
6
7
8
9
10
11
12
13
14
15
16
17
import wordninja
import re


def split_long_words(text):
    segments = text.split(' ')
    for i in range(len(segments)):
        words = re.findall(r'\w+|[^\w\s]', segments[i], re.UNICODE)
        for j in range(len(words)):
            if len(words[j]) > 15:
                words[j] = ' '.join(wordninja.split(words[j]))
        segments[i] = ''.join(words)
    return ' '.join(segments)
赵小蒙's avatar
赵小蒙 committed
18
19


赵小蒙's avatar
赵小蒙 committed
20
def ocr_mk_nlp_markdown(pdf_info_dict: list):
赵小蒙's avatar
赵小蒙 committed
21
22
    markdown = []

赵小蒙's avatar
赵小蒙 committed
23
    for page_info in pdf_info_dict:
赵小蒙's avatar
赵小蒙 committed
24
25
26
27
28
29
30
        blocks = page_info.get("preproc_blocks")
        if not blocks:
            continue
        for block in blocks:
            for line in block['lines']:
                line_text = ''
                for span in line['spans']:
31
32
                    if not span.get('content'):
                        continue
赵小蒙's avatar
赵小蒙 committed
33
                    content = ocr_escape_special_markdown_char(span['content'])  # 转义特殊符号
赵小蒙's avatar
赵小蒙 committed
34
                    if span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
35
                        content = f"${content}$"
赵小蒙's avatar
赵小蒙 committed
36
                    elif span['type'] == ContentType.InterlineEquation:
赵小蒙's avatar
赵小蒙 committed
37
38
39
40
41
                        content = f"$$\n{content}\n$$"
                    line_text += content + ' '
                # 在行末添加两个空格以强制换行
                markdown.append(line_text.strip() + '  ')
    return '\n'.join(markdown)
42

赵小蒙's avatar
赵小蒙 committed
43

赵小蒙's avatar
赵小蒙 committed
44
def ocr_mk_mm_markdown(pdf_info_dict: list):
45
46
    markdown = []

赵小蒙's avatar
赵小蒙 committed
47
    for page_info in pdf_info_dict:
48
49
50
51
52
53
54
55
56
57
58
        blocks = page_info.get("preproc_blocks")
        if not blocks:
            continue
        for block in blocks:
            for line in block['lines']:
                line_text = ''
                for span in line['spans']:
                    if not span.get('content'):
                        if not span.get('image_path'):
                            continue
                        else:
59
                            content = f"![]({span['image_path']})"
60
                    else:
赵小蒙's avatar
赵小蒙 committed
61
                        content = ocr_escape_special_markdown_char(span['content'])  # 转义特殊符号
赵小蒙's avatar
赵小蒙 committed
62
                        if span['type'] == ContentType.InlineEquation:
63
                            content = f"${content}$"
赵小蒙's avatar
赵小蒙 committed
64
                        elif span['type'] == ContentType.InterlineEquation:
65
66
67
68
69
                            content = f"$$\n{content}\n$$"
                    line_text += content + ' '
                # 在行末添加两个空格以强制换行
                markdown.append(line_text.strip() + '  ')
    return '\n'.join(markdown)
70

71

赵小蒙's avatar
赵小蒙 committed
72
def ocr_mk_mm_markdown_with_para(pdf_info_list: list, img_buket_path):
xuchao's avatar
xuchao committed
73
    markdown = []
赵小蒙's avatar
赵小蒙 committed
74
    for page_info in pdf_info_list:
75
        paras_of_layout = page_info.get("para_blocks")
赵小蒙's avatar
赵小蒙 committed
76
        page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm", img_buket_path)
77
        markdown.extend(page_markdown)
78
    return '\n\n'.join(markdown)
79
80


赵小蒙's avatar
赵小蒙 committed
81
def ocr_mk_nlp_markdown_with_para(pdf_info_dict: list):
82
    markdown = []
赵小蒙's avatar
赵小蒙 committed
83
    for page_info in pdf_info_dict:
84
        paras_of_layout = page_info.get("para_blocks")
85
        page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "nlp")
86
87
88
        markdown.extend(page_markdown)
    return '\n\n'.join(markdown)

赵小蒙's avatar
赵小蒙 committed
89
def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list):
90
    markdown_with_para_and_pagination = []
赵小蒙's avatar
赵小蒙 committed
91
92
    page_no = 0
    for page_info in pdf_info_dict:
93
94
        paras_of_layout = page_info.get("para_blocks")
        if not paras_of_layout:
95
            continue
96
        page_markdown = ocr_mk_markdown_with_para_core(paras_of_layout, "mm")
97
98
        markdown_with_para_and_pagination.append({
            'page_no': page_no,
99
            'md_content': '\n\n'.join(page_markdown)
100
        })
赵小蒙's avatar
赵小蒙 committed
101
        page_no += 1
102
103
104
    return markdown_with_para_and_pagination


赵小蒙's avatar
赵小蒙 committed
105
def ocr_mk_markdown_with_para_core(paras_of_layout, mode, img_buket_path):
106
107
108
109
110
111
112
    page_markdown = []
    for paras in paras_of_layout:
        for para in paras:
            para_text = ''
            for line in para:
                for span in line['spans']:
                    span_type = span.get('type')
113
                    content = ''
114
                    language = ''
115
                    if span_type == ContentType.Text:
116
117
118
119
120
121
                        content = span['content']
                        language = detect_lang(content)
                        if language == 'en':  # 只对英文长词进行分词处理,中文分词会丢失文本
                            content = ocr_escape_special_markdown_char(split_long_words(content))
                        else:
                            content = ocr_escape_special_markdown_char(content)
122
                    elif span_type == ContentType.InlineEquation:
123
                        content = f"${span['content']}$"
124
                    elif span_type == ContentType.InterlineEquation:
125
                        content = f"\n$$\n{span['content']}\n$$\n"
126
                    elif span_type in [ContentType.Image, ContentType.Table]:
127
                        if mode == 'mm':
赵小蒙's avatar
赵小蒙 committed
128
                            content = f"\n![]({join_path(img_buket_path, span['image_path'])})\n"
129
130
                        elif mode == 'nlp':
                            pass
131
                    if content != '':
132
133
134
135
                        if language == 'en':  # 英文语境下 content间需要空格分隔
                            para_text += content + ' '
                        else:  # 中文语境下,content间不需要空格分隔
                            para_text += content
136
137
138
139
            if para_text.strip() == '':
                continue
            else:
                page_markdown.append(para_text.strip() + '  ')
140
141
142
    return page_markdown


143
def para_to_standard_format(para, img_buket_path):
144
145
    para_content = {}
    if len(para) == 1:
146
        para_content = line_to_standard_format(para[0], img_buket_path)
147
148
149
150
151
    elif len(para) > 1:
        para_text = ''
        inline_equation_num = 0
        for line in para:
            for span in line['spans']:
152
                language = ''
153
154
                span_type = span.get('type')
                if span_type == ContentType.Text:
155
156
157
158
159
160
                    content = span['content']
                    language = detect_lang(content)
                    if language == 'en':  # 只对英文长词进行分词处理,中文分词会丢失文本
                        content = ocr_escape_special_markdown_char(split_long_words(content))
                    else:
                        content = ocr_escape_special_markdown_char(content)
161
                elif span_type == ContentType.InlineEquation:
162
                    content = f"${span['content']}$"
163
                    inline_equation_num += 1
164
165
166
167
168

                if language == 'en':  # 英文语境下 content间需要空格分隔
                    para_text += content + ' '
                else:  # 中文语境下,content间不需要空格分隔
                    para_text += content
169
170
171
172
173
174
175
        para_content = {
            'type': 'text',
            'text': para_text,
            'inline_equation_num': inline_equation_num
        }
    return para_content

赵小蒙's avatar
赵小蒙 committed
176
def make_standard_format_with_para(pdf_info_dict: list, img_buket_path: str):
赵小蒙's avatar
赵小蒙 committed
177
    content_list = []
赵小蒙's avatar
赵小蒙 committed
178
    for page_info in pdf_info_dict:
179
180
        paras_of_layout = page_info.get("para_blocks")
        if not paras_of_layout:
赵小蒙's avatar
赵小蒙 committed
181
            continue
182
183
        for paras in paras_of_layout:
            for para in paras:
184
                para_content = para_to_standard_format(para, img_buket_path)
185
                content_list.append(para_content)
赵小蒙's avatar
赵小蒙 committed
186
187
188
    return content_list


189
def line_to_standard_format(line, img_buket_path):
赵小蒙's avatar
赵小蒙 committed
190
191
192
193
194
195
196
197
198
199
    line_text = ""
    inline_equation_num = 0
    for span in line['spans']:
        if not span.get('content'):
            if not span.get('image_path'):
                continue
            else:
                if span['type'] == ContentType.Image:
                    content = {
                        'type': 'image',
200
                        'img_path': join_path(img_buket_path, span['image_path'])
赵小蒙's avatar
赵小蒙 committed
201
202
203
204
205
                    }
                    return content
                elif span['type'] == ContentType.Table:
                    content = {
                        'type': 'table',
206
                        'img_path': join_path(img_buket_path, span['image_path'])
赵小蒙's avatar
赵小蒙 committed
207
208
209
210
                    }
                    return content
        else:
            if span['type'] == ContentType.InterlineEquation:
赵小蒙's avatar
赵小蒙 committed
211
                interline_equation = span['content']
赵小蒙's avatar
赵小蒙 committed
212
213
214
215
216
217
                content = {
                    'type': 'equation',
                    'latex': f"$$\n{interline_equation}\n$$"
                }
                return content
            elif span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
218
                inline_equation = span['content']
赵小蒙's avatar
赵小蒙 committed
219
220
221
                line_text += f"${inline_equation}$"
                inline_equation_num += 1
            elif span['type'] == ContentType.Text:
222
223
                text_content = ocr_escape_special_markdown_char(span['content'])  # 转义特殊符号
                line_text += text_content
赵小蒙's avatar
赵小蒙 committed
224
225
226
227
228
229
230
231
    content = {
        'type': 'text',
        'text': line_text,
        'inline_equation_num': inline_equation_num
    }
    return content


赵小蒙's avatar
赵小蒙 committed
232
def ocr_mk_mm_standard_format(pdf_info_dict: list):
赵小蒙's avatar
update  
赵小蒙 committed
233
    """
234
    content_list
赵小蒙's avatar
赵小蒙 committed
235
236
237
238
239
    type         string      image/text/table/equation(行间的单独拿出来,行内的和text合并)
    latex        string      latex文本字段。
    text         string      纯文本格式的文本数据。
    md           string      markdown格式的文本数据。
    img_path     string      s3://full/path/to/img.jpg
赵小蒙's avatar
update  
赵小蒙 committed
240
    """
赵小蒙's avatar
赵小蒙 committed
241
    content_list = []
赵小蒙's avatar
赵小蒙 committed
242
    for page_info in pdf_info_dict:
赵小蒙's avatar
赵小蒙 committed
243
244
245
246
247
248
249
250
        blocks = page_info.get("preproc_blocks")
        if not blocks:
            continue
        for block in blocks:
            for line in block['lines']:
                content = line_to_standard_format(line)
                content_list.append(content)
    return content_list