pdf_parse_union_core_v2.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. import copy
  2. import os
  3. import statistics
  4. import time
  5. from typing import List
  6. import torch
  7. from loguru import logger
  8. from magic_pdf.config.drop_reason import DropReason
  9. from magic_pdf.config.enums import SupportedPdfParseMethod
  10. from magic_pdf.config.ocr_content_type import BlockType, ContentType
  11. from magic_pdf.data.dataset import Dataset, PageableData
  12. from magic_pdf.libs.boxbase import calculate_overlap_area_in_bbox1_area_ratio
  13. from magic_pdf.libs.clean_memory import clean_memory
  14. from magic_pdf.libs.commons import fitz, get_delta_time
  15. from magic_pdf.libs.config_reader import get_local_layoutreader_model_dir
  16. from magic_pdf.libs.convert_utils import dict_to_list
  17. from magic_pdf.libs.hash_utils import compute_md5
  18. from magic_pdf.libs.local_math import float_equal
  19. from magic_pdf.libs.pdf_image_tools import cut_image_to_pil_image
  20. from magic_pdf.model.magic_model import MagicModel
  21. os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新
  22. os.environ['YOLO_VERBOSE'] = 'False' # disable yolo logger
  23. try:
  24. import torchtext
  25. if torchtext.__version__ >= "0.18.0":
  26. torchtext.disable_torchtext_deprecation_warning()
  27. except ImportError:
  28. pass
  29. from magic_pdf.model.sub_modules.model_init import AtomModelSingleton
  30. from magic_pdf.para.para_split_v3 import para_split
  31. from magic_pdf.pre_proc.citationmarker_remove import remove_citation_marker
  32. from magic_pdf.pre_proc.construct_page_dict import \
  33. ocr_construct_page_component_v2
  34. from magic_pdf.pre_proc.cut_image import ocr_cut_image_and_table
  35. from magic_pdf.pre_proc.equations_replace import (
  36. combine_chars_to_pymudict, remove_chars_in_text_blocks,
  37. replace_equations_in_textblock)
  38. from magic_pdf.pre_proc.ocr_detect_all_bboxes import \
  39. ocr_prepare_bboxes_for_layout_split_v2
  40. from magic_pdf.pre_proc.ocr_dict_merge import (fill_spans_in_blocks,
  41. fix_block_spans_v2,
  42. fix_discarded_block)
  43. from magic_pdf.pre_proc.ocr_span_list_modify import (
  44. get_qa_need_list_v2, remove_overlaps_low_confidence_spans,
  45. remove_overlaps_min_spans)
  46. from magic_pdf.pre_proc.resolve_bbox_conflict import \
  47. check_useful_block_horizontal_overlap
  48. def remove_horizontal_overlap_block_which_smaller(all_bboxes):
  49. useful_blocks = []
  50. for bbox in all_bboxes:
  51. useful_blocks.append({'bbox': bbox[:4]})
  52. is_useful_block_horz_overlap, smaller_bbox, bigger_bbox = (
  53. check_useful_block_horizontal_overlap(useful_blocks)
  54. )
  55. if is_useful_block_horz_overlap:
  56. logger.warning(
  57. f'skip this page, reason: {DropReason.USEFUL_BLOCK_HOR_OVERLAP}, smaller bbox is {smaller_bbox}, bigger bbox is {bigger_bbox}'
  58. ) # noqa: E501
  59. for bbox in all_bboxes.copy():
  60. if smaller_bbox == bbox[:4]:
  61. all_bboxes.remove(bbox)
  62. return is_useful_block_horz_overlap, all_bboxes
  63. def __replace_STX_ETX(text_str: str):
  64. """Replace \u0002 and \u0003, as these characters become garbled when extracted using pymupdf. In fact, they were originally quotation marks.
  65. Drawback: This issue is only observed in English text; it has not been found in Chinese text so far.
  66. Args:
  67. text_str (str): raw text
  68. Returns:
  69. _type_: replaced text
  70. """ # noqa: E501
  71. if text_str:
  72. s = text_str.replace('\u0002', "'")
  73. s = s.replace('\u0003', "'")
  74. return s
  75. return text_str
  76. def chars_to_content(span):
  77. # # 先给chars按char['bbox']的x坐标排序
  78. # span['chars'] = sorted(span['chars'], key=lambda x: x['bbox'][0])
  79. # 先给chars按char['bbox']的中心点的x坐标排序
  80. span['chars'] = sorted(span['chars'], key=lambda x: (x['bbox'][0] + x['bbox'][2]) / 2)
  81. content = ''
  82. # 求char的平均宽度
  83. if len(span['chars']) == 0:
  84. span['content'] = content
  85. del span['chars']
  86. return
  87. else:
  88. char_width_sum = sum([char['bbox'][2] - char['bbox'][0] for char in span['chars']])
  89. char_avg_width = char_width_sum / len(span['chars'])
  90. for char in span['chars']:
  91. # 如果下一个char的x0和上一个char的x1距离超过一个字符宽度,则需要在中间插入一个空格
  92. if char['bbox'][0] - span['chars'][span['chars'].index(char) - 1]['bbox'][2] > char_avg_width:
  93. content += ' '
  94. content += char['c']
  95. span['content'] = __replace_STX_ETX(content)
  96. del span['chars']
  97. LINE_STOP_FLAG = ('.', '!', '?', '。', '!', '?', ')', ')', '"', '”', ':', ':', ';', ';', ']', '】', '}', '}', '>', '》', '、', ',', ',', '-', '—', '–',)
  98. def fill_char_in_spans(spans, all_chars):
  99. for char in all_chars:
  100. for span in spans:
  101. # 判断char是否属于LINE_STOP_FLAG
  102. if char['c'] in LINE_STOP_FLAG:
  103. char_is_line_stop_flag = True
  104. else:
  105. char_is_line_stop_flag = False
  106. if calculate_char_in_span(char['bbox'], span['bbox'], char_is_line_stop_flag):
  107. span['chars'].append(char)
  108. break
  109. for span in spans:
  110. chars_to_content(span)
  111. # 使用鲁棒性更强的中心点坐标判断
  112. def calculate_char_in_span(char_bbox, span_bbox, char_is_line_stop_flag):
  113. char_center_x = (char_bbox[0] + char_bbox[2]) / 2
  114. char_center_y = (char_bbox[1] + char_bbox[3]) / 2
  115. span_center_y = (span_bbox[1] + span_bbox[3]) / 2
  116. span_height = span_bbox[3] - span_bbox[1]
  117. if (
  118. span_bbox[0] < char_center_x < span_bbox[2]
  119. and span_bbox[1] < char_center_y < span_bbox[3]
  120. and abs(char_center_y - span_center_y) < span_height / 4 # 字符的中轴和span的中轴高度差不能超过1/4span高度
  121. ):
  122. return True
  123. else:
  124. # 如果char是LINE_STOP_FLAG,就不用中心点判定,换一种方案(左边界在span区域内,高度判定和之前逻辑一致)
  125. # 主要是给结尾符号一个进入span的机会,这个char还应该离span右边界较近
  126. if char_is_line_stop_flag:
  127. if (
  128. (span_bbox[2] - span_height) < char_bbox[0] < span_bbox[2]
  129. and char_center_x > span_bbox[0]
  130. and span_bbox[1] < char_center_y < span_bbox[3]
  131. and abs(char_center_y - span_center_y) < span_height / 4
  132. ):
  133. return True
  134. else:
  135. return False
  136. def txt_spans_extract_v2(pdf_page, spans, all_bboxes, all_discarded_blocks, lang):
  137. useful_spans = []
  138. unuseful_spans = []
  139. for span in spans:
  140. for block in all_bboxes:
  141. if block[7] in [BlockType.ImageBody, BlockType.TableBody, BlockType.InterlineEquation]:
  142. continue
  143. else:
  144. if calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block[0:4]) > 0.5:
  145. useful_spans.append(span)
  146. break
  147. for block in all_discarded_blocks:
  148. if calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block[0:4]) > 0.5:
  149. unuseful_spans.append(span)
  150. break
  151. text_blocks = pdf_page.get_text('rawdict', flags=fitz.TEXTFLAGS_TEXT)['blocks']
  152. # @todo: 拿到char之后把倾斜角度较大的先删一遍
  153. all_pymu_chars = []
  154. for block in text_blocks:
  155. for line in block['lines']:
  156. for span in line['spans']:
  157. all_pymu_chars.extend(span['chars'])
  158. new_spans = []
  159. for span in useful_spans:
  160. if span['type'] in [ContentType.Text]:
  161. span['chars'] = []
  162. new_spans.append(span)
  163. for span in unuseful_spans:
  164. if span['type'] in [ContentType.Text]:
  165. span['chars'] = []
  166. new_spans.append(span)
  167. fill_char_in_spans(new_spans, all_pymu_chars)
  168. empty_spans = []
  169. for span in new_spans:
  170. if len(span['content']) == 0:
  171. empty_spans.append(span)
  172. if len(empty_spans) > 0:
  173. # 初始化ocr模型
  174. atom_model_manager = AtomModelSingleton()
  175. ocr_model = atom_model_manager.get_atom_model(
  176. atom_model_name="ocr",
  177. ocr_show_log=False,
  178. det_db_box_thresh=0.3,
  179. lang=lang
  180. )
  181. for span in empty_spans:
  182. spans.remove(span)
  183. # 对span的bbox截图
  184. span_img = cut_image_to_pil_image(span['bbox'], pdf_page, mode="cv2")
  185. ocr_res = ocr_model.ocr(span_img, det=False)
  186. # logger.info(f"ocr_res: {ocr_res}")
  187. # logger.info(f"empty_span: {span}")
  188. if ocr_res and len(ocr_res) > 0:
  189. if len(ocr_res[0]) > 0:
  190. ocr_text, ocr_score = ocr_res[0][0]
  191. if ocr_score > 0.5 and len(ocr_text) > 0:
  192. span['content'] = ocr_text
  193. spans.append(span)
  194. return spans
  195. def txt_spans_extract_v1(pdf_page, inline_equations, interline_equations):
  196. text_raw_blocks = pdf_page.get_text('dict', flags=fitz.TEXTFLAGS_TEXT)['blocks']
  197. char_level_text_blocks = pdf_page.get_text('rawdict', flags=fitz.TEXTFLAGS_TEXT)[
  198. 'blocks'
  199. ]
  200. text_blocks = combine_chars_to_pymudict(text_raw_blocks, char_level_text_blocks)
  201. text_blocks = replace_equations_in_textblock(
  202. text_blocks, inline_equations, interline_equations
  203. )
  204. text_blocks = remove_citation_marker(text_blocks)
  205. text_blocks = remove_chars_in_text_blocks(text_blocks)
  206. spans = []
  207. for v in text_blocks:
  208. for line in v['lines']:
  209. for span in line['spans']:
  210. bbox = span['bbox']
  211. if float_equal(bbox[0], bbox[2]) or float_equal(bbox[1], bbox[3]):
  212. continue
  213. if span.get('type') not in (
  214. ContentType.InlineEquation,
  215. ContentType.InterlineEquation,
  216. ):
  217. spans.append(
  218. {
  219. 'bbox': list(span['bbox']),
  220. 'content': __replace_STX_ETX(span['text']),
  221. 'type': ContentType.Text,
  222. 'score': 1.0,
  223. }
  224. )
  225. return spans
  226. def replace_text_span(pymu_spans, ocr_spans):
  227. return list(filter(lambda x: x['type'] != ContentType.Text, ocr_spans)) + pymu_spans
  228. def model_init(model_name: str):
  229. from transformers import LayoutLMv3ForTokenClassification
  230. if torch.cuda.is_available():
  231. device = torch.device('cuda')
  232. if torch.cuda.is_bf16_supported():
  233. supports_bfloat16 = True
  234. else:
  235. supports_bfloat16 = False
  236. else:
  237. device = torch.device('cpu')
  238. supports_bfloat16 = False
  239. if model_name == 'layoutreader':
  240. # 检测modelscope的缓存目录是否存在
  241. layoutreader_model_dir = get_local_layoutreader_model_dir()
  242. if os.path.exists(layoutreader_model_dir):
  243. model = LayoutLMv3ForTokenClassification.from_pretrained(
  244. layoutreader_model_dir
  245. )
  246. else:
  247. logger.warning(
  248. 'local layoutreader model not exists, use online model from huggingface'
  249. )
  250. model = LayoutLMv3ForTokenClassification.from_pretrained(
  251. 'hantian/layoutreader'
  252. )
  253. # 检查设备是否支持 bfloat16
  254. if supports_bfloat16:
  255. model.bfloat16()
  256. model.to(device).eval()
  257. else:
  258. logger.error('model name not allow')
  259. exit(1)
  260. return model
  261. class ModelSingleton:
  262. _instance = None
  263. _models = {}
  264. def __new__(cls, *args, **kwargs):
  265. if cls._instance is None:
  266. cls._instance = super().__new__(cls)
  267. return cls._instance
  268. def get_model(self, model_name: str):
  269. if model_name not in self._models:
  270. self._models[model_name] = model_init(model_name=model_name)
  271. return self._models[model_name]
  272. def do_predict(boxes: List[List[int]], model) -> List[int]:
  273. from magic_pdf.model.sub_modules.reading_oreder.layoutreader.helpers import (
  274. boxes2inputs, parse_logits, prepare_inputs)
  275. inputs = boxes2inputs(boxes)
  276. inputs = prepare_inputs(inputs, model)
  277. logits = model(**inputs).logits.cpu().squeeze(0)
  278. return parse_logits(logits, len(boxes))
  279. def cal_block_index(fix_blocks, sorted_bboxes):
  280. if sorted_bboxes is not None:
  281. # 使用layoutreader排序
  282. for block in fix_blocks:
  283. line_index_list = []
  284. if len(block['lines']) == 0:
  285. block['index'] = sorted_bboxes.index(block['bbox'])
  286. else:
  287. for line in block['lines']:
  288. line['index'] = sorted_bboxes.index(line['bbox'])
  289. line_index_list.append(line['index'])
  290. median_value = statistics.median(line_index_list)
  291. block['index'] = median_value
  292. # 删除图表body block中的虚拟line信息, 并用real_lines信息回填
  293. if block['type'] in [BlockType.ImageBody, BlockType.TableBody]:
  294. block['virtual_lines'] = copy.deepcopy(block['lines'])
  295. block['lines'] = copy.deepcopy(block['real_lines'])
  296. del block['real_lines']
  297. else:
  298. # 使用xycut排序
  299. block_bboxes = []
  300. for block in fix_blocks:
  301. block_bboxes.append(block['bbox'])
  302. # 删除图表body block中的虚拟line信息, 并用real_lines信息回填
  303. if block['type'] in [BlockType.ImageBody, BlockType.TableBody]:
  304. block['virtual_lines'] = copy.deepcopy(block['lines'])
  305. block['lines'] = copy.deepcopy(block['real_lines'])
  306. del block['real_lines']
  307. import numpy as np
  308. from magic_pdf.model.sub_modules.reading_oreder.layoutreader.xycut import \
  309. recursive_xy_cut
  310. random_boxes = np.array(block_bboxes)
  311. np.random.shuffle(random_boxes)
  312. res = []
  313. recursive_xy_cut(np.asarray(random_boxes).astype(int), np.arange(len(block_bboxes)), res)
  314. assert len(res) == len(block_bboxes)
  315. sorted_boxes = random_boxes[np.array(res)].tolist()
  316. for i, block in enumerate(fix_blocks):
  317. block['index'] = sorted_boxes.index(block['bbox'])
  318. # 生成line index
  319. sorted_blocks = sorted(fix_blocks, key=lambda b: b['index'])
  320. line_inedx = 1
  321. for block in sorted_blocks:
  322. for line in block['lines']:
  323. line['index'] = line_inedx
  324. line_inedx += 1
  325. return fix_blocks
  326. def insert_lines_into_block(block_bbox, line_height, page_w, page_h):
  327. # block_bbox是一个元组(x0, y0, x1, y1),其中(x0, y0)是左下角坐标,(x1, y1)是右上角坐标
  328. x0, y0, x1, y1 = block_bbox
  329. block_height = y1 - y0
  330. block_weight = x1 - x0
  331. # 如果block高度小于n行正文,则直接返回block的bbox
  332. if line_height * 3 < block_height:
  333. if (
  334. block_height > page_h * 0.25 and page_w * 0.5 > block_weight > page_w * 0.25
  335. ): # 可能是双列结构,可以切细点
  336. lines = int(block_height / line_height) + 1
  337. else:
  338. # 如果block的宽度超过0.4页面宽度,则将block分成3行(是一种复杂布局,图不能切的太细)
  339. if block_weight > page_w * 0.4:
  340. line_height = (y1 - y0) / 3
  341. lines = 3
  342. elif block_weight > page_w * 0.25: # (可能是三列结构,也切细点)
  343. lines = int(block_height / line_height) + 1
  344. else: # 判断长宽比
  345. if block_height / block_weight > 1.2: # 细长的不分
  346. return [[x0, y0, x1, y1]]
  347. else: # 不细长的还是分成两行
  348. line_height = (y1 - y0) / 2
  349. lines = 2
  350. # 确定从哪个y位置开始绘制线条
  351. current_y = y0
  352. # 用于存储线条的位置信息[(x0, y), ...]
  353. lines_positions = []
  354. for i in range(lines):
  355. lines_positions.append([x0, current_y, x1, current_y + line_height])
  356. current_y += line_height
  357. return lines_positions
  358. else:
  359. return [[x0, y0, x1, y1]]
  360. def sort_lines_by_model(fix_blocks, page_w, page_h, line_height):
  361. page_line_list = []
  362. for block in fix_blocks:
  363. if block['type'] in [
  364. BlockType.Text, BlockType.Title, BlockType.InterlineEquation,
  365. BlockType.ImageCaption, BlockType.ImageFootnote,
  366. BlockType.TableCaption, BlockType.TableFootnote
  367. ]:
  368. if len(block['lines']) == 0:
  369. bbox = block['bbox']
  370. lines = insert_lines_into_block(bbox, line_height, page_w, page_h)
  371. for line in lines:
  372. block['lines'].append({'bbox': line, 'spans': []})
  373. page_line_list.extend(lines)
  374. else:
  375. for line in block['lines']:
  376. bbox = line['bbox']
  377. page_line_list.append(bbox)
  378. elif block['type'] in [BlockType.ImageBody, BlockType.TableBody]:
  379. bbox = block['bbox']
  380. block['real_lines'] = copy.deepcopy(block['lines'])
  381. lines = insert_lines_into_block(bbox, line_height, page_w, page_h)
  382. block['lines'] = []
  383. for line in lines:
  384. block['lines'].append({'bbox': line, 'spans': []})
  385. page_line_list.extend(lines)
  386. if len(page_line_list) > 200: # layoutreader最高支持512line
  387. return None
  388. # 使用layoutreader排序
  389. x_scale = 1000.0 / page_w
  390. y_scale = 1000.0 / page_h
  391. boxes = []
  392. # logger.info(f"Scale: {x_scale}, {y_scale}, Boxes len: {len(page_line_list)}")
  393. for left, top, right, bottom in page_line_list:
  394. if left < 0:
  395. logger.warning(
  396. f'left < 0, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'
  397. ) # noqa: E501
  398. left = 0
  399. if right > page_w:
  400. logger.warning(
  401. f'right > page_w, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'
  402. ) # noqa: E501
  403. right = page_w
  404. if top < 0:
  405. logger.warning(
  406. f'top < 0, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'
  407. ) # noqa: E501
  408. top = 0
  409. if bottom > page_h:
  410. logger.warning(
  411. f'bottom > page_h, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'
  412. ) # noqa: E501
  413. bottom = page_h
  414. left = round(left * x_scale)
  415. top = round(top * y_scale)
  416. right = round(right * x_scale)
  417. bottom = round(bottom * y_scale)
  418. assert (
  419. 1000 >= right >= left >= 0 and 1000 >= bottom >= top >= 0
  420. ), f'Invalid box. right: {right}, left: {left}, bottom: {bottom}, top: {top}' # noqa: E126, E121
  421. boxes.append([left, top, right, bottom])
  422. model_manager = ModelSingleton()
  423. model = model_manager.get_model('layoutreader')
  424. with torch.no_grad():
  425. orders = do_predict(boxes, model)
  426. sorted_bboxes = [page_line_list[i] for i in orders]
  427. return sorted_bboxes
  428. def get_line_height(blocks):
  429. page_line_height_list = []
  430. for block in blocks:
  431. if block['type'] in [
  432. BlockType.Text, BlockType.Title,
  433. BlockType.ImageCaption, BlockType.ImageFootnote,
  434. BlockType.TableCaption, BlockType.TableFootnote
  435. ]:
  436. for line in block['lines']:
  437. bbox = line['bbox']
  438. page_line_height_list.append(int(bbox[3] - bbox[1]))
  439. if len(page_line_height_list) > 0:
  440. return statistics.median(page_line_height_list)
  441. else:
  442. return 10
  443. def process_groups(groups, body_key, caption_key, footnote_key):
  444. body_blocks = []
  445. caption_blocks = []
  446. footnote_blocks = []
  447. for i, group in enumerate(groups):
  448. group[body_key]['group_id'] = i
  449. body_blocks.append(group[body_key])
  450. for caption_block in group[caption_key]:
  451. caption_block['group_id'] = i
  452. caption_blocks.append(caption_block)
  453. for footnote_block in group[footnote_key]:
  454. footnote_block['group_id'] = i
  455. footnote_blocks.append(footnote_block)
  456. return body_blocks, caption_blocks, footnote_blocks
  457. def process_block_list(blocks, body_type, block_type):
  458. indices = [block['index'] for block in blocks]
  459. median_index = statistics.median(indices)
  460. body_bbox = next((block['bbox'] for block in blocks if block.get('type') == body_type), [])
  461. return {
  462. 'type': block_type,
  463. 'bbox': body_bbox,
  464. 'blocks': blocks,
  465. 'index': median_index,
  466. }
  467. def revert_group_blocks(blocks):
  468. image_groups = {}
  469. table_groups = {}
  470. new_blocks = []
  471. for block in blocks:
  472. if block['type'] in [BlockType.ImageBody, BlockType.ImageCaption, BlockType.ImageFootnote]:
  473. group_id = block['group_id']
  474. if group_id not in image_groups:
  475. image_groups[group_id] = []
  476. image_groups[group_id].append(block)
  477. elif block['type'] in [BlockType.TableBody, BlockType.TableCaption, BlockType.TableFootnote]:
  478. group_id = block['group_id']
  479. if group_id not in table_groups:
  480. table_groups[group_id] = []
  481. table_groups[group_id].append(block)
  482. else:
  483. new_blocks.append(block)
  484. for group_id, blocks in image_groups.items():
  485. new_blocks.append(process_block_list(blocks, BlockType.ImageBody, BlockType.Image))
  486. for group_id, blocks in table_groups.items():
  487. new_blocks.append(process_block_list(blocks, BlockType.TableBody, BlockType.Table))
  488. return new_blocks
  489. def remove_outside_spans(spans, all_bboxes, all_discarded_blocks):
  490. def get_block_bboxes(blocks, block_type_list):
  491. return [block[0:4] for block in blocks if block[7] in block_type_list]
  492. image_bboxes = get_block_bboxes(all_bboxes, [BlockType.ImageBody])
  493. table_bboxes = get_block_bboxes(all_bboxes, [BlockType.TableBody])
  494. other_block_type = []
  495. for block_type in BlockType.__dict__.values():
  496. if not isinstance(block_type, str):
  497. continue
  498. if block_type not in [BlockType.ImageBody, BlockType.TableBody]:
  499. other_block_type.append(block_type)
  500. other_block_bboxes = get_block_bboxes(all_bboxes, other_block_type)
  501. discarded_block_bboxes = get_block_bboxes(all_discarded_blocks, [BlockType.Discarded])
  502. new_spans = []
  503. for span in spans:
  504. span_bbox = span['bbox']
  505. span_type = span['type']
  506. if any(calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > 0.4 for block_bbox in
  507. discarded_block_bboxes):
  508. new_spans.append(span)
  509. continue
  510. if span_type == ContentType.Image:
  511. if any(calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > 0.5 for block_bbox in
  512. image_bboxes):
  513. new_spans.append(span)
  514. elif span_type == ContentType.Table:
  515. if any(calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > 0.5 for block_bbox in
  516. table_bboxes):
  517. new_spans.append(span)
  518. else:
  519. if any(calculate_overlap_area_in_bbox1_area_ratio(span_bbox, block_bbox) > 0.5 for block_bbox in
  520. other_block_bboxes):
  521. new_spans.append(span)
  522. return new_spans
  523. def parse_page_core(
  524. page_doc: PageableData, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode, lang
  525. ):
  526. need_drop = False
  527. drop_reason = []
  528. """从magic_model对象中获取后面会用到的区块信息"""
  529. img_groups = magic_model.get_imgs_v2(page_id)
  530. table_groups = magic_model.get_tables_v2(page_id)
  531. """对image和table的区块分组"""
  532. img_body_blocks, img_caption_blocks, img_footnote_blocks = process_groups(
  533. img_groups, 'image_body', 'image_caption_list', 'image_footnote_list'
  534. )
  535. table_body_blocks, table_caption_blocks, table_footnote_blocks = process_groups(
  536. table_groups, 'table_body', 'table_caption_list', 'table_footnote_list'
  537. )
  538. discarded_blocks = magic_model.get_discarded(page_id)
  539. text_blocks = magic_model.get_text_blocks(page_id)
  540. title_blocks = magic_model.get_title_blocks(page_id)
  541. inline_equations, interline_equations, interline_equation_blocks = (
  542. magic_model.get_equations(page_id)
  543. )
  544. page_w, page_h = magic_model.get_page_size(page_id)
  545. """将所有区块的bbox整理到一起"""
  546. # interline_equation_blocks参数不够准,后面切换到interline_equations上
  547. interline_equation_blocks = []
  548. if len(interline_equation_blocks) > 0:
  549. all_bboxes, all_discarded_blocks = ocr_prepare_bboxes_for_layout_split_v2(
  550. img_body_blocks, img_caption_blocks, img_footnote_blocks,
  551. table_body_blocks, table_caption_blocks, table_footnote_blocks,
  552. discarded_blocks,
  553. text_blocks,
  554. title_blocks,
  555. interline_equation_blocks,
  556. page_w,
  557. page_h,
  558. )
  559. else:
  560. all_bboxes, all_discarded_blocks = ocr_prepare_bboxes_for_layout_split_v2(
  561. img_body_blocks, img_caption_blocks, img_footnote_blocks,
  562. table_body_blocks, table_caption_blocks, table_footnote_blocks,
  563. discarded_blocks,
  564. text_blocks,
  565. title_blocks,
  566. interline_equations,
  567. page_w,
  568. page_h,
  569. )
  570. """获取所有的spans信息"""
  571. spans = magic_model.get_all_spans(page_id)
  572. """在删除重复span之前,应该通过image_body和table_body的block过滤一下image和table的span"""
  573. """顺便删除大水印并保留abandon的span"""
  574. spans = remove_outside_spans(spans, all_bboxes, all_discarded_blocks)
  575. """先处理不需要排版的discarded_blocks"""
  576. discarded_block_with_spans, spans = fill_spans_in_blocks(
  577. all_discarded_blocks, spans, 0.4
  578. )
  579. fix_discarded_blocks = fix_discarded_block(discarded_block_with_spans)
  580. """如果当前页面没有有效的bbox则跳过"""
  581. if len(all_bboxes) == 0:
  582. logger.warning(f'skip this page, not found useful bbox, page_id: {page_id}')
  583. return ocr_construct_page_component_v2(
  584. [],
  585. [],
  586. page_id,
  587. page_w,
  588. page_h,
  589. [],
  590. [],
  591. [],
  592. interline_equations,
  593. fix_discarded_blocks,
  594. need_drop,
  595. drop_reason,
  596. )
  597. """删除重叠spans中置信度较低的那些"""
  598. spans, dropped_spans_by_confidence = remove_overlaps_low_confidence_spans(spans)
  599. """删除重叠spans中较小的那些"""
  600. spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)
  601. """根据parse_mode,构造spans,主要是文本类的字符填充"""
  602. if parse_mode == SupportedPdfParseMethod.TXT:
  603. """之前的公式替换方案"""
  604. # pymu_spans = txt_spans_extract_v1(page_doc, inline_equations, interline_equations)
  605. # spans = replace_text_span(pymu_spans, spans)
  606. """ocr 中文本类的 span 用 pymu spans 替换!"""
  607. spans = txt_spans_extract_v2(page_doc, spans, all_bboxes, all_discarded_blocks, lang)
  608. elif parse_mode == SupportedPdfParseMethod.OCR:
  609. pass
  610. else:
  611. raise Exception('parse_mode must be txt or ocr')
  612. """对image和table截图"""
  613. spans = ocr_cut_image_and_table(
  614. spans, page_doc, page_id, pdf_bytes_md5, imageWriter
  615. )
  616. """span填充进block"""
  617. block_with_spans, spans = fill_spans_in_blocks(all_bboxes, spans, 0.5)
  618. """对block进行fix操作"""
  619. fix_blocks = fix_block_spans_v2(block_with_spans)
  620. """获取所有line并计算正文line的高度"""
  621. line_height = get_line_height(fix_blocks)
  622. """获取所有line并对line排序"""
  623. sorted_bboxes = sort_lines_by_model(fix_blocks, page_w, page_h, line_height)
  624. """根据line的中位数算block的序列关系"""
  625. fix_blocks = cal_block_index(fix_blocks, sorted_bboxes)
  626. """将image和table的block还原回group形式参与后续流程"""
  627. fix_blocks = revert_group_blocks(fix_blocks)
  628. """重排block"""
  629. sorted_blocks = sorted(fix_blocks, key=lambda b: b['index'])
  630. """获取QA需要外置的list"""
  631. images, tables, interline_equations = get_qa_need_list_v2(sorted_blocks)
  632. """构造pdf_info_dict"""
  633. page_info = ocr_construct_page_component_v2(
  634. sorted_blocks,
  635. [],
  636. page_id,
  637. page_w,
  638. page_h,
  639. [],
  640. images,
  641. tables,
  642. interline_equations,
  643. fix_discarded_blocks,
  644. need_drop,
  645. drop_reason,
  646. )
  647. return page_info
  648. def pdf_parse_union(
  649. dataset: Dataset,
  650. model_list,
  651. imageWriter,
  652. parse_mode,
  653. start_page_id=0,
  654. end_page_id=None,
  655. debug_mode=False,
  656. lang=None,
  657. ):
  658. pdf_bytes_md5 = compute_md5(dataset.data_bits())
  659. """初始化空的pdf_info_dict"""
  660. pdf_info_dict = {}
  661. """用model_list和docs对象初始化magic_model"""
  662. magic_model = MagicModel(model_list, dataset)
  663. """根据输入的起始范围解析pdf"""
  664. # end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
  665. end_page_id = (
  666. end_page_id
  667. if end_page_id is not None and end_page_id >= 0
  668. else len(dataset) - 1
  669. )
  670. if end_page_id > len(dataset) - 1:
  671. logger.warning('end_page_id is out of range, use pdf_docs length')
  672. end_page_id = len(dataset) - 1
  673. """初始化启动时间"""
  674. start_time = time.time()
  675. for page_id, page in enumerate(dataset):
  676. """debug时输出每页解析的耗时."""
  677. if debug_mode:
  678. time_now = time.time()
  679. logger.info(
  680. f'page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}'
  681. )
  682. start_time = time_now
  683. """解析pdf中的每一页"""
  684. if start_page_id <= page_id <= end_page_id:
  685. page_info = parse_page_core(
  686. page, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode, lang
  687. )
  688. else:
  689. page_info = page.get_page_info()
  690. page_w = page_info.w
  691. page_h = page_info.h
  692. page_info = ocr_construct_page_component_v2(
  693. [], [], page_id, page_w, page_h, [], [], [], [], [], True, 'skip page'
  694. )
  695. pdf_info_dict[f'page_{page_id}'] = page_info
  696. """分段"""
  697. para_split(pdf_info_dict)
  698. """dict转list"""
  699. pdf_info_list = dict_to_list(pdf_info_dict)
  700. new_pdf_info_dict = {
  701. 'pdf_info': pdf_info_list,
  702. }
  703. clean_memory()
  704. return new_pdf_info_dict
  705. if __name__ == '__main__':
  706. pass