magic-pdf 0.5.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- magic_pdf/__init__.py +0 -0
- magic_pdf/cli/__init__.py +0 -0
- magic_pdf/cli/magicpdf.py +294 -0
- magic_pdf/dict2md/__init__.py +0 -0
- magic_pdf/dict2md/mkcontent.py +397 -0
- magic_pdf/dict2md/ocr_mkcontent.py +356 -0
- magic_pdf/filter/__init__.py +0 -0
- magic_pdf/filter/pdf_classify_by_type.py +381 -0
- magic_pdf/filter/pdf_meta_scan.py +368 -0
- magic_pdf/layout/__init__.py +0 -0
- magic_pdf/layout/bbox_sort.py +681 -0
- magic_pdf/layout/layout_det_utils.py +182 -0
- magic_pdf/layout/layout_sort.py +732 -0
- magic_pdf/layout/layout_spiler_recog.py +101 -0
- magic_pdf/layout/mcol_sort.py +336 -0
- magic_pdf/libs/Constants.py +11 -0
- magic_pdf/libs/MakeContentConfig.py +10 -0
- magic_pdf/libs/ModelBlockTypeEnum.py +9 -0
- magic_pdf/libs/__init__.py +0 -0
- magic_pdf/libs/boxbase.py +408 -0
- magic_pdf/libs/calc_span_stats.py +239 -0
- magic_pdf/libs/commons.py +204 -0
- magic_pdf/libs/config_reader.py +63 -0
- magic_pdf/libs/convert_utils.py +5 -0
- magic_pdf/libs/coordinate_transform.py +9 -0
- magic_pdf/libs/detect_language_from_model.py +21 -0
- magic_pdf/libs/draw_bbox.py +227 -0
- magic_pdf/libs/drop_reason.py +27 -0
- magic_pdf/libs/drop_tag.py +19 -0
- magic_pdf/libs/hash_utils.py +15 -0
- magic_pdf/libs/json_compressor.py +27 -0
- magic_pdf/libs/language.py +31 -0
- magic_pdf/libs/markdown_utils.py +31 -0
- magic_pdf/libs/math.py +9 -0
- magic_pdf/libs/nlp_utils.py +203 -0
- magic_pdf/libs/ocr_content_type.py +21 -0
- magic_pdf/libs/path_utils.py +23 -0
- magic_pdf/libs/pdf_image_tools.py +33 -0
- magic_pdf/libs/safe_filename.py +11 -0
- magic_pdf/libs/textbase.py +33 -0
- magic_pdf/libs/version.py +1 -0
- magic_pdf/libs/vis_utils.py +308 -0
- magic_pdf/model/__init__.py +0 -0
- magic_pdf/model/doc_analyze_by_360layout.py +8 -0
- magic_pdf/model/doc_analyze_by_pp_structurev2.py +125 -0
- magic_pdf/model/magic_model.py +632 -0
- magic_pdf/para/__init__.py +0 -0
- magic_pdf/para/block_continuation_processor.py +562 -0
- magic_pdf/para/block_termination_processor.py +480 -0
- magic_pdf/para/commons.py +222 -0
- magic_pdf/para/denoise.py +246 -0
- magic_pdf/para/draw.py +121 -0
- magic_pdf/para/exceptions.py +198 -0
- magic_pdf/para/layout_match_processor.py +40 -0
- magic_pdf/para/para_pipeline.py +297 -0
- magic_pdf/para/para_split.py +644 -0
- magic_pdf/para/para_split_v2.py +772 -0
- magic_pdf/para/raw_processor.py +207 -0
- magic_pdf/para/stats.py +268 -0
- magic_pdf/para/title_processor.py +1014 -0
- magic_pdf/pdf_parse_by_ocr.py +219 -0
- magic_pdf/pdf_parse_by_ocr_v2.py +17 -0
- magic_pdf/pdf_parse_by_txt.py +410 -0
- magic_pdf/pdf_parse_by_txt_v2.py +56 -0
- magic_pdf/pdf_parse_for_train.py +685 -0
- magic_pdf/pdf_parse_union_core.py +241 -0
- magic_pdf/pipe/AbsPipe.py +112 -0
- magic_pdf/pipe/OCRPipe.py +28 -0
- magic_pdf/pipe/TXTPipe.py +29 -0
- magic_pdf/pipe/UNIPipe.py +83 -0
- magic_pdf/pipe/__init__.py +0 -0
- magic_pdf/post_proc/__init__.py +0 -0
- magic_pdf/post_proc/detect_para.py +3472 -0
- magic_pdf/post_proc/pdf_post_filter.py +67 -0
- magic_pdf/post_proc/remove_footnote.py +153 -0
- magic_pdf/pre_proc/__init__.py +0 -0
- magic_pdf/pre_proc/citationmarker_remove.py +157 -0
- magic_pdf/pre_proc/construct_page_dict.py +72 -0
- magic_pdf/pre_proc/cut_image.py +71 -0
- magic_pdf/pre_proc/detect_equation.py +134 -0
- magic_pdf/pre_proc/detect_footer_by_model.py +64 -0
- magic_pdf/pre_proc/detect_footer_header_by_statistics.py +284 -0
- magic_pdf/pre_proc/detect_footnote.py +170 -0
- magic_pdf/pre_proc/detect_header.py +64 -0
- magic_pdf/pre_proc/detect_images.py +647 -0
- magic_pdf/pre_proc/detect_page_number.py +64 -0
- magic_pdf/pre_proc/detect_tables.py +62 -0
- magic_pdf/pre_proc/equations_replace.py +559 -0
- magic_pdf/pre_proc/fix_image.py +244 -0
- magic_pdf/pre_proc/fix_table.py +270 -0
- magic_pdf/pre_proc/main_text_font.py +23 -0
- magic_pdf/pre_proc/ocr_detect_all_bboxes.py +115 -0
- magic_pdf/pre_proc/ocr_detect_layout.py +133 -0
- magic_pdf/pre_proc/ocr_dict_merge.py +336 -0
- magic_pdf/pre_proc/ocr_span_list_modify.py +258 -0
- magic_pdf/pre_proc/pdf_pre_filter.py +74 -0
- magic_pdf/pre_proc/post_layout_split.py +0 -0
- magic_pdf/pre_proc/remove_bbox_overlap.py +98 -0
- magic_pdf/pre_proc/remove_colored_strip_bbox.py +79 -0
- magic_pdf/pre_proc/remove_footer_header.py +117 -0
- magic_pdf/pre_proc/remove_rotate_bbox.py +188 -0
- magic_pdf/pre_proc/resolve_bbox_conflict.py +191 -0
- magic_pdf/pre_proc/solve_line_alien.py +29 -0
- magic_pdf/pre_proc/statistics.py +12 -0
- magic_pdf/rw/AbsReaderWriter.py +34 -0
- magic_pdf/rw/DiskReaderWriter.py +66 -0
- magic_pdf/rw/S3ReaderWriter.py +107 -0
- magic_pdf/rw/__init__.py +0 -0
- magic_pdf/spark/__init__.py +0 -0
- magic_pdf/spark/spark_api.py +51 -0
- magic_pdf/train_utils/__init__.py +0 -0
- magic_pdf/train_utils/convert_to_train_format.py +65 -0
- magic_pdf/train_utils/extract_caption.py +59 -0
- magic_pdf/train_utils/remove_footer_header.py +159 -0
- magic_pdf/train_utils/vis_utils.py +327 -0
- magic_pdf/user_api.py +136 -0
- magic_pdf-0.5.4.dist-info/LICENSE.md +661 -0
- magic_pdf-0.5.4.dist-info/METADATA +24 -0
- magic_pdf-0.5.4.dist-info/RECORD +121 -0
- magic_pdf-0.5.4.dist-info/WHEEL +5 -0
- magic_pdf-0.5.4.dist-info/top_level.txt +1 -0
@@ -0,0 +1,219 @@
|
|
1
|
+
import time
|
2
|
+
from loguru import logger
|
3
|
+
from magic_pdf.libs.commons import (
|
4
|
+
fitz,
|
5
|
+
get_delta_time,
|
6
|
+
get_docx_model_output,
|
7
|
+
)
|
8
|
+
from magic_pdf.libs.convert_utils import dict_to_list
|
9
|
+
from magic_pdf.libs.coordinate_transform import get_scale_ratio
|
10
|
+
from magic_pdf.libs.drop_tag import DropTag
|
11
|
+
from magic_pdf.libs.hash_utils import compute_md5
|
12
|
+
from magic_pdf.libs.ocr_content_type import ContentType
|
13
|
+
from magic_pdf.para.para_split import para_split
|
14
|
+
from magic_pdf.pre_proc.construct_page_dict import ocr_construct_page_component
|
15
|
+
from magic_pdf.pre_proc.detect_footer_by_model import parse_footers
|
16
|
+
from magic_pdf.pre_proc.detect_footnote import parse_footnotes_by_model
|
17
|
+
from magic_pdf.pre_proc.detect_header import parse_headers
|
18
|
+
from magic_pdf.pre_proc.detect_page_number import parse_pageNos
|
19
|
+
from magic_pdf.pre_proc.cut_image import ocr_cut_image_and_table
|
20
|
+
from magic_pdf.pre_proc.ocr_detect_layout import layout_detect
|
21
|
+
from magic_pdf.pre_proc.ocr_dict_merge import (
|
22
|
+
merge_spans_to_line_by_layout, merge_lines_to_block,
|
23
|
+
)
|
24
|
+
from magic_pdf.pre_proc.ocr_span_list_modify import remove_spans_by_bboxes, remove_overlaps_min_spans, \
|
25
|
+
adjust_bbox_for_standalone_block, modify_y_axis, modify_inline_equation, get_qa_need_list, \
|
26
|
+
remove_spans_by_bboxes_dict
|
27
|
+
from magic_pdf.pre_proc.remove_bbox_overlap import remove_overlap_between_bbox_for_span
|
28
|
+
|
29
|
+
|
30
|
+
def parse_pdf_by_ocr(
|
31
|
+
pdf_bytes,
|
32
|
+
pdf_model_output,
|
33
|
+
imageWriter,
|
34
|
+
start_page_id=0,
|
35
|
+
end_page_id=None,
|
36
|
+
debug_mode=False,
|
37
|
+
):
|
38
|
+
pdf_bytes_md5 = compute_md5(pdf_bytes)
|
39
|
+
|
40
|
+
pdf_docs = fitz.open("pdf", pdf_bytes)
|
41
|
+
# 初始化空的pdf_info_dict
|
42
|
+
pdf_info_dict = {}
|
43
|
+
|
44
|
+
start_time = time.time()
|
45
|
+
|
46
|
+
end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
|
47
|
+
for page_id in range(start_page_id, end_page_id + 1):
|
48
|
+
|
49
|
+
# 获取当前页的page对象
|
50
|
+
page = pdf_docs[page_id]
|
51
|
+
# 获取当前页的宽高
|
52
|
+
page_w = page.rect.width
|
53
|
+
page_h = page.rect.height
|
54
|
+
|
55
|
+
if debug_mode:
|
56
|
+
time_now = time.time()
|
57
|
+
logger.info(
|
58
|
+
f"page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}"
|
59
|
+
)
|
60
|
+
start_time = time_now
|
61
|
+
|
62
|
+
# 获取当前页的模型数据
|
63
|
+
ocr_page_info = get_docx_model_output(
|
64
|
+
pdf_model_output, page_id
|
65
|
+
)
|
66
|
+
|
67
|
+
"""从json中获取每页的页码、页眉、页脚的bbox"""
|
68
|
+
page_no_bboxes = parse_pageNos(page_id, page, ocr_page_info)
|
69
|
+
header_bboxes = parse_headers(page_id, page, ocr_page_info)
|
70
|
+
footer_bboxes = parse_footers(page_id, page, ocr_page_info)
|
71
|
+
footnote_bboxes = parse_footnotes_by_model(page_id, page, ocr_page_info, debug_mode=debug_mode)
|
72
|
+
|
73
|
+
# 构建需要remove的bbox字典
|
74
|
+
need_remove_spans_bboxes_dict = {
|
75
|
+
DropTag.PAGE_NUMBER: page_no_bboxes,
|
76
|
+
DropTag.HEADER: header_bboxes,
|
77
|
+
DropTag.FOOTER: footer_bboxes,
|
78
|
+
DropTag.FOOTNOTE: footnote_bboxes,
|
79
|
+
}
|
80
|
+
|
81
|
+
layout_dets = ocr_page_info["layout_dets"]
|
82
|
+
spans = []
|
83
|
+
|
84
|
+
# 计算模型坐标和pymu坐标的缩放比例
|
85
|
+
horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(
|
86
|
+
ocr_page_info, page
|
87
|
+
)
|
88
|
+
|
89
|
+
for layout_det in layout_dets:
|
90
|
+
category_id = layout_det["category_id"]
|
91
|
+
allow_category_id_list = [1, 7, 13, 14, 15]
|
92
|
+
if category_id in allow_category_id_list:
|
93
|
+
x0, y0, _, _, x1, y1, _, _ = layout_det["poly"]
|
94
|
+
bbox = [
|
95
|
+
int(x0 / horizontal_scale_ratio),
|
96
|
+
int(y0 / vertical_scale_ratio),
|
97
|
+
int(x1 / horizontal_scale_ratio),
|
98
|
+
int(y1 / vertical_scale_ratio),
|
99
|
+
]
|
100
|
+
# 删除高度或者宽度为0的spans
|
101
|
+
if bbox[2] - bbox[0] == 0 or bbox[3] - bbox[1] == 0:
|
102
|
+
continue
|
103
|
+
"""要删除的"""
|
104
|
+
# 3: 'header', # 页眉
|
105
|
+
# 4: 'page number', # 页码
|
106
|
+
# 5: 'footnote', # 脚注
|
107
|
+
# 6: 'footer', # 页脚
|
108
|
+
"""当成span拼接的"""
|
109
|
+
# 1: 'image', # 图片
|
110
|
+
# 7: 'table', # 表格
|
111
|
+
# 13: 'inline_equation', # 行内公式
|
112
|
+
# 14: 'interline_equation', # 行间公式
|
113
|
+
# 15: 'text', # ocr识别文本
|
114
|
+
"""layout信息"""
|
115
|
+
# 11: 'full column', # 单栏
|
116
|
+
# 12: 'sub column', # 多栏
|
117
|
+
span = {
|
118
|
+
"bbox": bbox,
|
119
|
+
}
|
120
|
+
if category_id == 1:
|
121
|
+
span["type"] = ContentType.Image
|
122
|
+
|
123
|
+
elif category_id == 7:
|
124
|
+
span["type"] = ContentType.Table
|
125
|
+
|
126
|
+
elif category_id == 13:
|
127
|
+
span["content"] = layout_det["latex"]
|
128
|
+
span["type"] = ContentType.InlineEquation
|
129
|
+
elif category_id == 14:
|
130
|
+
span["content"] = layout_det["latex"]
|
131
|
+
span["type"] = ContentType.InterlineEquation
|
132
|
+
elif category_id == 15:
|
133
|
+
span["content"] = layout_det["text"]
|
134
|
+
span["type"] = ContentType.Text
|
135
|
+
# print(span)
|
136
|
+
spans.append(span)
|
137
|
+
else:
|
138
|
+
continue
|
139
|
+
|
140
|
+
'''删除重叠spans中较小的那些'''
|
141
|
+
spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)
|
142
|
+
|
143
|
+
'''
|
144
|
+
删除remove_span_block_bboxes中的bbox
|
145
|
+
并增加drop相关数据
|
146
|
+
'''
|
147
|
+
spans, dropped_spans_by_removed_bboxes = remove_spans_by_bboxes_dict(spans, need_remove_spans_bboxes_dict)
|
148
|
+
|
149
|
+
'''对image和table截图'''
|
150
|
+
spans = ocr_cut_image_and_table(spans, page, page_id, pdf_bytes_md5, imageWriter)
|
151
|
+
|
152
|
+
'''行内公式调整, 高度调整至与同行文字高度一致(优先左侧, 其次右侧)'''
|
153
|
+
displayed_list = []
|
154
|
+
text_inline_lines = []
|
155
|
+
modify_y_axis(spans, displayed_list, text_inline_lines)
|
156
|
+
|
157
|
+
'''模型识别错误的行间公式, type类型转换成行内公式'''
|
158
|
+
spans = modify_inline_equation(spans, displayed_list, text_inline_lines)
|
159
|
+
|
160
|
+
'''bbox去除粘连'''
|
161
|
+
spans = remove_overlap_between_bbox_for_span(spans)
|
162
|
+
'''
|
163
|
+
对tpye=["interline_equation", "image", "table"]进行额外处理,
|
164
|
+
如果左边有字的话,将该span的bbox中y0调整至不高于文字的y0
|
165
|
+
'''
|
166
|
+
spans = adjust_bbox_for_standalone_block(spans)
|
167
|
+
|
168
|
+
'''从ocr_page_info中解析layout信息(按自然阅读方向排序,并修复重叠和交错的bad case)'''
|
169
|
+
layout_bboxes, layout_tree = layout_detect(ocr_page_info['subfield_dets'], page, ocr_page_info)
|
170
|
+
|
171
|
+
'''将spans合并成line(在layout内,从上到下,从左到右)'''
|
172
|
+
lines, dropped_spans_by_layout = merge_spans_to_line_by_layout(spans, layout_bboxes)
|
173
|
+
|
174
|
+
'''将lines合并成block'''
|
175
|
+
blocks = merge_lines_to_block(lines)
|
176
|
+
|
177
|
+
'''获取QA需要外置的list'''
|
178
|
+
images, tables, interline_equations, inline_equations = get_qa_need_list(blocks)
|
179
|
+
|
180
|
+
'''drop的span_list合并'''
|
181
|
+
dropped_spans = []
|
182
|
+
dropped_spans.extend(dropped_spans_by_span_overlap)
|
183
|
+
dropped_spans.extend(dropped_spans_by_removed_bboxes)
|
184
|
+
dropped_spans.extend(dropped_spans_by_layout)
|
185
|
+
|
186
|
+
dropped_text_block = []
|
187
|
+
dropped_image_block = []
|
188
|
+
dropped_table_block = []
|
189
|
+
dropped_equation_block = []
|
190
|
+
for span in dropped_spans:
|
191
|
+
# drop出的spans进行分类
|
192
|
+
if span['type'] == ContentType.Text:
|
193
|
+
dropped_text_block.append(span)
|
194
|
+
elif span['type'] == ContentType.Image:
|
195
|
+
dropped_image_block.append(span)
|
196
|
+
elif span['type'] == ContentType.Table:
|
197
|
+
dropped_table_block.append(span)
|
198
|
+
elif span['type'] in [ContentType.InlineEquation, ContentType.InterlineEquation]:
|
199
|
+
dropped_equation_block.append(span)
|
200
|
+
|
201
|
+
'''构造pdf_info_dict'''
|
202
|
+
page_info = ocr_construct_page_component(blocks, layout_bboxes, page_id, page_w, page_h, layout_tree,
|
203
|
+
images, tables, interline_equations, inline_equations,
|
204
|
+
dropped_text_block, dropped_image_block, dropped_table_block,
|
205
|
+
dropped_equation_block,
|
206
|
+
need_remove_spans_bboxes_dict)
|
207
|
+
pdf_info_dict[f"page_{page_id}"] = page_info
|
208
|
+
|
209
|
+
"""分段"""
|
210
|
+
|
211
|
+
para_split(pdf_info_dict, debug_mode=debug_mode)
|
212
|
+
|
213
|
+
"""dict转list"""
|
214
|
+
pdf_info_list = dict_to_list(pdf_info_dict)
|
215
|
+
new_pdf_info_dict = {
|
216
|
+
"pdf_info": pdf_info_list,
|
217
|
+
}
|
218
|
+
|
219
|
+
return new_pdf_info_dict
|
@@ -0,0 +1,17 @@
|
|
1
|
+
from magic_pdf.pdf_parse_union_core import pdf_parse_union
|
2
|
+
|
3
|
+
def parse_pdf_by_ocr(pdf_bytes,
|
4
|
+
model_list,
|
5
|
+
imageWriter,
|
6
|
+
start_page_id=0,
|
7
|
+
end_page_id=None,
|
8
|
+
debug_mode=False,
|
9
|
+
):
|
10
|
+
return pdf_parse_union(pdf_bytes,
|
11
|
+
model_list,
|
12
|
+
imageWriter,
|
13
|
+
"ocr",
|
14
|
+
start_page_id=start_page_id,
|
15
|
+
end_page_id=end_page_id,
|
16
|
+
debug_mode=debug_mode,
|
17
|
+
)
|
@@ -0,0 +1,410 @@
|
|
1
|
+
import time
|
2
|
+
|
3
|
+
# from anyio import Path
|
4
|
+
|
5
|
+
from magic_pdf.libs.commons import fitz, get_delta_time, get_img_s3_client, get_docx_model_output
|
6
|
+
import json
|
7
|
+
import os
|
8
|
+
import math
|
9
|
+
from loguru import logger
|
10
|
+
from magic_pdf.layout.bbox_sort import (
|
11
|
+
prepare_bboxes_for_layout_split,
|
12
|
+
)
|
13
|
+
from magic_pdf.layout.layout_sort import LAYOUT_UNPROC, get_bboxes_layout, get_columns_cnt_of_layout, sort_text_block
|
14
|
+
from magic_pdf.libs.convert_utils import dict_to_list
|
15
|
+
from magic_pdf.libs.drop_reason import DropReason
|
16
|
+
from magic_pdf.libs.hash_utils import compute_md5
|
17
|
+
from magic_pdf.libs.markdown_utils import escape_special_markdown_char
|
18
|
+
from magic_pdf.libs.safe_filename import sanitize_filename
|
19
|
+
from magic_pdf.libs.vis_utils import draw_bbox_on_page, draw_layout_bbox_on_page
|
20
|
+
from magic_pdf.pre_proc.cut_image import txt_save_images_by_bboxes
|
21
|
+
from magic_pdf.pre_proc.detect_images import parse_images
|
22
|
+
from magic_pdf.pre_proc.detect_tables import parse_tables # 获取tables的bbox
|
23
|
+
from magic_pdf.pre_proc.detect_equation import parse_equations # 获取equations的bbox
|
24
|
+
from magic_pdf.pre_proc.detect_header import parse_headers # 获取headers的bbox
|
25
|
+
from magic_pdf.pre_proc.detect_page_number import parse_pageNos # 获取pageNos的bbox
|
26
|
+
from magic_pdf.pre_proc.detect_footnote import parse_footnotes_by_model, parse_footnotes_by_rule # 获取footnotes的bbox
|
27
|
+
from magic_pdf.pre_proc.detect_footer_by_model import parse_footers # 获取footers的bbox
|
28
|
+
|
29
|
+
from magic_pdf.post_proc.detect_para import (
|
30
|
+
ParaProcessPipeline,
|
31
|
+
TitleDetectionException,
|
32
|
+
TitleLevelException,
|
33
|
+
ParaSplitException,
|
34
|
+
ParaMergeException,
|
35
|
+
DenseSingleLineBlockException,
|
36
|
+
)
|
37
|
+
from magic_pdf.pre_proc.main_text_font import get_main_text_font
|
38
|
+
from magic_pdf.pre_proc.remove_colored_strip_bbox import remove_colored_strip_textblock
|
39
|
+
from magic_pdf.pre_proc.remove_footer_header import remove_headder_footer_one_page
|
40
|
+
|
41
|
+
'''
|
42
|
+
from para.para_pipeline import ParaProcessPipeline
|
43
|
+
from para.exceptions import (
|
44
|
+
TitleDetectionException,
|
45
|
+
TitleLevelException,
|
46
|
+
ParaSplitException,
|
47
|
+
ParaMergeException,
|
48
|
+
DenseSingleLineBlockException,
|
49
|
+
)
|
50
|
+
'''
|
51
|
+
|
52
|
+
from magic_pdf.post_proc.remove_footnote import merge_footnote_blocks, remove_footnote_blocks
|
53
|
+
from magic_pdf.pre_proc.citationmarker_remove import remove_citation_marker
|
54
|
+
from magic_pdf.pre_proc.equations_replace import combine_chars_to_pymudict, remove_chars_in_text_blocks, replace_equations_in_textblock
|
55
|
+
from magic_pdf.pre_proc.pdf_pre_filter import pdf_filter
|
56
|
+
from magic_pdf.pre_proc.detect_footer_header_by_statistics import drop_footer_header
|
57
|
+
from magic_pdf.pre_proc.construct_page_dict import construct_page_component
|
58
|
+
from magic_pdf.pre_proc.fix_image import combine_images, fix_image_vertical, fix_seperated_image, include_img_title
|
59
|
+
from magic_pdf.post_proc.pdf_post_filter import pdf_post_filter
|
60
|
+
from magic_pdf.pre_proc.remove_rotate_bbox import get_side_boundry, remove_rotate_side_textblock, remove_side_blank_block
|
61
|
+
from magic_pdf.pre_proc.resolve_bbox_conflict import check_text_block_horizontal_overlap, resolve_bbox_overlap_conflict
|
62
|
+
from magic_pdf.pre_proc.fix_table import fix_table_text_block, fix_tables, include_table_title
|
63
|
+
from magic_pdf.pre_proc.solve_line_alien import solve_inline_too_large_interval
|
64
|
+
|
65
|
+
denseSingleLineBlockException_msg = DenseSingleLineBlockException().message
|
66
|
+
titleDetectionException_msg = TitleDetectionException().message
|
67
|
+
titleLevelException_msg = TitleLevelException().message
|
68
|
+
paraSplitException_msg = ParaSplitException().message
|
69
|
+
paraMergeException_msg = ParaMergeException().message
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
|
74
|
+
def parse_pdf_by_txt(
|
75
|
+
pdf_bytes,
|
76
|
+
pdf_model_output,
|
77
|
+
imageWriter,
|
78
|
+
start_page_id=0,
|
79
|
+
end_page_id=None,
|
80
|
+
debug_mode=False,
|
81
|
+
):
|
82
|
+
pdf_bytes_md5 = compute_md5(pdf_bytes)
|
83
|
+
|
84
|
+
pdf_docs = fitz.open("pdf", pdf_bytes)
|
85
|
+
pdf_info_dict = {}
|
86
|
+
start_time = time.time()
|
87
|
+
|
88
|
+
"""通过统计pdf全篇文字,识别正文字体"""
|
89
|
+
main_text_font = get_main_text_font(pdf_docs)
|
90
|
+
|
91
|
+
end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
|
92
|
+
for page_id in range(start_page_id, end_page_id + 1):
|
93
|
+
page = pdf_docs[page_id]
|
94
|
+
page_width = page.rect.width
|
95
|
+
page_height = page.rect.height
|
96
|
+
|
97
|
+
if debug_mode:
|
98
|
+
time_now = time.time()
|
99
|
+
logger.info(f"page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}")
|
100
|
+
start_time = time_now
|
101
|
+
"""
|
102
|
+
# 通过一个规则,过滤掉单页超过1500非junkimg的pdf
|
103
|
+
# 对单页面非重复id的img数量做统计,如果当前页超过1500则直接return need_drop
|
104
|
+
"""
|
105
|
+
page_imgs = page.get_images()
|
106
|
+
|
107
|
+
# 去除对junkimg的依赖,简化逻辑
|
108
|
+
if len(page_imgs) > 1500: # 如果当前页超过1500张图片,直接跳过
|
109
|
+
logger.warning(f"page_id: {page_id}, img_counts: {len(page_imgs)}, drop this pdf")
|
110
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.HIGH_COMPUTATIONAL_lOAD_BY_IMGS}
|
111
|
+
if not debug_mode:
|
112
|
+
return result
|
113
|
+
|
114
|
+
"""
|
115
|
+
==================================================================================================================================
|
116
|
+
首先获取基本的block数据,对pdf进行分解,获取图片、表格、公式、text的bbox
|
117
|
+
"""
|
118
|
+
# 解析pdf原始文本block
|
119
|
+
text_raw_blocks = page.get_text(
|
120
|
+
"dict",
|
121
|
+
flags=fitz.TEXTFLAGS_TEXT,
|
122
|
+
)["blocks"]
|
123
|
+
model_output_json = get_docx_model_output(pdf_model_output, page_id)
|
124
|
+
|
125
|
+
# 解析图片
|
126
|
+
image_bboxes = parse_images(page_id, page, model_output_json)
|
127
|
+
image_bboxes = fix_image_vertical(image_bboxes, text_raw_blocks) # 修正图片的位置
|
128
|
+
image_bboxes = fix_seperated_image(image_bboxes) # 合并有边重合的图片
|
129
|
+
image_bboxes = include_img_title(text_raw_blocks, image_bboxes) # 向图片上方和下方寻找title,使用规则进行匹配,暂时只支持英文规则
|
130
|
+
"""此时image_bboxes中可能出现这种情况,水平并列的2个图片,下方分别有各自的子标题,2个子标题下方又有大标题(形如Figxxx),会出现2个图片的bbox都包含了这个大标题,这种情况需要把图片合并"""
|
131
|
+
image_bboxes = combine_images(image_bboxes) # 合并图片
|
132
|
+
|
133
|
+
# 解析表格并对table_bboxes进行位置的微调,防止表格周围的文字被截断
|
134
|
+
table_bboxes = parse_tables(page_id, page, model_output_json)
|
135
|
+
table_bboxes = fix_tables(page, table_bboxes, include_table_title=True, scan_line_num=2) # 修正
|
136
|
+
table_bboxes = fix_table_text_block(text_raw_blocks, table_bboxes) # 修正与text block的关系,某些table修正与pymupdf获取到的table内textblock没有完全包含,因此要进行一次修正。
|
137
|
+
#debug_show_bbox(pdf_docs, page_id, table_bboxes, [], [b['bbox'] for b in text_raw_blocks], join_path(save_path, book_name, f"{book_name}_debug.pdf"), 7)
|
138
|
+
table_bboxes = include_table_title(text_raw_blocks, table_bboxes) # 向table上方和下方寻找title,使用规则进行匹配,暂时只支持英文规则
|
139
|
+
|
140
|
+
# 解析公式
|
141
|
+
equations_inline_bboxes, equations_interline_bboxes = parse_equations(page_id, page, model_output_json)
|
142
|
+
|
143
|
+
"""
|
144
|
+
==================================================================================================================================
|
145
|
+
进入预处理-1阶段
|
146
|
+
-------------------
|
147
|
+
# # 解析标题
|
148
|
+
# title_bboxs = parse_titles(page_id, page, model_output_json)
|
149
|
+
# # 评估Layout是否规整、简单
|
150
|
+
# isSimpleLayout_flag, fullColumn_cnt, subColumn_cnt, curPage_loss = evaluate_pdf_layout(page_id, page, model_output_json)
|
151
|
+
接下来开始进行预处理过程
|
152
|
+
"""
|
153
|
+
|
154
|
+
"""去掉每页的页码、页眉、页脚"""
|
155
|
+
page_no_bboxs = parse_pageNos(page_id, page, model_output_json)
|
156
|
+
header_bboxs = parse_headers(page_id, page, model_output_json)
|
157
|
+
footer_bboxs = parse_footers(page_id, page, model_output_json)
|
158
|
+
image_bboxes, table_bboxes, remain_text_blocks, removed_hdr_foot_txt_block, removed_hdr_foot_img_block, removed_hdr_foot_table = remove_headder_footer_one_page(text_raw_blocks, image_bboxes, table_bboxes, header_bboxs, footer_bboxs, page_no_bboxs, page_width, page_height)
|
159
|
+
|
160
|
+
"""去除页面上半部分长条色块内的文本块"""
|
161
|
+
remain_text_blocks, removed_colored_narrow_strip_background_text_block = remove_colored_strip_textblock(remain_text_blocks, page)
|
162
|
+
|
163
|
+
#debug_show_bbox(pdf_docs, page_id, footnote_bboxes_by_model, [b['bbox'] for b in remain_text_blocks], header_bboxs, join_path(save_path, book_name, f"{book_name}_debug.pdf"), 7)
|
164
|
+
|
165
|
+
"""去掉旋转的文字:水印、垂直排列的文字"""
|
166
|
+
remain_text_blocks, removed_non_horz_text_block = remove_rotate_side_textblock(
|
167
|
+
remain_text_blocks, page_width, page_height
|
168
|
+
) # 去掉水印,非水平文字
|
169
|
+
remain_text_blocks, removed_empty_side_block = remove_side_blank_block(remain_text_blocks, page_width, page_height) # 删除页面四周可能会留下的完全空白的textblock,这种block形成原因未知
|
170
|
+
|
171
|
+
"""出现在图片、表格上的文字块去掉,把层叠的图片单独分离出来,不参与layout的计算"""
|
172
|
+
(
|
173
|
+
image_bboxes,
|
174
|
+
table_bboxes,
|
175
|
+
equations_interline_bboxes,
|
176
|
+
equations_inline_bboxes,
|
177
|
+
remain_text_blocks,
|
178
|
+
text_block_on_image_removed,
|
179
|
+
images_overlap_backup,
|
180
|
+
interline_eq_temp_text_block
|
181
|
+
) = resolve_bbox_overlap_conflict(
|
182
|
+
image_bboxes, table_bboxes, equations_interline_bboxes, equations_inline_bboxes, remain_text_blocks
|
183
|
+
)
|
184
|
+
|
185
|
+
# """去掉footnote, 从文字和图片中"""
|
186
|
+
# # 通过模型识别到的footnote
|
187
|
+
# footnote_bboxes_by_model = parse_footnotes_by_model(page_id, page, model_output_json, md_bookname_save_path,
|
188
|
+
# debug_mode=debug_mode)
|
189
|
+
# # 通过规则识别到的footnote
|
190
|
+
# footnote_bboxes_by_rule = parse_footnotes_by_rule(remain_text_blocks, page_height, page_id)
|
191
|
+
"""
|
192
|
+
==================================================================================================================================
|
193
|
+
"""
|
194
|
+
|
195
|
+
# 把图、表、公式都进行截图,保存到存储上,返回图片路径作为内容
|
196
|
+
image_info, image_backup_info, table_info, inline_eq_info, interline_eq_info = txt_save_images_by_bboxes(
|
197
|
+
page_id,
|
198
|
+
page,
|
199
|
+
pdf_bytes_md5,
|
200
|
+
image_bboxes,
|
201
|
+
images_overlap_backup,
|
202
|
+
table_bboxes,
|
203
|
+
equations_inline_bboxes,
|
204
|
+
equations_interline_bboxes,
|
205
|
+
imageWriter
|
206
|
+
) # 只要表格和图片的截图
|
207
|
+
|
208
|
+
""""以下进入到公式替换环节 """
|
209
|
+
char_level_text_blocks = page.get_text("rawdict", flags=fitz.TEXTFLAGS_TEXT)['blocks']
|
210
|
+
remain_text_blocks = combine_chars_to_pymudict(remain_text_blocks, char_level_text_blocks)# 合并chars
|
211
|
+
remain_text_blocks = replace_equations_in_textblock(remain_text_blocks, inline_eq_info, interline_eq_info)
|
212
|
+
remain_text_blocks = remove_citation_marker(remain_text_blocks) # 公式替换之后去角标,防止公式无法替换成功。但是这样也会带来个问题就是把角标当公式。各有优劣。
|
213
|
+
remain_text_blocks = remove_chars_in_text_blocks(remain_text_blocks) # 减少中间态数据体积
|
214
|
+
#debug_show_bbox(pdf_docs, page_id, [b['bbox'] for b in inline_eq_info], [b['bbox'] for b in interline_eq_info], [], join_path(save_path, book_name, f"{book_name}_debug.pdf"), 3)
|
215
|
+
|
216
|
+
"""去掉footnote, 从文字和图片中(先去角标再去footnote试试)"""
|
217
|
+
# 通过模型识别到的footnote
|
218
|
+
footnote_bboxes_by_model = parse_footnotes_by_model(page_id, page, model_output_json, debug_mode=debug_mode)
|
219
|
+
# 通过规则识别到的footnote
|
220
|
+
footnote_bboxes_by_rule = parse_footnotes_by_rule(remain_text_blocks, page_height, page_id, main_text_font)
|
221
|
+
"""进入pdf过滤器,去掉一些不合理的pdf"""
|
222
|
+
is_good_pdf, err = pdf_filter(page, remain_text_blocks, table_bboxes, image_bboxes)
|
223
|
+
if not is_good_pdf:
|
224
|
+
logger.warning(f"page_id: {page_id}, drop this pdf: {pdf_bytes_md5}, reason: {err}")
|
225
|
+
if not debug_mode:
|
226
|
+
return err
|
227
|
+
|
228
|
+
"""
|
229
|
+
==================================================================================================================================
|
230
|
+
进行版面布局切分和过滤
|
231
|
+
"""
|
232
|
+
"""在切分之前,先检查一下bbox是否有左右重叠的情况,如果有,那么就认为这个pdf暂时没有能力处理好,这种左右重叠的情况大概率是由于pdf里的行间公式、表格没有被正确识别出来造成的 """
|
233
|
+
|
234
|
+
is_text_block_horz_overlap = check_text_block_horizontal_overlap(remain_text_blocks, header_bboxs, footer_bboxs)
|
235
|
+
|
236
|
+
if is_text_block_horz_overlap:
|
237
|
+
# debug_show_bbox(pdf_docs, page_id, [b['bbox'] for b in remain_text_blocks], [], [], join_path(save_path, book_name, f"{book_name}_debug.pdf"), 0)
|
238
|
+
logger.warning(f"page_id: {page_id}, drop this pdf: {pdf_bytes_md5}, reason: {DropReason.TEXT_BLCOK_HOR_OVERLAP}")
|
239
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.TEXT_BLCOK_HOR_OVERLAP}
|
240
|
+
if not debug_mode:
|
241
|
+
return result
|
242
|
+
|
243
|
+
"""统一格式化成一个数据结构用于计算layout"""
|
244
|
+
page_y0 = 0 if len(header_bboxs) == 0 else max([b[3] for b in header_bboxs])
|
245
|
+
page_y1 = page_height if len(footer_bboxs) == 0 else min([b[1] for b in footer_bboxs])
|
246
|
+
left_x, right_x = get_side_boundry(removed_non_horz_text_block, page_width, page_height)
|
247
|
+
page_boundry = [math.floor(left_x), page_y0 + 1, math.ceil(right_x), page_y1 - 1]
|
248
|
+
# 返回的是一个数组,每个元素[x0, y0, x1, y1, block_content, idx_x, idx_y], 初始时候idx_x, idx_y都是None. 对于图片、公式来说,block_content是图片的地址, 对于段落来说,block_content是段落的内容
|
249
|
+
|
250
|
+
all_bboxes = prepare_bboxes_for_layout_split(
|
251
|
+
image_info, image_backup_info, table_info, inline_eq_info, interline_eq_info, remain_text_blocks, page_boundry, page)
|
252
|
+
#debug_show_bbox(pdf_docs, page_id, [], [], all_bboxes, join_path(save_path, book_name, f"{book_name}_debug.pdf"), 1)
|
253
|
+
"""page_y0, page_y1能够过滤掉页眉和页脚,不会算作layout内"""
|
254
|
+
layout_bboxes, layout_tree = get_bboxes_layout(all_bboxes, page_boundry, page_id)
|
255
|
+
|
256
|
+
if len(remain_text_blocks)>0 and len(all_bboxes)>0 and len(layout_bboxes)==0:
|
257
|
+
logger.warning(f"page_id: {page_id}, drop this pdf: {pdf_bytes_md5}, reason: {DropReason.CAN_NOT_DETECT_PAGE_LAYOUT}")
|
258
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.CAN_NOT_DETECT_PAGE_LAYOUT}
|
259
|
+
if not debug_mode:
|
260
|
+
return result
|
261
|
+
|
262
|
+
"""以下去掉复杂的布局和超过2列的布局"""
|
263
|
+
if any([lay["layout_label"] == LAYOUT_UNPROC for lay in layout_bboxes]): # 复杂的布局
|
264
|
+
logger.warning(f"page_id: {page_id}, drop this pdf: {pdf_bytes_md5}, reason: {DropReason.COMPLICATED_LAYOUT}")
|
265
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.COMPLICATED_LAYOUT}
|
266
|
+
if not debug_mode:
|
267
|
+
return result
|
268
|
+
|
269
|
+
layout_column_width = get_columns_cnt_of_layout(layout_tree)
|
270
|
+
if layout_column_width > 2: # 去掉超过2列的布局pdf
|
271
|
+
logger.warning(f"page_id: {page_id}, drop this pdf: {pdf_bytes_md5}, reason: {DropReason.TOO_MANY_LAYOUT_COLUMNS}")
|
272
|
+
result = {
|
273
|
+
"_need_drop": True,
|
274
|
+
"_drop_reason": DropReason.TOO_MANY_LAYOUT_COLUMNS,
|
275
|
+
"extra_info": {"column_cnt": layout_column_width},
|
276
|
+
}
|
277
|
+
if not debug_mode:
|
278
|
+
return result
|
279
|
+
|
280
|
+
|
281
|
+
"""
|
282
|
+
==================================================================================================================================
|
283
|
+
构造出下游需要的数据结构
|
284
|
+
"""
|
285
|
+
remain_text_blocks = remain_text_blocks + interline_eq_temp_text_block # 把计算layout时候临时删除的行间公式再放回去,防止行间公式替换的时候丢失。
|
286
|
+
removed_text_blocks = []
|
287
|
+
removed_text_blocks.extend(removed_hdr_foot_txt_block)
|
288
|
+
# removed_text_blocks.extend(removed_footnote_text_block)
|
289
|
+
removed_text_blocks.extend(text_block_on_image_removed)
|
290
|
+
removed_text_blocks.extend(removed_non_horz_text_block)
|
291
|
+
removed_text_blocks.extend(removed_colored_narrow_strip_background_text_block)
|
292
|
+
|
293
|
+
removed_images = []
|
294
|
+
# removed_images.extend(footnote_imgs)
|
295
|
+
removed_images.extend(removed_hdr_foot_img_block)
|
296
|
+
|
297
|
+
images_backup = []
|
298
|
+
images_backup.extend(image_backup_info)
|
299
|
+
remain_text_blocks = escape_special_markdown_char(remain_text_blocks) # 转义span里的text
|
300
|
+
sorted_text_remain_text_block = sort_text_block(remain_text_blocks, layout_bboxes)
|
301
|
+
|
302
|
+
footnote_bboxes_tmp = []
|
303
|
+
footnote_bboxes_tmp.extend(footnote_bboxes_by_model)
|
304
|
+
footnote_bboxes_tmp.extend(footnote_bboxes_by_rule)
|
305
|
+
|
306
|
+
|
307
|
+
page_info = construct_page_component(
|
308
|
+
page_id,
|
309
|
+
image_info,
|
310
|
+
table_info,
|
311
|
+
sorted_text_remain_text_block,
|
312
|
+
layout_bboxes,
|
313
|
+
inline_eq_info,
|
314
|
+
interline_eq_info,
|
315
|
+
page.get_text("dict", flags=fitz.TEXTFLAGS_TEXT)["blocks"],
|
316
|
+
removed_text_blocks=removed_text_blocks,
|
317
|
+
removed_image_blocks=removed_images,
|
318
|
+
images_backup=images_backup,
|
319
|
+
droped_table_block=[],
|
320
|
+
table_backup=[],
|
321
|
+
layout_tree=layout_tree,
|
322
|
+
page_w=page.rect.width,
|
323
|
+
page_h=page.rect.height,
|
324
|
+
footnote_bboxes_tmp=footnote_bboxes_tmp
|
325
|
+
)
|
326
|
+
pdf_info_dict[f"page_{page_id}"] = page_info
|
327
|
+
|
328
|
+
# end page for
|
329
|
+
|
330
|
+
'''计算后处理阶段耗时'''
|
331
|
+
start_time = time.time()
|
332
|
+
|
333
|
+
"""
|
334
|
+
==================================================================================================================================
|
335
|
+
去掉页眉和页脚,这里需要用到一定的统计量,所以放到最后
|
336
|
+
页眉和页脚主要从文本box和图片box中去除,位于页面的四周。
|
337
|
+
下面函数会直接修改pdf_info_dict,从文字块中、图片中删除属于页眉页脚的内容,删除内容做相对应记录
|
338
|
+
"""
|
339
|
+
# 去页眉页脚
|
340
|
+
header, footer = drop_footer_header(pdf_info_dict)
|
341
|
+
|
342
|
+
"""对单个layout内footnote和他下面的所有textbbox合并"""
|
343
|
+
|
344
|
+
for page_key, page_info in pdf_info_dict.items():
|
345
|
+
page_info = merge_footnote_blocks(page_info, main_text_font)
|
346
|
+
page_info = remove_footnote_blocks(page_info)
|
347
|
+
pdf_info_dict[page_key] = page_info
|
348
|
+
|
349
|
+
"""进入pdf后置过滤器,去掉一些不合理的pdf"""
|
350
|
+
|
351
|
+
i = 0
|
352
|
+
for page_info in pdf_info_dict.values():
|
353
|
+
is_good_pdf, err = pdf_post_filter(page_info)
|
354
|
+
if not is_good_pdf:
|
355
|
+
logger.warning(f"page_id: {i}, drop this pdf: {pdf_bytes_md5}, reason: {err}")
|
356
|
+
if not debug_mode:
|
357
|
+
return err
|
358
|
+
i += 1
|
359
|
+
|
360
|
+
if debug_mode:
|
361
|
+
# 打印后处理阶段耗时
|
362
|
+
logger.info(f"post_processing_time: {get_delta_time(start_time)}")
|
363
|
+
|
364
|
+
"""
|
365
|
+
==================================================================================================================================
|
366
|
+
进入段落处理-2阶段
|
367
|
+
"""
|
368
|
+
|
369
|
+
# 处理行内文字间距较大问题
|
370
|
+
pdf_info_dict = solve_inline_too_large_interval(pdf_info_dict)
|
371
|
+
|
372
|
+
start_time = time.time()
|
373
|
+
|
374
|
+
para_process_pipeline = ParaProcessPipeline()
|
375
|
+
|
376
|
+
def _deal_with_text_exception(error_info):
|
377
|
+
logger.warning(f"page_id: {page_id}, drop this pdf: {pdf_bytes_md5}, reason: {error_info}")
|
378
|
+
if error_info == denseSingleLineBlockException_msg:
|
379
|
+
logger.warning(f"Drop this pdf: {pdf_bytes_md5}, reason: {DropReason.DENSE_SINGLE_LINE_BLOCK}")
|
380
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.DENSE_SINGLE_LINE_BLOCK}
|
381
|
+
return result
|
382
|
+
if error_info == titleDetectionException_msg:
|
383
|
+
logger.warning(f"Drop this pdf: {pdf_bytes_md5}, reason: {DropReason.TITLE_DETECTION_FAILED}")
|
384
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.TITLE_DETECTION_FAILED}
|
385
|
+
return result
|
386
|
+
elif error_info == titleLevelException_msg:
|
387
|
+
logger.warning(f"Drop this pdf: {pdf_bytes_md5}, reason: {DropReason.TITLE_LEVEL_FAILED}")
|
388
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.TITLE_LEVEL_FAILED}
|
389
|
+
return result
|
390
|
+
elif error_info == paraSplitException_msg:
|
391
|
+
logger.warning(f"Drop this pdf: {pdf_bytes_md5}, reason: {DropReason.PARA_SPLIT_FAILED}")
|
392
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.PARA_SPLIT_FAILED}
|
393
|
+
return result
|
394
|
+
elif error_info == paraMergeException_msg:
|
395
|
+
logger.warning(f"Drop this pdf: {pdf_bytes_md5}, reason: {DropReason.PARA_MERGE_FAILED}")
|
396
|
+
result = {"_need_drop": True, "_drop_reason": DropReason.PARA_MERGE_FAILED}
|
397
|
+
return result
|
398
|
+
|
399
|
+
pdf_info_dict, error_info = para_process_pipeline.para_process_pipeline(pdf_info_dict)
|
400
|
+
if error_info is not None:
|
401
|
+
return _deal_with_text_exception(error_info)
|
402
|
+
|
403
|
+
|
404
|
+
"""dict转list"""
|
405
|
+
pdf_info_list = dict_to_list(pdf_info_dict)
|
406
|
+
new_pdf_info_dict = {
|
407
|
+
"pdf_info": pdf_info_list,
|
408
|
+
}
|
409
|
+
|
410
|
+
return new_pdf_info_dict
|