pdf_parse_union_core_v2.py 29 KB

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