magic-pdf 0.8.1__py3-none-any.whl → 0.9.1__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 +143 -0
  9. magic_pdf/data/data_reader_writer/s3.py +73 -0
  10. magic_pdf/data/dataset.py +194 -0
  11. magic_pdf/data/io/__init__.py +6 -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 +19 -0
  17. magic_pdf/data/utils.py +32 -0
  18. magic_pdf/dict2md/ocr_mkcontent.py +106 -244
  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 +170 -83
  30. magic_pdf/model/pek_sub_modules/structeqtable/StructTableModel.py +40 -16
  31. magic_pdf/model/ppTableModel.py +8 -6
  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 +322 -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.1.dist-info}/LICENSE.md +1 -0
  53. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.1.dist-info}/METADATA +124 -78
  54. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.1.dist-info}/RECORD +57 -33
  55. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.1.dist-info}/WHEEL +0 -0
  56. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.1.dist-info}/entry_points.txt +0 -0
  57. {magic_pdf-0.8.1.dist-info → magic_pdf-0.9.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,125 @@
1
+ from collections import defaultdict
2
+ from typing import List, Dict
3
+
4
+ import torch
5
+ from transformers import LayoutLMv3ForTokenClassification
6
+
7
+ MAX_LEN = 510
8
+ CLS_TOKEN_ID = 0
9
+ UNK_TOKEN_ID = 3
10
+ EOS_TOKEN_ID = 2
11
+
12
+
13
+ class DataCollator:
14
+ def __call__(self, features: List[dict]) -> Dict[str, torch.Tensor]:
15
+ bbox = []
16
+ labels = []
17
+ input_ids = []
18
+ attention_mask = []
19
+
20
+ # clip bbox and labels to max length, build input_ids and attention_mask
21
+ for feature in features:
22
+ _bbox = feature["source_boxes"]
23
+ if len(_bbox) > MAX_LEN:
24
+ _bbox = _bbox[:MAX_LEN]
25
+ _labels = feature["target_index"]
26
+ if len(_labels) > MAX_LEN:
27
+ _labels = _labels[:MAX_LEN]
28
+ _input_ids = [UNK_TOKEN_ID] * len(_bbox)
29
+ _attention_mask = [1] * len(_bbox)
30
+ assert len(_bbox) == len(_labels) == len(_input_ids) == len(_attention_mask)
31
+ bbox.append(_bbox)
32
+ labels.append(_labels)
33
+ input_ids.append(_input_ids)
34
+ attention_mask.append(_attention_mask)
35
+
36
+ # add CLS and EOS tokens
37
+ for i in range(len(bbox)):
38
+ bbox[i] = [[0, 0, 0, 0]] + bbox[i] + [[0, 0, 0, 0]]
39
+ labels[i] = [-100] + labels[i] + [-100]
40
+ input_ids[i] = [CLS_TOKEN_ID] + input_ids[i] + [EOS_TOKEN_ID]
41
+ attention_mask[i] = [1] + attention_mask[i] + [1]
42
+
43
+ # padding to max length
44
+ max_len = max(len(x) for x in bbox)
45
+ for i in range(len(bbox)):
46
+ bbox[i] = bbox[i] + [[0, 0, 0, 0]] * (max_len - len(bbox[i]))
47
+ labels[i] = labels[i] + [-100] * (max_len - len(labels[i]))
48
+ input_ids[i] = input_ids[i] + [EOS_TOKEN_ID] * (max_len - len(input_ids[i]))
49
+ attention_mask[i] = attention_mask[i] + [0] * (
50
+ max_len - len(attention_mask[i])
51
+ )
52
+
53
+ ret = {
54
+ "bbox": torch.tensor(bbox),
55
+ "attention_mask": torch.tensor(attention_mask),
56
+ "labels": torch.tensor(labels),
57
+ "input_ids": torch.tensor(input_ids),
58
+ }
59
+ # set label > MAX_LEN to -100, because original labels may be > MAX_LEN
60
+ ret["labels"][ret["labels"] > MAX_LEN] = -100
61
+ # set label > 0 to label-1, because original labels are 1-indexed
62
+ ret["labels"][ret["labels"] > 0] -= 1
63
+ return ret
64
+
65
+
66
+ def boxes2inputs(boxes: List[List[int]]) -> Dict[str, torch.Tensor]:
67
+ bbox = [[0, 0, 0, 0]] + boxes + [[0, 0, 0, 0]]
68
+ input_ids = [CLS_TOKEN_ID] + [UNK_TOKEN_ID] * len(boxes) + [EOS_TOKEN_ID]
69
+ attention_mask = [1] + [1] * len(boxes) + [1]
70
+ return {
71
+ "bbox": torch.tensor([bbox]),
72
+ "attention_mask": torch.tensor([attention_mask]),
73
+ "input_ids": torch.tensor([input_ids]),
74
+ }
75
+
76
+
77
+ def prepare_inputs(
78
+ inputs: Dict[str, torch.Tensor], model: LayoutLMv3ForTokenClassification
79
+ ) -> Dict[str, torch.Tensor]:
80
+ ret = {}
81
+ for k, v in inputs.items():
82
+ v = v.to(model.device)
83
+ if torch.is_floating_point(v):
84
+ v = v.to(model.dtype)
85
+ ret[k] = v
86
+ return ret
87
+
88
+
89
+ def parse_logits(logits: torch.Tensor, length: int) -> List[int]:
90
+ """
91
+ parse logits to orders
92
+
93
+ :param logits: logits from model
94
+ :param length: input length
95
+ :return: orders
96
+ """
97
+ logits = logits[1 : length + 1, :length]
98
+ orders = logits.argsort(descending=False).tolist()
99
+ ret = [o.pop() for o in orders]
100
+ while True:
101
+ order_to_idxes = defaultdict(list)
102
+ for idx, order in enumerate(ret):
103
+ order_to_idxes[order].append(idx)
104
+ # filter idxes len > 1
105
+ order_to_idxes = {k: v for k, v in order_to_idxes.items() if len(v) > 1}
106
+ if not order_to_idxes:
107
+ break
108
+ # filter
109
+ for order, idxes in order_to_idxes.items():
110
+ # find original logits of idxes
111
+ idxes_to_logit = {}
112
+ for idx in idxes:
113
+ idxes_to_logit[idx] = logits[idx, order]
114
+ idxes_to_logit = sorted(
115
+ idxes_to_logit.items(), key=lambda x: x[1], reverse=True
116
+ )
117
+ # keep the highest logit as order, set others to next candidate
118
+ for idx, _ in idxes_to_logit[1:]:
119
+ ret[idx] = orders[idx].pop()
120
+
121
+ return ret
122
+
123
+
124
+ def check_duplicate(a: List[int]) -> bool:
125
+ return len(a) != len(set(a))
@@ -0,0 +1,322 @@
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
+ block_height = block['bbox_fs'][3] - block['bbox_fs'][1]
67
+
68
+ left_close_num = 0
69
+ left_not_close_num = 0
70
+ right_not_close_num = 0
71
+ right_close_num = 0
72
+ lines_text_list = []
73
+ center_close_num = 0
74
+ external_sides_not_close_num = 0
75
+ multiple_para_flag = False
76
+ last_line = block['lines'][-1]
77
+
78
+ # 如果首行左边不顶格而右边顶格,末行左边顶格而右边不顶格 (第一行可能可以右边不顶格)
79
+ if (first_line['bbox'][0] - block['bbox_fs'][0] > line_height / 2 and
80
+ # block['bbox_fs'][2] - first_line['bbox'][2] < line_height and
81
+ abs(last_line['bbox'][0] - block['bbox_fs'][0]) < line_height / 2 and
82
+ block['bbox_fs'][2] - last_line['bbox'][2] > line_height
83
+ ):
84
+ multiple_para_flag = True
85
+
86
+ for line in block['lines']:
87
+
88
+ line_mid_x = (line['bbox'][0] + line['bbox'][2]) / 2
89
+ block_mid_x = (block['bbox_fs'][0] + block['bbox_fs'][2]) / 2
90
+ if (
91
+ line['bbox'][0] - block['bbox_fs'][0] > 0.8 * line_height and
92
+ block['bbox_fs'][2] - line['bbox'][2] > 0.8 * line_height
93
+ ):
94
+ external_sides_not_close_num += 1
95
+ if abs(line_mid_x - block_mid_x) < line_height / 2:
96
+ center_close_num += 1
97
+
98
+ line_text = ""
99
+
100
+ for span in line['spans']:
101
+ span_type = span['type']
102
+ if span_type == ContentType.Text:
103
+ line_text += span['content'].strip()
104
+
105
+ lines_text_list.append(line_text)
106
+
107
+ # 计算line左侧顶格数量是否大于2,是否顶格用abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height/2 来判断
108
+ if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
109
+ left_close_num += 1
110
+ elif line['bbox'][0] - block['bbox_fs'][0] > line_height:
111
+ # logger.info(f"{line_text}, {block['bbox_fs']}, {line['bbox']}")
112
+ left_not_close_num += 1
113
+
114
+ # 计算右侧是否顶格
115
+ if abs(block['bbox_fs'][2] - line['bbox'][2]) < line_height:
116
+ right_close_num += 1
117
+ else:
118
+ # 右侧不顶格情况下是否有一段距离,拍脑袋用0.3block宽度做阈值
119
+ closed_area = 0.26 * block_weight
120
+ # closed_area = 5 * line_height
121
+ if block['bbox_fs'][2] - line['bbox'][2] > closed_area:
122
+ right_not_close_num += 1
123
+
124
+ # 判断lines_text_list中的元素是否有超过80%都以LIST_END_FLAG结尾
125
+ line_end_flag = False
126
+ # 判断lines_text_list中的元素是否有超过80%都以数字开头或都以数字结尾
127
+ line_num_flag = False
128
+ num_start_count = 0
129
+ num_end_count = 0
130
+ flag_end_count = 0
131
+ if len(lines_text_list) > 0:
132
+ for line_text in lines_text_list:
133
+ if len(line_text) > 0:
134
+ if line_text[-1] in LIST_END_FLAG:
135
+ flag_end_count += 1
136
+ if line_text[0].isdigit():
137
+ num_start_count += 1
138
+ if line_text[-1].isdigit():
139
+ num_end_count += 1
140
+
141
+ if flag_end_count / len(lines_text_list) >= 0.8:
142
+ line_end_flag = True
143
+
144
+ if num_start_count / len(lines_text_list) >= 0.8 or num_end_count / len(lines_text_list) >= 0.8:
145
+ line_num_flag = True
146
+
147
+ # 有的目录右侧不贴边, 目前认为左边或者右边有一边全贴边,且符合数字规则极为index
148
+ if ((left_close_num / len(block['lines']) >= 0.8 or right_close_num / len(block['lines']) >= 0.8)
149
+ and line_num_flag
150
+ ):
151
+ for line in block['lines']:
152
+ line[ListLineTag.IS_LIST_START_LINE] = True
153
+ return BlockType.Index
154
+
155
+ # 全部line都居中的特殊list识别,每行都需要换行,特征是多行,且大多数行都前后not_close,每line中点x坐标接近
156
+ # 补充条件block的长宽比有要求
157
+ elif (
158
+ external_sides_not_close_num >= 2 and
159
+ center_close_num == len(block['lines']) and
160
+ external_sides_not_close_num / len(block['lines']) >= 0.5 and
161
+ block_height / block_weight > 0.4
162
+ ):
163
+ for line in block['lines']:
164
+ line[ListLineTag.IS_LIST_START_LINE] = True
165
+ return BlockType.List
166
+
167
+ elif left_close_num >= 2 and (
168
+ right_not_close_num >= 2 or line_end_flag or left_not_close_num >= 2) and not multiple_para_flag:
169
+ # 处理一种特殊的没有缩进的list,所有行都贴左边,通过右边的空隙判断是否是item尾
170
+ if left_close_num / len(block['lines']) > 0.8:
171
+ # 这种是每个item只有一行,且左边都贴边的短item list
172
+ if flag_end_count == 0 and right_close_num / len(block['lines']) < 0.5:
173
+ for line in block['lines']:
174
+ if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
175
+ line[ListLineTag.IS_LIST_START_LINE] = True
176
+ # 这种是大部分line item 都有结束标识符的情况,按结束标识符区分不同item
177
+ elif line_end_flag:
178
+ for i, line in enumerate(block['lines']):
179
+ if lines_text_list[i][-1] in LIST_END_FLAG:
180
+ line[ListLineTag.IS_LIST_END_LINE] = True
181
+ if i + 1 < len(block['lines']):
182
+ block['lines'][i + 1][ListLineTag.IS_LIST_START_LINE] = True
183
+ # line item基本没有结束标识符,而且也没有缩进,按右侧空隙判断哪些是item end
184
+ else:
185
+ line_start_flag = False
186
+ for i, line in enumerate(block['lines']):
187
+ if line_start_flag:
188
+ line[ListLineTag.IS_LIST_START_LINE] = True
189
+ line_start_flag = False
190
+ # elif abs(block['bbox_fs'][2] - line['bbox'][2]) > line_height:
191
+ if abs(block['bbox_fs'][2] - line['bbox'][2]) > 0.1 * block_weight:
192
+ line[ListLineTag.IS_LIST_END_LINE] = True
193
+ line_start_flag = True
194
+ # 一种有缩进的特殊有序list,start line 左侧不贴边且以数字开头,end line 以 IS_LIST_END_LINE 结尾且数量和start line 一致
195
+ elif num_start_count >= 2 and num_start_count == flag_end_count: # 简单一点先不考虑左侧不贴边的情况
196
+ for i, line in enumerate(block['lines']):
197
+ if lines_text_list[i][0].isdigit():
198
+ line[ListLineTag.IS_LIST_START_LINE] = True
199
+ if lines_text_list[i][-1] in LIST_END_FLAG:
200
+ line[ListLineTag.IS_LIST_END_LINE] = True
201
+ else:
202
+ # 正常有缩进的list处理
203
+ for line in block['lines']:
204
+ if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
205
+ line[ListLineTag.IS_LIST_START_LINE] = True
206
+ if abs(block['bbox_fs'][2] - line['bbox'][2]) > line_height:
207
+ line[ListLineTag.IS_LIST_END_LINE] = True
208
+
209
+ return BlockType.List
210
+ else:
211
+ return BlockType.Text
212
+ else:
213
+ return BlockType.Text
214
+
215
+
216
+ def __merge_2_text_blocks(block1, block2):
217
+ if len(block1['lines']) > 0:
218
+ first_line = block1['lines'][0]
219
+ line_height = first_line['bbox'][3] - first_line['bbox'][1]
220
+ block1_weight = block1['bbox'][2] - block1['bbox'][0]
221
+ block2_weight = block2['bbox'][2] - block2['bbox'][0]
222
+ min_block_weight = min(block1_weight, block2_weight)
223
+ if abs(block1['bbox_fs'][0] - first_line['bbox'][0]) < line_height / 2:
224
+ last_line = block2['lines'][-1]
225
+ if len(last_line['spans']) > 0:
226
+ last_span = last_line['spans'][-1]
227
+ line_height = last_line['bbox'][3] - last_line['bbox'][1]
228
+ if (abs(block2['bbox_fs'][2] - last_line['bbox'][2]) < line_height and
229
+ not last_span['content'].endswith(LINE_STOP_FLAG) and
230
+ # 两个block宽度差距超过2倍也不合并
231
+ abs(block1_weight - block2_weight) < min_block_weight
232
+ ):
233
+ if block1['page_num'] != block2['page_num']:
234
+ for line in block1['lines']:
235
+ for span in line['spans']:
236
+ span[CROSS_PAGE] = True
237
+ block2['lines'].extend(block1['lines'])
238
+ block1['lines'] = []
239
+ block1[LINES_DELETED] = True
240
+
241
+ return block1, block2
242
+
243
+
244
+ def __merge_2_list_blocks(block1, block2):
245
+ if block1['page_num'] != block2['page_num']:
246
+ for line in block1['lines']:
247
+ for span in line['spans']:
248
+ span[CROSS_PAGE] = True
249
+ block2['lines'].extend(block1['lines'])
250
+ block1['lines'] = []
251
+ block1[LINES_DELETED] = True
252
+
253
+ return block1, block2
254
+
255
+
256
+ def __is_list_group(text_blocks_group):
257
+ # list group的特征是一个group内的所有block都满足以下条件
258
+ # 1.每个block都不超过3行 2. 每个block 的左边界都比较接近(逻辑简单点先不加这个规则)
259
+ for block in text_blocks_group:
260
+ if len(block['lines']) > 3:
261
+ return False
262
+ return True
263
+
264
+
265
+ def __para_merge_page(blocks):
266
+ page_text_blocks_groups = __process_blocks(blocks)
267
+ for text_blocks_group in page_text_blocks_groups:
268
+
269
+ if len(text_blocks_group) > 0:
270
+ # 需要先在合并前对所有block判断是否为list or index block
271
+ for block in text_blocks_group:
272
+ block_type = __is_list_or_index_block(block)
273
+ block['type'] = block_type
274
+ # logger.info(f"{block['type']}:{block}")
275
+
276
+ if len(text_blocks_group) > 1:
277
+
278
+ # 在合并前判断这个group 是否是一个 list group
279
+ is_list_group = __is_list_group(text_blocks_group)
280
+
281
+ # 倒序遍历
282
+ for i in range(len(text_blocks_group) - 1, -1, -1):
283
+ current_block = text_blocks_group[i]
284
+
285
+ # 检查是否有前一个块
286
+ if i - 1 >= 0:
287
+ prev_block = text_blocks_group[i - 1]
288
+
289
+ if current_block['type'] == 'text' and prev_block['type'] == 'text' and not is_list_group:
290
+ __merge_2_text_blocks(current_block, prev_block)
291
+ elif (
292
+ (current_block['type'] == BlockType.List and prev_block['type'] == BlockType.List) or
293
+ (current_block['type'] == BlockType.Index and prev_block['type'] == BlockType.Index)
294
+ ):
295
+ __merge_2_list_blocks(current_block, prev_block)
296
+
297
+ else:
298
+ continue
299
+
300
+
301
+ def para_split(pdf_info_dict, debug_mode=False):
302
+ all_blocks = []
303
+ for page_num, page in pdf_info_dict.items():
304
+ blocks = copy.deepcopy(page['preproc_blocks'])
305
+ for block in blocks:
306
+ block['page_num'] = page_num
307
+ all_blocks.extend(blocks)
308
+
309
+ __para_merge_page(all_blocks)
310
+ for page_num, page in pdf_info_dict.items():
311
+ page['para_blocks'] = []
312
+ for block in all_blocks:
313
+ if block['page_num'] == page_num:
314
+ page['para_blocks'].append(block)
315
+
316
+
317
+ if __name__ == '__main__':
318
+ input_blocks = []
319
+ # 调用函数
320
+ groups = __process_blocks(input_blocks)
321
+ for group_index, group in enumerate(groups):
322
+ 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,