magic-pdf 0.10.1__py3-none-any.whl → 0.10.2__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/filter/pdf_meta_scan.py +3 -17
- magic_pdf/libs/commons.py +0 -161
- magic_pdf/libs/draw_bbox.py +2 -3
- magic_pdf/libs/markdown_utils.py +0 -21
- magic_pdf/libs/pdf_image_tools.py +2 -1
- magic_pdf/libs/version.py +1 -1
- magic_pdf/model/doc_analyze_by_custom_model.py +2 -2
- magic_pdf/model/magic_model.py +0 -30
- magic_pdf/model/sub_modules/ocr/paddleocr/ocr_utils.py +3 -28
- magic_pdf/model/sub_modules/ocr/paddleocr/ppocr_273_mod.py +3 -3
- magic_pdf/para/para_split_v3.py +7 -2
- magic_pdf/pdf_parse_union_core_v2.py +97 -124
- magic_pdf/pre_proc/construct_page_dict.py +0 -55
- magic_pdf/pre_proc/cut_image.py +0 -37
- magic_pdf/pre_proc/ocr_detect_all_bboxes.py +5 -178
- magic_pdf/pre_proc/ocr_dict_merge.py +1 -224
- magic_pdf/pre_proc/ocr_span_list_modify.py +2 -252
- magic_pdf/rw/S3ReaderWriter.py +1 -1
- {magic_pdf-0.10.1.dist-info → magic_pdf-0.10.2.dist-info}/METADATA +3 -77
- {magic_pdf-0.10.1.dist-info → magic_pdf-0.10.2.dist-info}/RECORD +24 -75
- magic_pdf/dict2md/mkcontent.py +0 -438
- magic_pdf/layout/__init__.py +0 -0
- magic_pdf/layout/bbox_sort.py +0 -681
- magic_pdf/layout/layout_det_utils.py +0 -182
- magic_pdf/layout/layout_sort.py +0 -921
- magic_pdf/layout/layout_spiler_recog.py +0 -101
- magic_pdf/layout/mcol_sort.py +0 -336
- magic_pdf/libs/calc_span_stats.py +0 -239
- magic_pdf/libs/detect_language_from_model.py +0 -21
- magic_pdf/libs/nlp_utils.py +0 -203
- magic_pdf/libs/textbase.py +0 -33
- magic_pdf/libs/vis_utils.py +0 -308
- magic_pdf/para/block_continuation_processor.py +0 -562
- magic_pdf/para/block_termination_processor.py +0 -480
- magic_pdf/para/commons.py +0 -222
- magic_pdf/para/denoise.py +0 -246
- magic_pdf/para/draw.py +0 -121
- magic_pdf/para/exceptions.py +0 -198
- magic_pdf/para/layout_match_processor.py +0 -40
- magic_pdf/para/para_split.py +0 -807
- magic_pdf/para/para_split_v2.py +0 -959
- magic_pdf/para/raw_processor.py +0 -207
- magic_pdf/para/stats.py +0 -268
- magic_pdf/para/title_processor.py +0 -1014
- magic_pdf/pdf_parse_union_core.py +0 -345
- magic_pdf/post_proc/__init__.py +0 -0
- magic_pdf/post_proc/detect_para.py +0 -3472
- magic_pdf/post_proc/pdf_post_filter.py +0 -60
- magic_pdf/post_proc/remove_footnote.py +0 -153
- magic_pdf/pre_proc/citationmarker_remove.py +0 -161
- magic_pdf/pre_proc/detect_equation.py +0 -134
- magic_pdf/pre_proc/detect_footer_by_model.py +0 -64
- magic_pdf/pre_proc/detect_footer_header_by_statistics.py +0 -284
- magic_pdf/pre_proc/detect_footnote.py +0 -170
- magic_pdf/pre_proc/detect_header.py +0 -64
- magic_pdf/pre_proc/detect_images.py +0 -647
- magic_pdf/pre_proc/detect_page_number.py +0 -64
- magic_pdf/pre_proc/detect_tables.py +0 -62
- magic_pdf/pre_proc/equations_replace.py +0 -550
- magic_pdf/pre_proc/fix_image.py +0 -244
- magic_pdf/pre_proc/fix_table.py +0 -270
- magic_pdf/pre_proc/main_text_font.py +0 -23
- magic_pdf/pre_proc/ocr_detect_layout.py +0 -133
- magic_pdf/pre_proc/pdf_pre_filter.py +0 -78
- magic_pdf/pre_proc/post_layout_split.py +0 -0
- magic_pdf/pre_proc/remove_colored_strip_bbox.py +0 -101
- magic_pdf/pre_proc/remove_footer_header.py +0 -114
- magic_pdf/pre_proc/remove_rotate_bbox.py +0 -236
- magic_pdf/pre_proc/resolve_bbox_conflict.py +0 -184
- magic_pdf/pre_proc/solve_line_alien.py +0 -29
- magic_pdf/pre_proc/statistics.py +0 -12
- {magic_pdf-0.10.1.dist-info → magic_pdf-0.10.2.dist-info}/LICENSE.md +0 -0
- {magic_pdf-0.10.1.dist-info → magic_pdf-0.10.2.dist-info}/WHEEL +0 -0
- {magic_pdf-0.10.1.dist-info → magic_pdf-0.10.2.dist-info}/entry_points.txt +0 -0
- {magic_pdf-0.10.1.dist-info → magic_pdf-0.10.2.dist-info}/top_level.txt +0 -0
@@ -1,64 +0,0 @@
|
|
1
|
-
from magic_pdf.libs.commons import fitz # pyMuPDF库
|
2
|
-
from magic_pdf.libs.coordinate_transform import get_scale_ratio
|
3
|
-
|
4
|
-
|
5
|
-
def parse_pageNos(page_ID: int, page: fitz.Page, json_from_DocXchain_obj: dict):
|
6
|
-
"""
|
7
|
-
:param page_ID: int类型,当前page在当前pdf文档中是第page_D页。
|
8
|
-
:param page :fitz读取的当前页的内容
|
9
|
-
:param res_dir_path: str类型,是每一个pdf文档,在当前.py文件的目录下生成一个与pdf文档同名的文件夹,res_dir_path就是文件夹的dir
|
10
|
-
:param json_from_DocXchain_obj: dict类型,把pdf文档送入DocXChain模型中后,提取bbox,结果保存到pdf文档同名文件夹下的 page_ID.json文件中了。json_from_DocXchain_obj就是打开后的dict
|
11
|
-
"""
|
12
|
-
|
13
|
-
#--------- 通过json_from_DocXchain来获取 pageNo ---------#
|
14
|
-
pageNo_bbox_from_DocXChain = []
|
15
|
-
|
16
|
-
xf_json = json_from_DocXchain_obj
|
17
|
-
horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(xf_json, page)
|
18
|
-
|
19
|
-
# {0: 'title', # 标题
|
20
|
-
# 1: 'figure', # 图片
|
21
|
-
# 2: 'plain text', # 文本
|
22
|
-
# 3: 'header', # 页眉
|
23
|
-
# 4: 'page number', # 页码
|
24
|
-
# 5: 'footnote', # 脚注
|
25
|
-
# 6: 'footer', # 页脚
|
26
|
-
# 7: 'table', # 表格
|
27
|
-
# 8: 'table caption', # 表格描述
|
28
|
-
# 9: 'figure caption', # 图片描述
|
29
|
-
# 10: 'equation', # 公式
|
30
|
-
# 11: 'full column', # 单栏
|
31
|
-
# 12: 'sub column', # 多栏
|
32
|
-
# 13: 'embedding', # 嵌入公式
|
33
|
-
# 14: 'isolated'} # 单行公式
|
34
|
-
for xf in xf_json['layout_dets']:
|
35
|
-
L = xf['poly'][0] / horizontal_scale_ratio
|
36
|
-
U = xf['poly'][1] / vertical_scale_ratio
|
37
|
-
R = xf['poly'][2] / horizontal_scale_ratio
|
38
|
-
D = xf['poly'][5] / vertical_scale_ratio
|
39
|
-
# L += pageL # 有的页面,artBox偏移了。不在(0,0)
|
40
|
-
# R += pageL
|
41
|
-
# U += pageU
|
42
|
-
# D += pageU
|
43
|
-
L, R = min(L, R), max(L, R)
|
44
|
-
U, D = min(U, D), max(U, D)
|
45
|
-
if xf['category_id'] == 4 and xf['score'] >= 0.3:
|
46
|
-
pageNo_bbox_from_DocXChain.append((L, U, R, D))
|
47
|
-
|
48
|
-
|
49
|
-
pageNo_final_names = []
|
50
|
-
pageNo_final_bboxs = []
|
51
|
-
pageNo_ID = 0
|
52
|
-
for L, U, R, D in pageNo_bbox_from_DocXChain:
|
53
|
-
# cur_pageNo = page.get_pixmap(clip=(L,U,R,D))
|
54
|
-
new_pageNo_name = "pageNo_{}_{}.png".format(page_ID, pageNo_ID) # 页码name
|
55
|
-
# cur_pageNo.save(res_dir_path + '/' + new_pageNo_name) # 把页码存储在新建的文件夹,并命名
|
56
|
-
pageNo_final_names.append(new_pageNo_name) # 把页码的名字存在list中
|
57
|
-
pageNo_final_bboxs.append((L, U, R, D))
|
58
|
-
pageNo_ID += 1
|
59
|
-
|
60
|
-
|
61
|
-
pageNo_final_bboxs.sort(key = lambda LURD: (LURD[1], LURD[0]))
|
62
|
-
curPage_all_pageNo_bboxs = pageNo_final_bboxs
|
63
|
-
return curPage_all_pageNo_bboxs
|
64
|
-
|
@@ -1,62 +0,0 @@
|
|
1
|
-
from magic_pdf.libs.commons import fitz # pyMuPDF库
|
2
|
-
|
3
|
-
|
4
|
-
def parse_tables(page_ID: int, page: fitz.Page, json_from_DocXchain_obj: dict):
|
5
|
-
"""
|
6
|
-
:param page_ID: int类型,当前page在当前pdf文档中是第page_D页。
|
7
|
-
:param page :fitz读取的当前页的内容
|
8
|
-
:param res_dir_path: str类型,是每一个pdf文档,在当前.py文件的目录下生成一个与pdf文档同名的文件夹,res_dir_path就是文件夹的dir
|
9
|
-
:param json_from_DocXchain_obj: dict类型,把pdf文档送入DocXChain模型中后,提取bbox,结果保存到pdf文档同名文件夹下的 page_ID.json文件中了。json_from_DocXchain_obj就是打开后的dict
|
10
|
-
"""
|
11
|
-
DPI = 72 # use this resolution
|
12
|
-
pix = page.get_pixmap(dpi=DPI)
|
13
|
-
pageL = 0
|
14
|
-
pageR = int(pix.w)
|
15
|
-
pageU = 0
|
16
|
-
pageD = int(pix.h)
|
17
|
-
|
18
|
-
|
19
|
-
#--------- 通过json_from_DocXchain来获取 table ---------#
|
20
|
-
table_bbox_from_DocXChain = []
|
21
|
-
|
22
|
-
xf_json = json_from_DocXchain_obj
|
23
|
-
width_from_json = xf_json['page_info']['width']
|
24
|
-
height_from_json = xf_json['page_info']['height']
|
25
|
-
LR_scaleRatio = width_from_json / (pageR - pageL)
|
26
|
-
UD_scaleRatio = height_from_json / (pageD - pageU)
|
27
|
-
|
28
|
-
|
29
|
-
for xf in xf_json['layout_dets']:
|
30
|
-
# {0: 'title', 1: 'figure', 2: 'plain text', 3: 'header', 4: 'page number', 5: 'footnote', 6: 'footer', 7: 'table', 8: 'table caption', 9: 'figure caption', 10: 'equation', 11: 'full column', 12: 'sub column'}
|
31
|
-
# 13: 'embedding', # 嵌入公式
|
32
|
-
# 14: 'isolated'} # 单行公式
|
33
|
-
L = xf['poly'][0] / LR_scaleRatio
|
34
|
-
U = xf['poly'][1] / UD_scaleRatio
|
35
|
-
R = xf['poly'][2] / LR_scaleRatio
|
36
|
-
D = xf['poly'][5] / UD_scaleRatio
|
37
|
-
# L += pageL # 有的页面,artBox偏移了。不在(0,0)
|
38
|
-
# R += pageL
|
39
|
-
# U += pageU
|
40
|
-
# D += pageU
|
41
|
-
L, R = min(L, R), max(L, R)
|
42
|
-
U, D = min(U, D), max(U, D)
|
43
|
-
if xf['category_id'] == 7 and xf['score'] >= 0.3:
|
44
|
-
table_bbox_from_DocXChain.append((L, U, R, D))
|
45
|
-
|
46
|
-
|
47
|
-
table_final_names = []
|
48
|
-
table_final_bboxs = []
|
49
|
-
table_ID = 0
|
50
|
-
for L, U, R, D in table_bbox_from_DocXChain:
|
51
|
-
# cur_table = page.get_pixmap(clip=(L,U,R,D))
|
52
|
-
new_table_name = "table_{}_{}.png".format(page_ID, table_ID) # 表格name
|
53
|
-
# cur_table.save(res_dir_path + '/' + new_table_name) # 把表格存出在新建的文件夹,并命名
|
54
|
-
table_final_names.append(new_table_name) # 把表格的名字存在list中,方便在md中插入引用
|
55
|
-
table_final_bboxs.append((L, U, R, D))
|
56
|
-
table_ID += 1
|
57
|
-
|
58
|
-
|
59
|
-
table_final_bboxs.sort(key = lambda LURD: (LURD[1], LURD[0]))
|
60
|
-
curPage_all_table_bboxs = table_final_bboxs
|
61
|
-
return curPage_all_table_bboxs
|
62
|
-
|
@@ -1,550 +0,0 @@
|
|
1
|
-
"""对pymupdf返回的结构里的公式进行替换,替换为模型识别的公式结果."""
|
2
|
-
|
3
|
-
import json
|
4
|
-
import os
|
5
|
-
from pathlib import Path
|
6
|
-
|
7
|
-
from loguru import logger
|
8
|
-
|
9
|
-
from magic_pdf.config.ocr_content_type import ContentType
|
10
|
-
from magic_pdf.libs.commons import fitz
|
11
|
-
|
12
|
-
TYPE_INLINE_EQUATION = ContentType.InlineEquation
|
13
|
-
TYPE_INTERLINE_EQUATION = ContentType.InterlineEquation
|
14
|
-
|
15
|
-
|
16
|
-
def combine_chars_to_pymudict(block_dict, char_dict):
|
17
|
-
"""把block级别的pymupdf 结构里加入char结构."""
|
18
|
-
# 因为block_dict 被裁剪过,因此先把他和char_dict文字块对齐,才能进行补充
|
19
|
-
char_map = {tuple(item['bbox']): item for item in char_dict}
|
20
|
-
|
21
|
-
for i in range(len(block_dict)): # block
|
22
|
-
block = block_dict[i]
|
23
|
-
key = block['bbox']
|
24
|
-
char_dict_item = char_map[tuple(key)]
|
25
|
-
char_dict_map = {tuple(item['bbox']): item for item in char_dict_item['lines']}
|
26
|
-
for j in range(len(block['lines'])):
|
27
|
-
lines = block['lines'][j]
|
28
|
-
with_char_lines = char_dict_map[lines['bbox']]
|
29
|
-
for k in range(len(lines['spans'])):
|
30
|
-
spans = lines['spans'][k]
|
31
|
-
try:
|
32
|
-
chars = with_char_lines['spans'][k]['chars']
|
33
|
-
except Exception:
|
34
|
-
logger.error(char_dict[i]['lines'][j])
|
35
|
-
|
36
|
-
spans['chars'] = chars
|
37
|
-
|
38
|
-
return block_dict
|
39
|
-
|
40
|
-
|
41
|
-
def calculate_overlap_area_2_minbox_area_ratio(bbox1, min_bbox):
|
42
|
-
"""计算box1和box2的重叠面积占最小面积的box的比例."""
|
43
|
-
# Determine the coordinates of the intersection rectangle
|
44
|
-
x_left = max(bbox1[0], min_bbox[0])
|
45
|
-
y_top = max(bbox1[1], min_bbox[1])
|
46
|
-
x_right = min(bbox1[2], min_bbox[2])
|
47
|
-
y_bottom = min(bbox1[3], min_bbox[3])
|
48
|
-
|
49
|
-
if x_right < x_left or y_bottom < y_top:
|
50
|
-
return 0.0
|
51
|
-
|
52
|
-
# The area of overlap area
|
53
|
-
intersection_area = (x_right - x_left) * (y_bottom - y_top)
|
54
|
-
min_box_area = (min_bbox[3] - min_bbox[1]) * (min_bbox[2] - min_bbox[0])
|
55
|
-
if min_box_area == 0:
|
56
|
-
return 0
|
57
|
-
else:
|
58
|
-
return intersection_area / min_box_area
|
59
|
-
|
60
|
-
|
61
|
-
def _is_xin(bbox1, bbox2):
|
62
|
-
area1 = abs(bbox1[2] - bbox1[0]) * abs(bbox1[3] - bbox1[1])
|
63
|
-
area2 = abs(bbox2[2] - bbox2[0]) * abs(bbox2[3] - bbox2[1])
|
64
|
-
if area1 < area2:
|
65
|
-
ratio = calculate_overlap_area_2_minbox_area_ratio(bbox2, bbox1)
|
66
|
-
else:
|
67
|
-
ratio = calculate_overlap_area_2_minbox_area_ratio(bbox1, bbox2)
|
68
|
-
|
69
|
-
return ratio > 0.6
|
70
|
-
|
71
|
-
|
72
|
-
def remove_text_block_in_interline_equation_bbox(interline_bboxes, text_blocks):
|
73
|
-
"""消除掉整个块都在行间公式块内部的文本块."""
|
74
|
-
for eq_bbox in interline_bboxes:
|
75
|
-
removed_txt_blk = []
|
76
|
-
for text_blk in text_blocks:
|
77
|
-
text_bbox = text_blk['bbox']
|
78
|
-
if (
|
79
|
-
calculate_overlap_area_2_minbox_area_ratio(eq_bbox['bbox'], text_bbox)
|
80
|
-
>= 0.7
|
81
|
-
):
|
82
|
-
removed_txt_blk.append(text_blk)
|
83
|
-
for blk in removed_txt_blk:
|
84
|
-
text_blocks.remove(blk)
|
85
|
-
|
86
|
-
return text_blocks
|
87
|
-
|
88
|
-
|
89
|
-
def _is_in_or_part_overlap(box1, box2) -> bool:
|
90
|
-
"""两个bbox是否有部分重叠或者包含."""
|
91
|
-
if box1 is None or box2 is None:
|
92
|
-
return False
|
93
|
-
|
94
|
-
x0_1, y0_1, x1_1, y1_1 = box1
|
95
|
-
x0_2, y0_2, x1_2, y1_2 = box2
|
96
|
-
|
97
|
-
return not (
|
98
|
-
x1_1 < x0_2 # box1在box2的左边
|
99
|
-
or x0_1 > x1_2 # box1在box2的右边
|
100
|
-
or y1_1 < y0_2 # box1在box2的上边
|
101
|
-
or y0_1 > y1_2
|
102
|
-
) # box1在box2的下边
|
103
|
-
|
104
|
-
|
105
|
-
def remove_text_block_overlap_interline_equation_bbox(
|
106
|
-
interline_eq_bboxes, pymu_block_list
|
107
|
-
):
|
108
|
-
"""消除掉行行内公式有部分重叠的文本块的内容。 同时重新计算消除重叠之后文本块的大小."""
|
109
|
-
deleted_block = []
|
110
|
-
for text_block in pymu_block_list:
|
111
|
-
deleted_line = []
|
112
|
-
for line in text_block['lines']:
|
113
|
-
deleted_span = []
|
114
|
-
for span in line['spans']:
|
115
|
-
deleted_chars = []
|
116
|
-
for char in span['chars']:
|
117
|
-
if any(
|
118
|
-
[
|
119
|
-
(
|
120
|
-
calculate_overlap_area_2_minbox_area_ratio(
|
121
|
-
eq_bbox['bbox'], char['bbox']
|
122
|
-
)
|
123
|
-
> 0.5
|
124
|
-
)
|
125
|
-
for eq_bbox in interline_eq_bboxes
|
126
|
-
]
|
127
|
-
):
|
128
|
-
deleted_chars.append(char)
|
129
|
-
# 检查span里没有char则删除这个span
|
130
|
-
for char in deleted_chars:
|
131
|
-
span['chars'].remove(char)
|
132
|
-
# 重新计算这个span的大小
|
133
|
-
if len(span['chars']) == 0: # 删除这个span
|
134
|
-
deleted_span.append(span)
|
135
|
-
else:
|
136
|
-
span['bbox'] = (
|
137
|
-
min([b['bbox'][0] for b in span['chars']]),
|
138
|
-
min([b['bbox'][1] for b in span['chars']]),
|
139
|
-
max([b['bbox'][2] for b in span['chars']]),
|
140
|
-
max([b['bbox'][3] for b in span['chars']]),
|
141
|
-
)
|
142
|
-
|
143
|
-
# 检查这个span
|
144
|
-
for span in deleted_span:
|
145
|
-
line['spans'].remove(span)
|
146
|
-
if len(line['spans']) == 0: # 删除这个line
|
147
|
-
deleted_line.append(line)
|
148
|
-
else:
|
149
|
-
line['bbox'] = (
|
150
|
-
min([b['bbox'][0] for b in line['spans']]),
|
151
|
-
min([b['bbox'][1] for b in line['spans']]),
|
152
|
-
max([b['bbox'][2] for b in line['spans']]),
|
153
|
-
max([b['bbox'][3] for b in line['spans']]),
|
154
|
-
)
|
155
|
-
|
156
|
-
# 检查这个block是否可以删除
|
157
|
-
for line in deleted_line:
|
158
|
-
text_block['lines'].remove(line)
|
159
|
-
if len(text_block['lines']) == 0: # 删除block
|
160
|
-
deleted_block.append(text_block)
|
161
|
-
else:
|
162
|
-
text_block['bbox'] = (
|
163
|
-
min([b['bbox'][0] for b in text_block['lines']]),
|
164
|
-
min([b['bbox'][1] for b in text_block['lines']]),
|
165
|
-
max([b['bbox'][2] for b in text_block['lines']]),
|
166
|
-
max([b['bbox'][3] for b in text_block['lines']]),
|
167
|
-
)
|
168
|
-
|
169
|
-
# 检查text block删除
|
170
|
-
for block in deleted_block:
|
171
|
-
pymu_block_list.remove(block)
|
172
|
-
if len(pymu_block_list) == 0:
|
173
|
-
return []
|
174
|
-
|
175
|
-
return pymu_block_list
|
176
|
-
|
177
|
-
|
178
|
-
def insert_interline_equations_textblock(interline_eq_bboxes, pymu_block_list):
|
179
|
-
"""在行间公式对应的地方插上一个伪造的block."""
|
180
|
-
for eq in interline_eq_bboxes:
|
181
|
-
bbox = eq['bbox']
|
182
|
-
latex_content = eq['latex']
|
183
|
-
text_block = {
|
184
|
-
'number': len(pymu_block_list),
|
185
|
-
'type': 0,
|
186
|
-
'bbox': bbox,
|
187
|
-
'lines': [
|
188
|
-
{
|
189
|
-
'spans': [
|
190
|
-
{
|
191
|
-
'size': 9.962599754333496,
|
192
|
-
'type': TYPE_INTERLINE_EQUATION,
|
193
|
-
'flags': 4,
|
194
|
-
'font': TYPE_INTERLINE_EQUATION,
|
195
|
-
'color': 0,
|
196
|
-
'ascender': 0.9409999847412109,
|
197
|
-
'descender': -0.3050000071525574,
|
198
|
-
'latex': latex_content,
|
199
|
-
'origin': [bbox[0], bbox[1]],
|
200
|
-
'bbox': bbox,
|
201
|
-
}
|
202
|
-
],
|
203
|
-
'wmode': 0,
|
204
|
-
'dir': [1.0, 0.0],
|
205
|
-
'bbox': bbox,
|
206
|
-
}
|
207
|
-
],
|
208
|
-
}
|
209
|
-
pymu_block_list.append(text_block)
|
210
|
-
|
211
|
-
|
212
|
-
def x_overlap_ratio(box1, box2):
|
213
|
-
a, _, c, _ = box1
|
214
|
-
e, _, g, _ = box2
|
215
|
-
|
216
|
-
# 计算重叠宽度
|
217
|
-
overlap_x = max(min(c, g) - max(a, e), 0)
|
218
|
-
|
219
|
-
# 计算box1的宽度
|
220
|
-
width1 = g - e
|
221
|
-
|
222
|
-
# 计算重叠比例
|
223
|
-
overlap_ratio = overlap_x / width1 if width1 != 0 else 0
|
224
|
-
|
225
|
-
return overlap_ratio
|
226
|
-
|
227
|
-
|
228
|
-
def __is_x_dir_overlap(bbox1, bbox2):
|
229
|
-
return not (bbox1[2] < bbox2[0] or bbox1[0] > bbox2[2])
|
230
|
-
|
231
|
-
|
232
|
-
def __y_overlap_ratio(box1, box2):
|
233
|
-
""""""
|
234
|
-
_, b, _, d = box1
|
235
|
-
_, f, _, h = box2
|
236
|
-
|
237
|
-
# 计算重叠高度
|
238
|
-
overlap_y = max(min(d, h) - max(b, f), 0)
|
239
|
-
|
240
|
-
# 计算box1的高度
|
241
|
-
height1 = d - b
|
242
|
-
|
243
|
-
# 计算重叠比例
|
244
|
-
overlap_ratio = overlap_y / height1 if height1 != 0 else 0
|
245
|
-
|
246
|
-
return overlap_ratio
|
247
|
-
|
248
|
-
|
249
|
-
def replace_line_v2(eqinfo, line):
|
250
|
-
"""扫描这一行所有的和公式框X方向重叠的char,然后计算char的左、右x0, x1,位于这个区间内的span删除掉。
|
251
|
-
最后与这个x0,x1有相交的span0, span1内部进行分割。"""
|
252
|
-
first_overlap_span = -1
|
253
|
-
first_overlap_span_idx = -1
|
254
|
-
last_overlap_span = -1
|
255
|
-
delete_chars = []
|
256
|
-
for i in range(0, len(line['spans'])):
|
257
|
-
if 'chars' not in line['spans'][i]:
|
258
|
-
continue
|
259
|
-
|
260
|
-
if line['spans'][i].get('_type', None) is not None:
|
261
|
-
continue # 忽略,因为已经是插入的伪造span公式了
|
262
|
-
|
263
|
-
for char in line['spans'][i]['chars']:
|
264
|
-
if __is_x_dir_overlap(eqinfo['bbox'], char['bbox']):
|
265
|
-
line_txt = ''
|
266
|
-
for span in line['spans']:
|
267
|
-
span_txt = '<span>'
|
268
|
-
for ch in span['chars']:
|
269
|
-
span_txt = span_txt + ch['c']
|
270
|
-
|
271
|
-
span_txt = span_txt + '</span>'
|
272
|
-
|
273
|
-
line_txt = line_txt + span_txt
|
274
|
-
|
275
|
-
if first_overlap_span_idx == -1:
|
276
|
-
first_overlap_span = line['spans'][i]
|
277
|
-
first_overlap_span_idx = i
|
278
|
-
last_overlap_span = line['spans'][i]
|
279
|
-
delete_chars.append(char)
|
280
|
-
|
281
|
-
# 第一个和最后一个char要进行检查,到底属于公式多还是属于正常span多
|
282
|
-
if len(delete_chars) > 0:
|
283
|
-
ch0_bbox = delete_chars[0]['bbox']
|
284
|
-
if x_overlap_ratio(eqinfo['bbox'], ch0_bbox) < 0.51:
|
285
|
-
delete_chars.remove(delete_chars[0])
|
286
|
-
if len(delete_chars) > 0:
|
287
|
-
ch0_bbox = delete_chars[-1]['bbox']
|
288
|
-
if x_overlap_ratio(eqinfo['bbox'], ch0_bbox) < 0.51:
|
289
|
-
delete_chars.remove(delete_chars[-1])
|
290
|
-
|
291
|
-
# 计算x方向上被删除区间内的char的真实x0, x1
|
292
|
-
if len(delete_chars):
|
293
|
-
x0, x1 = (
|
294
|
-
min([b['bbox'][0] for b in delete_chars]),
|
295
|
-
max([b['bbox'][2] for b in delete_chars]),
|
296
|
-
)
|
297
|
-
else:
|
298
|
-
# logger.debug(f"行内公式替换没有发生,尝试下一行匹配, eqinfo={eqinfo}")
|
299
|
-
return False
|
300
|
-
|
301
|
-
# 删除位于x0, x1这两个中间的span
|
302
|
-
delete_span = []
|
303
|
-
for span in line['spans']:
|
304
|
-
span_box = span['bbox']
|
305
|
-
if x0 <= span_box[0] and span_box[2] <= x1:
|
306
|
-
delete_span.append(span)
|
307
|
-
for span in delete_span:
|
308
|
-
line['spans'].remove(span)
|
309
|
-
|
310
|
-
equation_span = {
|
311
|
-
'size': 9.962599754333496,
|
312
|
-
'type': TYPE_INLINE_EQUATION,
|
313
|
-
'flags': 4,
|
314
|
-
'font': TYPE_INLINE_EQUATION,
|
315
|
-
'color': 0,
|
316
|
-
'ascender': 0.9409999847412109,
|
317
|
-
'descender': -0.3050000071525574,
|
318
|
-
'latex': '',
|
319
|
-
'origin': [337.1410153102337, 216.0205245153934],
|
320
|
-
'bbox': eqinfo['bbox'],
|
321
|
-
}
|
322
|
-
# equation_span = line['spans'][0].copy()
|
323
|
-
equation_span['latex'] = eqinfo['latex']
|
324
|
-
equation_span['bbox'] = [x0, equation_span['bbox'][1], x1, equation_span['bbox'][3]]
|
325
|
-
equation_span['origin'] = [equation_span['bbox'][0], equation_span['bbox'][1]]
|
326
|
-
equation_span['chars'] = delete_chars
|
327
|
-
equation_span['type'] = TYPE_INLINE_EQUATION
|
328
|
-
equation_span['_eq_bbox'] = eqinfo['bbox']
|
329
|
-
line['spans'].insert(first_overlap_span_idx + 1, equation_span) # 放入公式
|
330
|
-
|
331
|
-
# logger.info(f"==>text is 【{line_txt}】, equation is 【{eqinfo['latex_text']}】")
|
332
|
-
|
333
|
-
# 第一个、和最后一个有overlap的span进行分割,然后插入对应的位置
|
334
|
-
first_span_chars = [
|
335
|
-
char
|
336
|
-
for char in first_overlap_span['chars']
|
337
|
-
if (char['bbox'][2] + char['bbox'][0]) / 2 < x0
|
338
|
-
]
|
339
|
-
tail_span_chars = [
|
340
|
-
char
|
341
|
-
for char in last_overlap_span['chars']
|
342
|
-
if (char['bbox'][0] + char['bbox'][2]) / 2 > x1
|
343
|
-
]
|
344
|
-
|
345
|
-
if len(first_span_chars) > 0:
|
346
|
-
first_overlap_span['chars'] = first_span_chars
|
347
|
-
first_overlap_span['text'] = ''.join([char['c'] for char in first_span_chars])
|
348
|
-
first_overlap_span['bbox'] = (
|
349
|
-
first_overlap_span['bbox'][0],
|
350
|
-
first_overlap_span['bbox'][1],
|
351
|
-
max([chr['bbox'][2] for chr in first_span_chars]),
|
352
|
-
first_overlap_span['bbox'][3],
|
353
|
-
)
|
354
|
-
# first_overlap_span['_type'] = "first"
|
355
|
-
else:
|
356
|
-
# 删掉
|
357
|
-
if first_overlap_span not in delete_span:
|
358
|
-
line['spans'].remove(first_overlap_span)
|
359
|
-
|
360
|
-
if len(tail_span_chars) > 0:
|
361
|
-
min_of_tail_span_x0 = min([chr['bbox'][0] for chr in tail_span_chars])
|
362
|
-
min_of_tail_span_y0 = min([chr['bbox'][1] for chr in tail_span_chars])
|
363
|
-
max_of_tail_span_x1 = max([chr['bbox'][2] for chr in tail_span_chars])
|
364
|
-
max_of_tail_span_y1 = max([chr['bbox'][3] for chr in tail_span_chars])
|
365
|
-
|
366
|
-
if last_overlap_span == first_overlap_span: # 这个时候应该插入一个新的
|
367
|
-
tail_span_txt = ''.join([char['c'] for char in tail_span_chars]) # noqa: F841
|
368
|
-
last_span_to_insert = last_overlap_span.copy()
|
369
|
-
last_span_to_insert['chars'] = tail_span_chars
|
370
|
-
last_span_to_insert['text'] = ''.join(
|
371
|
-
[char['c'] for char in tail_span_chars]
|
372
|
-
)
|
373
|
-
if equation_span['bbox'][2] >= last_overlap_span['bbox'][2]:
|
374
|
-
last_span_to_insert['bbox'] = (
|
375
|
-
min_of_tail_span_x0,
|
376
|
-
min_of_tail_span_y0,
|
377
|
-
max_of_tail_span_x1,
|
378
|
-
max_of_tail_span_y1,
|
379
|
-
)
|
380
|
-
else:
|
381
|
-
last_span_to_insert['bbox'] = (
|
382
|
-
min([chr['bbox'][0] for chr in tail_span_chars]),
|
383
|
-
last_overlap_span['bbox'][1],
|
384
|
-
last_overlap_span['bbox'][2],
|
385
|
-
last_overlap_span['bbox'][3],
|
386
|
-
)
|
387
|
-
# 插入到公式对象之后
|
388
|
-
equation_idx = line['spans'].index(equation_span)
|
389
|
-
line['spans'].insert(equation_idx + 1, last_span_to_insert) # 放入公式
|
390
|
-
else: # 直接修改原来的span
|
391
|
-
last_overlap_span['chars'] = tail_span_chars
|
392
|
-
last_overlap_span['text'] = ''.join([char['c'] for char in tail_span_chars])
|
393
|
-
last_overlap_span['bbox'] = (
|
394
|
-
min([chr['bbox'][0] for chr in tail_span_chars]),
|
395
|
-
last_overlap_span['bbox'][1],
|
396
|
-
last_overlap_span['bbox'][2],
|
397
|
-
last_overlap_span['bbox'][3],
|
398
|
-
)
|
399
|
-
else:
|
400
|
-
# 删掉
|
401
|
-
if (
|
402
|
-
last_overlap_span not in delete_span
|
403
|
-
and last_overlap_span != first_overlap_span
|
404
|
-
):
|
405
|
-
line['spans'].remove(last_overlap_span)
|
406
|
-
|
407
|
-
remain_txt = ''
|
408
|
-
for span in line['spans']:
|
409
|
-
span_txt = '<span>'
|
410
|
-
for char in span['chars']:
|
411
|
-
span_txt = span_txt + char['c']
|
412
|
-
|
413
|
-
span_txt = span_txt + '</span>'
|
414
|
-
|
415
|
-
remain_txt = remain_txt + span_txt
|
416
|
-
|
417
|
-
# logger.info(f"<== succ replace, text is 【{remain_txt}】, equation is 【{eqinfo['latex_text']}】")
|
418
|
-
|
419
|
-
return True
|
420
|
-
|
421
|
-
|
422
|
-
def replace_eq_blk(eqinfo, text_block):
|
423
|
-
"""替换行内公式."""
|
424
|
-
for line in text_block['lines']:
|
425
|
-
line_bbox = line['bbox']
|
426
|
-
if (
|
427
|
-
_is_xin(eqinfo['bbox'], line_bbox)
|
428
|
-
or __y_overlap_ratio(eqinfo['bbox'], line_bbox) > 0.6
|
429
|
-
): # 定位到行, 使用y方向重合率是因为有的时候,一个行的宽度会小于公式位置宽度:行很高,公式很窄,
|
430
|
-
replace_succ = replace_line_v2(eqinfo, line)
|
431
|
-
if not replace_succ: # 有的时候,一个pdf的line高度从API里会计算的有问题,因此在行内span级别会替换不成功,这就需要继续重试下一行
|
432
|
-
continue
|
433
|
-
else:
|
434
|
-
break
|
435
|
-
else:
|
436
|
-
return False
|
437
|
-
return True
|
438
|
-
|
439
|
-
|
440
|
-
def replace_inline_equations(inline_equation_bboxes, raw_text_blocks):
|
441
|
-
"""替换行内公式."""
|
442
|
-
for eqinfo in inline_equation_bboxes:
|
443
|
-
eqbox = eqinfo['bbox']
|
444
|
-
for blk in raw_text_blocks:
|
445
|
-
if _is_xin(eqbox, blk['bbox']):
|
446
|
-
if not replace_eq_blk(eqinfo, blk):
|
447
|
-
logger.warning(f'行内公式没有替换成功:{eqinfo} ')
|
448
|
-
else:
|
449
|
-
break
|
450
|
-
|
451
|
-
return raw_text_blocks
|
452
|
-
|
453
|
-
|
454
|
-
def remove_chars_in_text_blocks(text_blocks):
|
455
|
-
"""删除text_blocks里的char."""
|
456
|
-
for blk in text_blocks:
|
457
|
-
for line in blk['lines']:
|
458
|
-
for span in line['spans']:
|
459
|
-
_ = span.pop('chars', 'no such key')
|
460
|
-
return text_blocks
|
461
|
-
|
462
|
-
|
463
|
-
def replace_equations_in_textblock(
|
464
|
-
raw_text_blocks, inline_equation_bboxes, interline_equation_bboxes
|
465
|
-
):
|
466
|
-
"""替换行间和和行内公式为latex."""
|
467
|
-
raw_text_blocks = remove_text_block_in_interline_equation_bbox(
|
468
|
-
interline_equation_bboxes, raw_text_blocks
|
469
|
-
) # 消除重叠:第一步,在公式内部的
|
470
|
-
|
471
|
-
raw_text_blocks = remove_text_block_overlap_interline_equation_bbox(
|
472
|
-
interline_equation_bboxes, raw_text_blocks
|
473
|
-
) # 消重,第二步,和公式覆盖的
|
474
|
-
|
475
|
-
insert_interline_equations_textblock(interline_equation_bboxes, raw_text_blocks)
|
476
|
-
raw_text_blocks = replace_inline_equations(inline_equation_bboxes, raw_text_blocks)
|
477
|
-
return raw_text_blocks
|
478
|
-
|
479
|
-
|
480
|
-
def draw_block_on_pdf_with_txt_replace_eq_bbox(json_path, pdf_path):
|
481
|
-
""""""
|
482
|
-
new_pdf = f'{Path(pdf_path).parent}/{Path(pdf_path).stem}.step3-消除行内公式text_block.pdf'
|
483
|
-
with open(json_path, 'r', encoding='utf-8') as f:
|
484
|
-
obj = json.loads(f.read())
|
485
|
-
|
486
|
-
if os.path.exists(new_pdf):
|
487
|
-
os.remove(new_pdf)
|
488
|
-
new_doc = fitz.open('')
|
489
|
-
|
490
|
-
doc = fitz.open(pdf_path) # noqa: F841
|
491
|
-
new_doc = fitz.open(pdf_path)
|
492
|
-
for i in range(len(new_doc)):
|
493
|
-
page = new_doc[i]
|
494
|
-
inline_equation_bboxes = obj[f'page_{i}']['inline_equations']
|
495
|
-
interline_equation_bboxes = obj[f'page_{i}']['interline_equations']
|
496
|
-
raw_text_blocks = obj[f'page_{i}']['preproc_blocks']
|
497
|
-
raw_text_blocks = remove_text_block_in_interline_equation_bbox(
|
498
|
-
interline_equation_bboxes, raw_text_blocks
|
499
|
-
) # 消除重叠:第一步,在公式内部的
|
500
|
-
raw_text_blocks = remove_text_block_overlap_interline_equation_bbox(
|
501
|
-
interline_equation_bboxes, raw_text_blocks
|
502
|
-
) # 消重,第二步,和公式覆盖的
|
503
|
-
insert_interline_equations_textblock(interline_equation_bboxes, raw_text_blocks)
|
504
|
-
raw_text_blocks = replace_inline_equations(
|
505
|
-
inline_equation_bboxes, raw_text_blocks
|
506
|
-
)
|
507
|
-
|
508
|
-
# 为了检验公式是否重复,把每一行里,含有公式的span背景改成黄色的
|
509
|
-
color_map = [fitz.pdfcolor['blue'], fitz.pdfcolor['green']] # noqa: F841
|
510
|
-
j = 0 # noqa: F841
|
511
|
-
for blk in raw_text_blocks:
|
512
|
-
for i, line in enumerate(blk['lines']):
|
513
|
-
# line_box = line['bbox']
|
514
|
-
# shape = page.new_shape()
|
515
|
-
# shape.draw_rect(line_box)
|
516
|
-
# shape.finish(color=fitz.pdfcolor['red'], fill=color_map[j%2], fill_opacity=0.3)
|
517
|
-
# shape.commit()
|
518
|
-
# j = j+1
|
519
|
-
|
520
|
-
for i, span in enumerate(line['spans']):
|
521
|
-
shape_page = page.new_shape()
|
522
|
-
span_type = span.get('_type')
|
523
|
-
color = fitz.pdfcolor['blue']
|
524
|
-
if span_type == 'first':
|
525
|
-
color = fitz.pdfcolor['blue']
|
526
|
-
elif span_type == 'tail':
|
527
|
-
color = fitz.pdfcolor['green']
|
528
|
-
elif span_type == TYPE_INLINE_EQUATION:
|
529
|
-
color = fitz.pdfcolor['black']
|
530
|
-
else:
|
531
|
-
color = None
|
532
|
-
|
533
|
-
b = span['bbox']
|
534
|
-
shape_page.draw_rect(b)
|
535
|
-
|
536
|
-
shape_page.finish(color=None, fill=color, fill_opacity=0.3)
|
537
|
-
shape_page.commit()
|
538
|
-
|
539
|
-
new_doc.save(new_pdf)
|
540
|
-
logger.info(f'save ok {new_pdf}')
|
541
|
-
final_json = json.dumps(obj, ensure_ascii=False, indent=2)
|
542
|
-
with open('equations_test/final_json.json', 'w') as f:
|
543
|
-
f.write(final_json)
|
544
|
-
|
545
|
-
return new_pdf
|
546
|
-
|
547
|
-
|
548
|
-
if __name__ == '__main__':
|
549
|
-
# draw_block_on_pdf_with_txt_replace_eq_bbox(new_json_path, equation_color_pdf)
|
550
|
-
pass
|