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