magic-pdf 0.5.8__py3-none-any.whl → 0.5.10__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/cli/magicpdf.py +9 -10
- magic_pdf/libs/version.py +1 -1
- magic_pdf/para/para_split_v2.py +43 -28
- magic_pdf/pdf_parse_by_ocr.py +18 -219
- magic_pdf/pdf_parse_by_txt.py +10 -401
- magic_pdf/pre_proc/equations_replace.py +1 -1
- magic_pdf/user_api.py +3 -41
- magic_pdf-0.5.10.dist-info/METADATA +133 -0
- {magic_pdf-0.5.8.dist-info → magic_pdf-0.5.10.dist-info}/RECORD +13 -14
- magic_pdf-0.5.10.dist-info/entry_points.txt +2 -0
- magic_pdf/pdf_parse_by_ocr_v2.py +0 -17
- magic_pdf/pdf_parse_by_txt_v2.py +0 -56
- magic_pdf-0.5.8.dist-info/METADATA +0 -28
- {magic_pdf-0.5.8.dist-info → magic_pdf-0.5.10.dist-info}/LICENSE.md +0 -0
- {magic_pdf-0.5.8.dist-info → magic_pdf-0.5.10.dist-info}/WHEEL +0 -0
- {magic_pdf-0.5.8.dist-info → magic_pdf-0.5.10.dist-info}/top_level.txt +0 -0
magic_pdf/pdf_parse_by_txt.py
CHANGED
@@ -1,410 +1,19 @@
|
|
1
|
-
import
|
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
|
-
|
1
|
+
from magic_pdf.pdf_parse_union_core import pdf_parse_union
|
72
2
|
|
73
3
|
|
74
4
|
def parse_pdf_by_txt(
|
75
5
|
pdf_bytes,
|
76
|
-
|
6
|
+
model_list,
|
77
7
|
imageWriter,
|
78
8
|
start_page_id=0,
|
79
9
|
end_page_id=None,
|
80
10
|
debug_mode=False,
|
81
11
|
):
|
82
|
-
|
83
|
-
|
84
|
-
|
85
|
-
|
86
|
-
|
87
|
-
|
88
|
-
|
89
|
-
|
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
|
12
|
+
return pdf_parse_union(pdf_bytes,
|
13
|
+
model_list,
|
14
|
+
imageWriter,
|
15
|
+
"txt",
|
16
|
+
start_page_id=start_page_id,
|
17
|
+
end_page_id=end_page_id,
|
18
|
+
debug_mode=debug_mode,
|
19
|
+
)
|
@@ -299,7 +299,7 @@ def replace_line_v2(eqinfo, line):
|
|
299
299
|
[b["bbox"][2] for b in delete_chars]
|
300
300
|
)
|
301
301
|
else:
|
302
|
-
logger.debug(f"行内公式替换没有发生,尝试下一行匹配, eqinfo={eqinfo}")
|
302
|
+
# logger.debug(f"行内公式替换没有发生,尝试下一行匹配, eqinfo={eqinfo}")
|
303
303
|
return False
|
304
304
|
|
305
305
|
# 删除位于x0, x1这两个中间的span
|
magic_pdf/user_api.py
CHANGED
@@ -18,8 +18,8 @@ from loguru import logger
|
|
18
18
|
from magic_pdf.libs.version import __version__
|
19
19
|
from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
|
20
20
|
from magic_pdf.rw import AbsReaderWriter
|
21
|
-
from magic_pdf.
|
22
|
-
from magic_pdf.
|
21
|
+
from magic_pdf.pdf_parse_by_ocr import parse_pdf_by_ocr
|
22
|
+
from magic_pdf.pdf_parse_by_txt import parse_pdf_by_txt
|
23
23
|
|
24
24
|
PARSE_TYPE_TXT = "txt"
|
25
25
|
PARSE_TYPE_OCR = "ocr"
|
@@ -86,45 +86,7 @@ def parse_union_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWr
|
|
86
86
|
return None
|
87
87
|
|
88
88
|
pdf_info_dict = parse_pdf(parse_pdf_by_txt)
|
89
|
-
|
90
|
-
# for page_dict in pdf_info_dict['pdf_info']:
|
91
|
-
# for para_block in page_dict['para_blocks']:
|
92
|
-
# if para_block['type'] in ['title', 'text']:
|
93
|
-
# for line in para_block['lines']:
|
94
|
-
# for span in line['spans']:
|
95
|
-
# text_all += span['content']
|
96
|
-
|
97
|
-
# def calculate_not_common_character_rate(text):
|
98
|
-
# garbage_regex = re.compile(r'[^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a\u3000-\u303f\uff00-\uffef]')
|
99
|
-
# # 计算乱码字符的数量
|
100
|
-
# garbage_count = len(garbage_regex.findall(text))
|
101
|
-
# total = len(text)
|
102
|
-
# if total == 0:
|
103
|
-
# return 0 # 避免除以零的错误
|
104
|
-
# return garbage_count / total
|
105
|
-
#
|
106
|
-
# def calculate_not_printable_rate(text):
|
107
|
-
# printable_text = ""
|
108
|
-
# for c in text:
|
109
|
-
# if c.isprintable():
|
110
|
-
# printable_text += c
|
111
|
-
# printable_total = len(printable_text)
|
112
|
-
# total = len(text)
|
113
|
-
# if total == 0:
|
114
|
-
# return 0 # 避免除以零的错误
|
115
|
-
# return (total - printable_total) / total
|
116
|
-
#
|
117
|
-
# not_common_character_rate = calculate_not_common_character_rate(text_all)
|
118
|
-
# not_printable_rate = calculate_not_printable_rate(text_all)
|
119
|
-
# pdf_info_dict["_not_common_character_rate"] = not_common_character_rate
|
120
|
-
# pdf_info_dict["_not_printable_rate"] = not_printable_rate
|
121
|
-
# logger.info(f"not_common_character_rate: {not_common_character_rate}, not_printable_rate: {not_printable_rate}")
|
122
|
-
'''新逻辑使用pdfminer识别乱码pdf,准确率高且不会误伤,已在解析流程之前进行处理'''
|
123
|
-
# not_common_character_rate对小语种可能会有误伤,not_printable_rate对小语种较为友好
|
124
|
-
if (pdf_info_dict is None
|
125
|
-
or pdf_info_dict.get("_need_drop", False)
|
126
|
-
# or not_printable_rate > 0.02 # 参考一些正常的pdf,这个值没有超过0.01的,阈值设为0.02
|
127
|
-
):
|
89
|
+
if pdf_info_dict is None or pdf_info_dict.get("_need_drop", False):
|
128
90
|
logger.warning(f"parse_pdf_by_txt drop or error, switch to parse_pdf_by_ocr")
|
129
91
|
if input_model_is_empty:
|
130
92
|
pdf_models = doc_analyze(pdf_bytes, ocr=True)
|
@@ -0,0 +1,133 @@
|
|
1
|
+
Metadata-Version: 2.1
|
2
|
+
Name: magic-pdf
|
3
|
+
Version: 0.5.10
|
4
|
+
Summary: A practical tool for converting PDF to Markdown
|
5
|
+
Home-page: https://github.com/magicpdf/Magic-PDF
|
6
|
+
Requires-Python: >=3.9
|
7
|
+
Description-Content-Type: text/markdown
|
8
|
+
License-File: LICENSE.md
|
9
|
+
Requires-Dist: boto3 >=1.28.43
|
10
|
+
Requires-Dist: Brotli >=1.1.0
|
11
|
+
Requires-Dist: click >=8.1.7
|
12
|
+
Requires-Dist: Distance >=0.1.3
|
13
|
+
Requires-Dist: PyMuPDF >=1.24.5
|
14
|
+
Requires-Dist: loguru >=0.6.0
|
15
|
+
Requires-Dist: matplotlib >=3.8.3
|
16
|
+
Requires-Dist: numpy >=1.21.6
|
17
|
+
Requires-Dist: pandas >=1.3.5
|
18
|
+
Requires-Dist: fast-langdetect >=0.1.1
|
19
|
+
Requires-Dist: regex >=2023.12.25
|
20
|
+
Requires-Dist: termcolor >=2.4.0
|
21
|
+
Requires-Dist: wordninja >=2.0.0
|
22
|
+
Requires-Dist: scikit-learn >=1.0.2
|
23
|
+
Requires-Dist: nltk ==3.8.1
|
24
|
+
Requires-Dist: s3pathlib >=2.1.1
|
25
|
+
Requires-Dist: paddleocr
|
26
|
+
Requires-Dist: pdfminer.six >=20231228
|
27
|
+
Provides-Extra: cpu
|
28
|
+
Requires-Dist: paddlepaddle ; extra == 'cpu'
|
29
|
+
Provides-Extra: gpu
|
30
|
+
Requires-Dist: paddlepaddle-gpu ; extra == 'gpu'
|
31
|
+
|
32
|
+
<div id="top"></div>
|
33
|
+
<div align="center">
|
34
|
+
|
35
|
+
[](https://github.com/magicpdf/Magic-PDF)
|
36
|
+
[](https://github.com/magicpdf/Magic-PDF)
|
37
|
+
[](https://github.com/magicpdf/Magic-PDF/tree/main/LICENSE)
|
38
|
+
[](https://github.com/magicpdf/Magic-PDF/issues)
|
39
|
+
[](https://github.com/magicpdf/Magic-PDF/issues)
|
40
|
+
|
41
|
+
[English](README.md) | [简体中文](README_zh-CN.md)
|
42
|
+
|
43
|
+
</div>
|
44
|
+
|
45
|
+
<div align="center">
|
46
|
+
|
47
|
+
</div>
|
48
|
+
|
49
|
+
# Magic-PDF
|
50
|
+
|
51
|
+
## Introduction
|
52
|
+
|
53
|
+
Magic-PDF is a tool designed to convert PDF documents into Markdown format, capable of processing files stored locally or on object storage supporting S3 protocol.
|
54
|
+
|
55
|
+
Key features include:
|
56
|
+
|
57
|
+
- Support for multiple front-end model inputs
|
58
|
+
- Removal of headers, footers, footnotes, and page numbers
|
59
|
+
- Human-readable layout formatting
|
60
|
+
- Retains the original document's structure and formatting, including headings, paragraphs, lists, and more
|
61
|
+
- Extraction and display of images and tables within markdown
|
62
|
+
- Conversion of equations into LaTeX format
|
63
|
+
- Automatic detection and conversion of garbled PDFs
|
64
|
+
- Compatibility with CPU and GPU environments
|
65
|
+
- Available for Windows, Linux, and macOS platforms
|
66
|
+
|
67
|
+
## Getting Started
|
68
|
+
|
69
|
+
### Requirements
|
70
|
+
|
71
|
+
- Python 3.9 or newer
|
72
|
+
|
73
|
+
### Usage Instructions
|
74
|
+
|
75
|
+
#### 1. Install Magic-PDF
|
76
|
+
```bash
|
77
|
+
pip install magic-pdf
|
78
|
+
```
|
79
|
+
|
80
|
+
#### 2. Usage via Command Line
|
81
|
+
|
82
|
+
###### simple
|
83
|
+
```bash
|
84
|
+
cp magic-pdf.template.json to ~/magic-pdf.json
|
85
|
+
magic-pdf pdf-command --pdf "pdf_path" --model "model_json_path"
|
86
|
+
```
|
87
|
+
###### more
|
88
|
+
```bash
|
89
|
+
magic-pdf --help
|
90
|
+
```
|
91
|
+
|
92
|
+
#### 3. Usage via Api
|
93
|
+
|
94
|
+
###### Local
|
95
|
+
```python
|
96
|
+
image_writer = DiskReaderWriter(local_image_dir)
|
97
|
+
image_dir = str(os.path.basename(local_image_dir))
|
98
|
+
jso_useful_key = {"_pdf_type": "", "model_list": model_json}
|
99
|
+
pipe = UNIPipe(pdf_bytes, jso_useful_key, image_writer)
|
100
|
+
pipe.pipe_classify()
|
101
|
+
pipe.pipe_parse()
|
102
|
+
md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")
|
103
|
+
```
|
104
|
+
|
105
|
+
###### Object Storage
|
106
|
+
```python
|
107
|
+
s3pdf_cli = S3ReaderWriter(pdf_ak, pdf_sk, pdf_endpoint)
|
108
|
+
image_dir = "s3://img_bucket/"
|
109
|
+
s3image_cli = S3ReaderWriter(img_ak, img_sk, img_endpoint, parent_path=image_dir)
|
110
|
+
pdf_bytes = s3pdf_cli.read(s3_pdf_path, mode=s3pdf_cli.MODE_BIN)
|
111
|
+
jso_useful_key = {"_pdf_type": "", "model_list": model_json}
|
112
|
+
pipe = UNIPipe(pdf_bytes, jso_useful_key, s3image_cli)
|
113
|
+
pipe.pipe_classify()
|
114
|
+
pipe.pipe_parse()
|
115
|
+
md_content = pipe.pipe_mk_markdown(image_dir, drop_mode="none")
|
116
|
+
```
|
117
|
+
|
118
|
+
Demo can be referred to [demo.py](https://github.com/magicpdf/Magic-PDF/blob/master/demo/demo.py)
|
119
|
+
|
120
|
+
## All Thanks To Our Contributors
|
121
|
+
|
122
|
+
<a href="https://github.com/magicpdf/Magic-PDF/graphs/contributors">
|
123
|
+
<img src="https://contrib.rocks/image?repo=magicpdf/Magic-PDF" />
|
124
|
+
</a>
|
125
|
+
|
126
|
+
## License Information
|
127
|
+
|
128
|
+
See [LICENSE.md](https://github.com/magicpdf/Magic-PDF/blob/master/LICENSE.md) for details.
|
129
|
+
|
130
|
+
## Acknowledgments
|
131
|
+
|
132
|
+
- [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR)
|
133
|
+
- [PyMuPDF](https://github.com/pymupdf/PyMuPDF)
|