magic-pdf 0.8.1__py3-none-any.whl → 0.9.0__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 (57) hide show
  1. magic_pdf/config/__init__.py +0 -0
  2. magic_pdf/config/enums.py +7 -0
  3. magic_pdf/config/exceptions.py +32 -0
  4. magic_pdf/data/__init__.py +0 -0
  5. magic_pdf/data/data_reader_writer/__init__.py +12 -0
  6. magic_pdf/data/data_reader_writer/base.py +51 -0
  7. magic_pdf/data/data_reader_writer/filebase.py +59 -0
  8. magic_pdf/data/data_reader_writer/multi_bucket_s3.py +137 -0
  9. magic_pdf/data/data_reader_writer/s3.py +69 -0
  10. magic_pdf/data/dataset.py +194 -0
  11. magic_pdf/data/io/__init__.py +0 -0
  12. magic_pdf/data/io/base.py +42 -0
  13. magic_pdf/data/io/http.py +37 -0
  14. magic_pdf/data/io/s3.py +114 -0
  15. magic_pdf/data/read_api.py +95 -0
  16. magic_pdf/data/schemas.py +15 -0
  17. magic_pdf/data/utils.py +32 -0
  18. magic_pdf/dict2md/ocr_mkcontent.py +74 -234
  19. magic_pdf/libs/Constants.py +21 -8
  20. magic_pdf/libs/MakeContentConfig.py +1 -0
  21. magic_pdf/libs/boxbase.py +35 -0
  22. magic_pdf/libs/clean_memory.py +10 -0
  23. magic_pdf/libs/config_reader.py +53 -23
  24. magic_pdf/libs/draw_bbox.py +150 -65
  25. magic_pdf/libs/ocr_content_type.py +2 -0
  26. magic_pdf/libs/version.py +1 -1
  27. magic_pdf/model/doc_analyze_by_custom_model.py +77 -32
  28. magic_pdf/model/magic_model.py +331 -15
  29. magic_pdf/model/pdf_extract_kit.py +164 -80
  30. magic_pdf/model/pek_sub_modules/structeqtable/StructTableModel.py +8 -1
  31. magic_pdf/model/ppTableModel.py +2 -2
  32. magic_pdf/model/pp_structure_v2.py +5 -2
  33. magic_pdf/model/v3/__init__.py +0 -0
  34. magic_pdf/model/v3/helpers.py +125 -0
  35. magic_pdf/para/para_split_v3.py +296 -0
  36. magic_pdf/pdf_parse_by_ocr.py +6 -3
  37. magic_pdf/pdf_parse_by_txt.py +6 -3
  38. magic_pdf/pdf_parse_union_core_v2.py +644 -0
  39. magic_pdf/pipe/AbsPipe.py +5 -1
  40. magic_pdf/pipe/OCRPipe.py +10 -4
  41. magic_pdf/pipe/TXTPipe.py +10 -4
  42. magic_pdf/pipe/UNIPipe.py +16 -7
  43. magic_pdf/pre_proc/ocr_detect_all_bboxes.py +83 -1
  44. magic_pdf/pre_proc/ocr_dict_merge.py +27 -2
  45. magic_pdf/resources/model_config/UniMERNet/demo.yaml +7 -7
  46. magic_pdf/resources/model_config/model_configs.yaml +5 -13
  47. magic_pdf/tools/cli.py +14 -1
  48. magic_pdf/tools/common.py +18 -8
  49. magic_pdf/user_api.py +25 -6
  50. magic_pdf/utils/__init__.py +0 -0
  51. magic_pdf/utils/annotations.py +11 -0
  52. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.0.dist-info}/LICENSE.md +1 -0
  53. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.0.dist-info}/METADATA +120 -75
  54. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.0.dist-info}/RECORD +57 -33
  55. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.0.dist-info}/WHEEL +0 -0
  56. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.0.dist-info}/entry_points.txt +0 -0
  57. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,296 @@
1
+ import copy
2
+
3
+ from loguru import logger
4
+
5
+ from magic_pdf.libs.Constants import LINES_DELETED, CROSS_PAGE
6
+ from magic_pdf.libs.ocr_content_type import BlockType, ContentType
7
+
8
+ LINE_STOP_FLAG = ('.', '!', '?', '。', '!', '?', ')', ')', '"', '”', ':', ':', ';', ';')
9
+ LIST_END_FLAG = ('.', '。', ';', ';')
10
+
11
+
12
+ class ListLineTag:
13
+ IS_LIST_START_LINE = "is_list_start_line"
14
+ IS_LIST_END_LINE = "is_list_end_line"
15
+
16
+
17
+ def __process_blocks(blocks):
18
+ # 对所有block预处理
19
+ # 1.通过title和interline_equation将block分组
20
+ # 2.bbox边界根据line信息重置
21
+
22
+ result = []
23
+ current_group = []
24
+
25
+ for i in range(len(blocks)):
26
+ current_block = blocks[i]
27
+
28
+ # 如果当前块是 text 类型
29
+ if current_block['type'] == 'text':
30
+ current_block["bbox_fs"] = copy.deepcopy(current_block["bbox"])
31
+ if 'lines' in current_block and len(current_block["lines"]) > 0:
32
+ current_block['bbox_fs'] = [min([line['bbox'][0] for line in current_block['lines']]),
33
+ min([line['bbox'][1] for line in current_block['lines']]),
34
+ max([line['bbox'][2] for line in current_block['lines']]),
35
+ max([line['bbox'][3] for line in current_block['lines']])]
36
+ current_group.append(current_block)
37
+
38
+ # 检查下一个块是否存在
39
+ if i + 1 < len(blocks):
40
+ next_block = blocks[i + 1]
41
+ # 如果下一个块不是 text 类型且是 title 或 interline_equation 类型
42
+ if next_block['type'] in ['title', 'interline_equation']:
43
+ result.append(current_group)
44
+ current_group = []
45
+
46
+ # 处理最后一个 group
47
+ if current_group:
48
+ result.append(current_group)
49
+
50
+ return result
51
+
52
+
53
+ def __is_list_or_index_block(block):
54
+ # 一个block如果是list block 应该同时满足以下特征
55
+ # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.block内有多个line 右侧不顶格(狗牙状)
56
+ # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.多个line以endflag结尾
57
+ # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.block内有多个line 左侧不顶格
58
+
59
+ # index block 是一种特殊的list block
60
+ # 一个block如果是index block 应该同时满足以下特征
61
+ # 1.block内有多个line 2.block 内有多个line两侧均顶格写 3.line的开头或者结尾均为数字
62
+ if len(block['lines']) >= 2:
63
+ first_line = block['lines'][0]
64
+ line_height = first_line['bbox'][3] - first_line['bbox'][1]
65
+ block_weight = block['bbox_fs'][2] - block['bbox_fs'][0]
66
+
67
+ left_close_num = 0
68
+ left_not_close_num = 0
69
+ right_not_close_num = 0
70
+ right_close_num = 0
71
+ lines_text_list = []
72
+
73
+ multiple_para_flag = False
74
+ last_line = block['lines'][-1]
75
+ # 如果首行左边不顶格而右边顶格,末行左边顶格而右边不顶格 (第一行可能可以右边不顶格)
76
+ if (first_line['bbox'][0] - block['bbox_fs'][0] > line_height / 2 and
77
+ # block['bbox_fs'][2] - first_line['bbox'][2] < line_height and
78
+ abs(last_line['bbox'][0] - block['bbox_fs'][0]) < line_height / 2 and
79
+ block['bbox_fs'][2] - last_line['bbox'][2] > line_height
80
+ ):
81
+ multiple_para_flag = True
82
+
83
+ for line in block['lines']:
84
+
85
+ line_text = ""
86
+
87
+ for span in line['spans']:
88
+ span_type = span['type']
89
+ if span_type == ContentType.Text:
90
+ line_text += span['content'].strip()
91
+
92
+ lines_text_list.append(line_text)
93
+
94
+ # 计算line左侧顶格数量是否大于2,是否顶格用abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height/2 来判断
95
+ if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
96
+ left_close_num += 1
97
+ elif line['bbox'][0] - block['bbox_fs'][0] > line_height:
98
+ # logger.info(f"{line_text}, {block['bbox_fs']}, {line['bbox']}")
99
+ left_not_close_num += 1
100
+
101
+ # 计算右侧是否顶格
102
+ if abs(block['bbox_fs'][2] - line['bbox'][2]) < line_height:
103
+ right_close_num += 1
104
+ else:
105
+ # 右侧不顶格情况下是否有一段距离,拍脑袋用0.3block宽度做阈值
106
+ closed_area = 0.3 * block_weight
107
+ # closed_area = 5 * line_height
108
+ if block['bbox_fs'][2] - line['bbox'][2] > closed_area:
109
+ right_not_close_num += 1
110
+
111
+ # 判断lines_text_list中的元素是否有超过80%都以LIST_END_FLAG结尾
112
+ line_end_flag = False
113
+ # 判断lines_text_list中的元素是否有超过80%都以数字开头或都以数字结尾
114
+ line_num_flag = False
115
+ num_start_count = 0
116
+ num_end_count = 0
117
+ flag_end_count = 0
118
+ if len(lines_text_list) > 0:
119
+ for line_text in lines_text_list:
120
+ if len(line_text) > 0:
121
+ if line_text[-1] in LIST_END_FLAG:
122
+ flag_end_count += 1
123
+ if line_text[0].isdigit():
124
+ num_start_count += 1
125
+ if line_text[-1].isdigit():
126
+ num_end_count += 1
127
+
128
+ if flag_end_count / len(lines_text_list) >= 0.8:
129
+ line_end_flag = True
130
+
131
+ if num_start_count / len(lines_text_list) >= 0.8 or num_end_count / len(lines_text_list) >= 0.8:
132
+ line_num_flag = True
133
+
134
+ # 有的目录右侧不贴边, 目前认为左边或者右边有一边全贴边,且符合数字规则极为index
135
+ if ((left_close_num/len(block['lines']) >= 0.8 or right_close_num/len(block['lines']) >= 0.8)
136
+ and line_num_flag
137
+ ):
138
+ for line in block['lines']:
139
+ line[ListLineTag.IS_LIST_START_LINE] = True
140
+ return BlockType.Index
141
+
142
+ elif left_close_num >= 2 and (
143
+ right_not_close_num >= 2 or line_end_flag or left_not_close_num >= 2) and not multiple_para_flag:
144
+ # 处理一种特殊的没有缩进的list,所有行都贴左边,通过右边的空隙判断是否是item尾
145
+ if left_close_num / len(block['lines']) > 0.9:
146
+ # 这种是每个item只有一行,且左边都贴边的短item list
147
+ if flag_end_count == 0 and right_close_num / len(block['lines']) < 0.5:
148
+ for line in block['lines']:
149
+ if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
150
+ line[ListLineTag.IS_LIST_START_LINE] = True
151
+ # 这种是大部分line item 都有结束标识符的情况,按结束标识符区分不同item
152
+ elif line_end_flag:
153
+ for i, line in enumerate(block['lines']):
154
+ if lines_text_list[i][-1] in LIST_END_FLAG:
155
+ line[ListLineTag.IS_LIST_END_LINE] = True
156
+ if i + 1 < len(block['lines']):
157
+ block['lines'][i+1][ListLineTag.IS_LIST_START_LINE] = True
158
+ # line item基本没有结束标识符,而且也没有缩进,按右侧空隙判断哪些是item end
159
+ else:
160
+ line_start_flag = False
161
+ for i, line in enumerate(block['lines']):
162
+ if line_start_flag:
163
+ line[ListLineTag.IS_LIST_START_LINE] = True
164
+ line_start_flag = False
165
+ elif abs(block['bbox_fs'][2] - line['bbox'][2]) > line_height:
166
+ line[ListLineTag.IS_LIST_END_LINE] = True
167
+ line_start_flag = True
168
+ # 一种有缩进的特殊有序list,start line 左侧不贴边且以数字开头,end line 以 IS_LIST_END_LINE 结尾且数量和start line 一致
169
+ elif num_start_count >= 2 and num_start_count == flag_end_count: # 简单一点先不考虑左侧不贴边的情况
170
+ for i, line in enumerate(block['lines']):
171
+ if lines_text_list[i][0].isdigit():
172
+ line[ListLineTag.IS_LIST_START_LINE] = True
173
+ if lines_text_list[i][-1] in LIST_END_FLAG:
174
+ line[ListLineTag.IS_LIST_END_LINE] = True
175
+ else:
176
+ # 正常有缩进的list处理
177
+ for line in block['lines']:
178
+ if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
179
+ line[ListLineTag.IS_LIST_START_LINE] = True
180
+ if abs(block['bbox_fs'][2] - line['bbox'][2]) > line_height:
181
+ line[ListLineTag.IS_LIST_END_LINE] = True
182
+
183
+ return BlockType.List
184
+ else:
185
+ return BlockType.Text
186
+ else:
187
+ return BlockType.Text
188
+
189
+
190
+ def __merge_2_text_blocks(block1, block2):
191
+ if len(block1['lines']) > 0:
192
+ first_line = block1['lines'][0]
193
+ line_height = first_line['bbox'][3] - first_line['bbox'][1]
194
+ block1_weight = block1['bbox'][2] - block1['bbox'][0]
195
+ block2_weight = block2['bbox'][2] - block2['bbox'][0]
196
+ min_block_weight = min(block1_weight, block2_weight)
197
+ if abs(block1['bbox_fs'][0] - first_line['bbox'][0]) < line_height / 2:
198
+ last_line = block2['lines'][-1]
199
+ if len(last_line['spans']) > 0:
200
+ last_span = last_line['spans'][-1]
201
+ line_height = last_line['bbox'][3] - last_line['bbox'][1]
202
+ if (abs(block2['bbox_fs'][2] - last_line['bbox'][2]) < line_height and
203
+ not last_span['content'].endswith(LINE_STOP_FLAG) and
204
+ # 两个block宽度差距超过2倍也不合并
205
+ abs(block1_weight - block2_weight) < min_block_weight
206
+ ):
207
+ if block1['page_num'] != block2['page_num']:
208
+ for line in block1['lines']:
209
+ for span in line['spans']:
210
+ span[CROSS_PAGE] = True
211
+ block2['lines'].extend(block1['lines'])
212
+ block1['lines'] = []
213
+ block1[LINES_DELETED] = True
214
+
215
+ return block1, block2
216
+
217
+
218
+ def __merge_2_list_blocks(block1, block2):
219
+ if block1['page_num'] != block2['page_num']:
220
+ for line in block1['lines']:
221
+ for span in line['spans']:
222
+ span[CROSS_PAGE] = True
223
+ block2['lines'].extend(block1['lines'])
224
+ block1['lines'] = []
225
+ block1[LINES_DELETED] = True
226
+
227
+ return block1, block2
228
+
229
+
230
+ def __is_list_group(text_blocks_group):
231
+ # list group的特征是一个group内的所有block都满足以下条件
232
+ # 1.每个block都不超过3行 2. 每个block 的左边界都比较接近(逻辑简单点先不加这个规则)
233
+ for block in text_blocks_group:
234
+ if len(block['lines']) > 3:
235
+ return False
236
+ return True
237
+
238
+
239
+ def __para_merge_page(blocks):
240
+ page_text_blocks_groups = __process_blocks(blocks)
241
+ for text_blocks_group in page_text_blocks_groups:
242
+
243
+ if len(text_blocks_group) > 0:
244
+ # 需要先在合并前对所有block判断是否为list or index block
245
+ for block in text_blocks_group:
246
+ block_type = __is_list_or_index_block(block)
247
+ block['type'] = block_type
248
+ # logger.info(f"{block['type']}:{block}")
249
+
250
+ if len(text_blocks_group) > 1:
251
+
252
+ # 在合并前判断这个group 是否是一个 list group
253
+ is_list_group = __is_list_group(text_blocks_group)
254
+
255
+ # 倒序遍历
256
+ for i in range(len(text_blocks_group) - 1, -1, -1):
257
+ current_block = text_blocks_group[i]
258
+
259
+ # 检查是否有前一个块
260
+ if i - 1 >= 0:
261
+ prev_block = text_blocks_group[i - 1]
262
+
263
+ if current_block['type'] == 'text' and prev_block['type'] == 'text' and not is_list_group:
264
+ __merge_2_text_blocks(current_block, prev_block)
265
+ elif (
266
+ (current_block['type'] == BlockType.List and prev_block['type'] == BlockType.List) or
267
+ (current_block['type'] == BlockType.Index and prev_block['type'] == BlockType.Index)
268
+ ):
269
+ __merge_2_list_blocks(current_block, prev_block)
270
+
271
+ else:
272
+ continue
273
+
274
+
275
+ def para_split(pdf_info_dict, debug_mode=False):
276
+ all_blocks = []
277
+ for page_num, page in pdf_info_dict.items():
278
+ blocks = copy.deepcopy(page['preproc_blocks'])
279
+ for block in blocks:
280
+ block['page_num'] = page_num
281
+ all_blocks.extend(blocks)
282
+
283
+ __para_merge_page(all_blocks)
284
+ for page_num, page in pdf_info_dict.items():
285
+ page['para_blocks'] = []
286
+ for block in all_blocks:
287
+ if block['page_num'] == page_num:
288
+ page['para_blocks'].append(block)
289
+
290
+
291
+ if __name__ == '__main__':
292
+ input_blocks = []
293
+ # 调用函数
294
+ groups = __process_blocks(input_blocks)
295
+ for group_index, group in enumerate(groups):
296
+ print(f"Group {group_index}: {group}")
@@ -1,4 +1,6 @@
1
- from magic_pdf.pdf_parse_union_core import pdf_parse_union
1
+ from magic_pdf.config.enums import SupportedPdfParseMethod
2
+ from magic_pdf.data.dataset import PymuDocDataset
3
+ from magic_pdf.pdf_parse_union_core_v2 import pdf_parse_union
2
4
 
3
5
 
4
6
  def parse_pdf_by_ocr(pdf_bytes,
@@ -8,10 +10,11 @@ def parse_pdf_by_ocr(pdf_bytes,
8
10
  end_page_id=None,
9
11
  debug_mode=False,
10
12
  ):
11
- return pdf_parse_union(pdf_bytes,
13
+ dataset = PymuDocDataset(pdf_bytes)
14
+ return pdf_parse_union(dataset,
12
15
  model_list,
13
16
  imageWriter,
14
- "ocr",
17
+ SupportedPdfParseMethod.OCR,
15
18
  start_page_id=start_page_id,
16
19
  end_page_id=end_page_id,
17
20
  debug_mode=debug_mode,
@@ -1,4 +1,6 @@
1
- from magic_pdf.pdf_parse_union_core import pdf_parse_union
1
+ from magic_pdf.config.enums import SupportedPdfParseMethod
2
+ from magic_pdf.data.dataset import PymuDocDataset
3
+ from magic_pdf.pdf_parse_union_core_v2 import pdf_parse_union
2
4
 
3
5
 
4
6
  def parse_pdf_by_txt(
@@ -9,10 +11,11 @@ def parse_pdf_by_txt(
9
11
  end_page_id=None,
10
12
  debug_mode=False,
11
13
  ):
12
- return pdf_parse_union(pdf_bytes,
14
+ dataset = PymuDocDataset(pdf_bytes)
15
+ return pdf_parse_union(dataset,
13
16
  model_list,
14
17
  imageWriter,
15
- "txt",
18
+ SupportedPdfParseMethod.TXT,
16
19
  start_page_id=start_page_id,
17
20
  end_page_id=end_page_id,
18
21
  debug_mode=debug_mode,