pdf_parse_union_core_v2.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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.enums import SupportedPdfParseMethod
  9. from magic_pdf.data.dataset import Dataset, PageableData
  10. from magic_pdf.libs.clean_memory import clean_memory
  11. from magic_pdf.libs.commons import fitz, get_delta_time
  12. from magic_pdf.libs.config_reader import get_local_layoutreader_model_dir
  13. from magic_pdf.libs.convert_utils import dict_to_list
  14. from magic_pdf.libs.drop_reason import DropReason
  15. from magic_pdf.libs.hash_utils import compute_md5
  16. from magic_pdf.libs.local_math import float_equal
  17. from magic_pdf.libs.ocr_content_type import ContentType, BlockType
  18. from magic_pdf.model.magic_model import MagicModel
  19. from magic_pdf.para.para_split_v3 import para_split
  20. from magic_pdf.pre_proc.citationmarker_remove import remove_citation_marker
  21. from magic_pdf.pre_proc.construct_page_dict import \
  22. ocr_construct_page_component_v2
  23. from magic_pdf.pre_proc.cut_image import ocr_cut_image_and_table
  24. from magic_pdf.pre_proc.equations_replace import (
  25. combine_chars_to_pymudict, remove_chars_in_text_blocks,
  26. replace_equations_in_textblock)
  27. from magic_pdf.pre_proc.ocr_detect_all_bboxes import \
  28. ocr_prepare_bboxes_for_layout_split_v2
  29. from magic_pdf.pre_proc.ocr_dict_merge import (fill_spans_in_blocks,
  30. fix_block_spans,
  31. fix_discarded_block, fix_block_spans_v2)
  32. from magic_pdf.pre_proc.ocr_span_list_modify import (
  33. get_qa_need_list_v2, remove_overlaps_low_confidence_spans,
  34. remove_overlaps_min_spans)
  35. from magic_pdf.pre_proc.resolve_bbox_conflict import \
  36. check_useful_block_horizontal_overlap
  37. def remove_horizontal_overlap_block_which_smaller(all_bboxes):
  38. useful_blocks = []
  39. for bbox in all_bboxes:
  40. useful_blocks.append({'bbox': bbox[:4]})
  41. is_useful_block_horz_overlap, smaller_bbox, bigger_bbox = (
  42. check_useful_block_horizontal_overlap(useful_blocks)
  43. )
  44. if is_useful_block_horz_overlap:
  45. logger.warning(
  46. f'skip this page, reason: {DropReason.USEFUL_BLOCK_HOR_OVERLAP}, smaller bbox is {smaller_bbox}, bigger bbox is {bigger_bbox}'
  47. ) # noqa: E501
  48. for bbox in all_bboxes.copy():
  49. if smaller_bbox == bbox[:4]:
  50. all_bboxes.remove(bbox)
  51. return is_useful_block_horz_overlap, all_bboxes
  52. def __replace_STX_ETX(text_str: str):
  53. """Replace \u0002 and \u0003, as these characters become garbled when extracted using pymupdf. In fact, they were originally quotation marks.
  54. Drawback: This issue is only observed in English text; it has not been found in Chinese text so far.
  55. Args:
  56. text_str (str): raw text
  57. Returns:
  58. _type_: replaced text
  59. """ # noqa: E501
  60. if text_str:
  61. s = text_str.replace('\u0002', "'")
  62. s = s.replace('\u0003', "'")
  63. return s
  64. return text_str
  65. def txt_spans_extract(pdf_page, inline_equations, interline_equations):
  66. text_raw_blocks = pdf_page.get_text('dict', flags=fitz.TEXTFLAGS_TEXT)['blocks']
  67. char_level_text_blocks = pdf_page.get_text('rawdict', flags=fitz.TEXTFLAGS_TEXT)[
  68. 'blocks'
  69. ]
  70. text_blocks = combine_chars_to_pymudict(text_raw_blocks, char_level_text_blocks)
  71. text_blocks = replace_equations_in_textblock(
  72. text_blocks, inline_equations, interline_equations
  73. )
  74. text_blocks = remove_citation_marker(text_blocks)
  75. text_blocks = remove_chars_in_text_blocks(text_blocks)
  76. spans = []
  77. for v in text_blocks:
  78. for line in v['lines']:
  79. for span in line['spans']:
  80. bbox = span['bbox']
  81. if float_equal(bbox[0], bbox[2]) or float_equal(bbox[1], bbox[3]):
  82. continue
  83. if span.get('type') not in (
  84. ContentType.InlineEquation,
  85. ContentType.InterlineEquation,
  86. ):
  87. spans.append(
  88. {
  89. 'bbox': list(span['bbox']),
  90. 'content': __replace_STX_ETX(span['text']),
  91. 'type': ContentType.Text,
  92. 'score': 1.0,
  93. }
  94. )
  95. return spans
  96. def replace_text_span(pymu_spans, ocr_spans):
  97. return list(filter(lambda x: x['type'] != ContentType.Text, ocr_spans)) + pymu_spans
  98. def model_init(model_name: str):
  99. from transformers import LayoutLMv3ForTokenClassification
  100. if torch.cuda.is_available():
  101. device = torch.device('cuda')
  102. if torch.cuda.is_bf16_supported():
  103. supports_bfloat16 = True
  104. else:
  105. supports_bfloat16 = False
  106. else:
  107. device = torch.device('cpu')
  108. supports_bfloat16 = False
  109. if model_name == 'layoutreader':
  110. # 检测modelscope的缓存目录是否存在
  111. layoutreader_model_dir = get_local_layoutreader_model_dir()
  112. if os.path.exists(layoutreader_model_dir):
  113. model = LayoutLMv3ForTokenClassification.from_pretrained(
  114. layoutreader_model_dir
  115. )
  116. else:
  117. logger.warning(
  118. 'local layoutreader model not exists, use online model from huggingface'
  119. )
  120. model = LayoutLMv3ForTokenClassification.from_pretrained(
  121. 'hantian/layoutreader'
  122. )
  123. # 检查设备是否支持 bfloat16
  124. if supports_bfloat16:
  125. model.bfloat16()
  126. model.to(device).eval()
  127. else:
  128. logger.error('model name not allow')
  129. exit(1)
  130. return model
  131. class ModelSingleton:
  132. _instance = None
  133. _models = {}
  134. def __new__(cls, *args, **kwargs):
  135. if cls._instance is None:
  136. cls._instance = super().__new__(cls)
  137. return cls._instance
  138. def get_model(self, model_name: str):
  139. if model_name not in self._models:
  140. self._models[model_name] = model_init(model_name=model_name)
  141. return self._models[model_name]
  142. def do_predict(boxes: List[List[int]], model) -> List[int]:
  143. from magic_pdf.model.v3.helpers import (boxes2inputs, parse_logits,
  144. prepare_inputs)
  145. inputs = boxes2inputs(boxes)
  146. inputs = prepare_inputs(inputs, model)
  147. logits = model(**inputs).logits.cpu().squeeze(0)
  148. return parse_logits(logits, len(boxes))
  149. def cal_block_index(fix_blocks, sorted_bboxes):
  150. for block in fix_blocks:
  151. line_index_list = []
  152. if len(block['lines']) == 0:
  153. block['index'] = sorted_bboxes.index(block['bbox'])
  154. else:
  155. for line in block['lines']:
  156. line['index'] = sorted_bboxes.index(line['bbox'])
  157. line_index_list.append(line['index'])
  158. median_value = statistics.median(line_index_list)
  159. block['index'] = median_value
  160. # 删除图表body block中的虚拟line信息, 并用real_lines信息回填
  161. if block['type'] in [BlockType.ImageBody, BlockType.TableBody]:
  162. block['virtual_lines'] = copy.deepcopy(block['lines'])
  163. block['lines'] = copy.deepcopy(block['real_lines'])
  164. del block['real_lines']
  165. return fix_blocks
  166. def insert_lines_into_block(block_bbox, line_height, page_w, page_h):
  167. # block_bbox是一个元组(x0, y0, x1, y1),其中(x0, y0)是左下角坐标,(x1, y1)是右上角坐标
  168. x0, y0, x1, y1 = block_bbox
  169. block_height = y1 - y0
  170. block_weight = x1 - x0
  171. # 如果block高度小于n行正文,则直接返回block的bbox
  172. if line_height * 3 < block_height:
  173. if (
  174. block_height > page_h * 0.25 and page_w * 0.5 > block_weight > page_w * 0.25
  175. ): # 可能是双列结构,可以切细点
  176. lines = int(block_height / line_height) + 1
  177. else:
  178. # 如果block的宽度超过0.4页面宽度,则将block分成3行(是一种复杂布局,图不能切的太细)
  179. if block_weight > page_w * 0.4:
  180. line_height = (y1 - y0) / 3
  181. lines = 3
  182. elif block_weight > page_w * 0.25: # (可能是三列结构,也切细点)
  183. lines = int(block_height / line_height) + 1
  184. else: # 判断长宽比
  185. if block_height / block_weight > 1.2: # 细长的不分
  186. return [[x0, y0, x1, y1]]
  187. else: # 不细长的还是分成两行
  188. line_height = (y1 - y0) / 2
  189. lines = 2
  190. # 确定从哪个y位置开始绘制线条
  191. current_y = y0
  192. # 用于存储线条的位置信息[(x0, y), ...]
  193. lines_positions = []
  194. for i in range(lines):
  195. lines_positions.append([x0, current_y, x1, current_y + line_height])
  196. current_y += line_height
  197. return lines_positions
  198. else:
  199. return [[x0, y0, x1, y1]]
  200. def sort_lines_by_model(fix_blocks, page_w, page_h, line_height):
  201. page_line_list = []
  202. for block in fix_blocks:
  203. if block['type'] in [
  204. BlockType.Text, BlockType.Title, BlockType.InterlineEquation,
  205. BlockType.ImageCaption, BlockType.ImageFootnote,
  206. BlockType.TableCaption, BlockType.TableFootnote
  207. ]:
  208. if len(block['lines']) == 0:
  209. bbox = block['bbox']
  210. lines = insert_lines_into_block(bbox, line_height, page_w, page_h)
  211. for line in lines:
  212. block['lines'].append({'bbox': line, 'spans': []})
  213. page_line_list.extend(lines)
  214. else:
  215. for line in block['lines']:
  216. bbox = line['bbox']
  217. page_line_list.append(bbox)
  218. elif block['type'] in [BlockType.ImageBody, BlockType.TableBody]:
  219. bbox = block['bbox']
  220. block["real_lines"] = copy.deepcopy(block['lines'])
  221. lines = insert_lines_into_block(bbox, line_height, page_w, page_h)
  222. block['lines'] = []
  223. for line in lines:
  224. block['lines'].append({'bbox': line, 'spans': []})
  225. page_line_list.extend(lines)
  226. # 使用layoutreader排序
  227. x_scale = 1000.0 / page_w
  228. y_scale = 1000.0 / page_h
  229. boxes = []
  230. # logger.info(f"Scale: {x_scale}, {y_scale}, Boxes len: {len(page_line_list)}")
  231. for left, top, right, bottom in page_line_list:
  232. if left < 0:
  233. logger.warning(
  234. f'left < 0, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'
  235. ) # noqa: E501
  236. left = 0
  237. if right > page_w:
  238. logger.warning(
  239. f'right > page_w, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'
  240. ) # noqa: E501
  241. right = page_w
  242. if top < 0:
  243. logger.warning(
  244. f'top < 0, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'
  245. ) # noqa: E501
  246. top = 0
  247. if bottom > page_h:
  248. logger.warning(
  249. f'bottom > page_h, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}'
  250. ) # noqa: E501
  251. bottom = page_h
  252. left = round(left * x_scale)
  253. top = round(top * y_scale)
  254. right = round(right * x_scale)
  255. bottom = round(bottom * y_scale)
  256. assert (
  257. 1000 >= right >= left >= 0 and 1000 >= bottom >= top >= 0
  258. ), f'Invalid box. right: {right}, left: {left}, bottom: {bottom}, top: {top}' # noqa: E126, E121
  259. boxes.append([left, top, right, bottom])
  260. model_manager = ModelSingleton()
  261. model = model_manager.get_model('layoutreader')
  262. with torch.no_grad():
  263. orders = do_predict(boxes, model)
  264. sorted_bboxes = [page_line_list[i] for i in orders]
  265. return sorted_bboxes
  266. def get_line_height(blocks):
  267. page_line_height_list = []
  268. for block in blocks:
  269. if block['type'] in [
  270. BlockType.Text, BlockType.Title,
  271. BlockType.ImageCaption, BlockType.ImageFootnote,
  272. BlockType.TableCaption, BlockType.TableFootnote
  273. ]:
  274. for line in block['lines']:
  275. bbox = line['bbox']
  276. page_line_height_list.append(int(bbox[3] - bbox[1]))
  277. if len(page_line_height_list) > 0:
  278. return statistics.median(page_line_height_list)
  279. else:
  280. return 10
  281. def process_groups(groups, body_key, caption_key, footnote_key):
  282. body_blocks = []
  283. caption_blocks = []
  284. footnote_blocks = []
  285. for i, group in enumerate(groups):
  286. group[body_key]['group_id'] = i
  287. body_blocks.append(group[body_key])
  288. for caption_block in group[caption_key]:
  289. caption_block['group_id'] = i
  290. caption_blocks.append(caption_block)
  291. for footnote_block in group[footnote_key]:
  292. footnote_block['group_id'] = i
  293. footnote_blocks.append(footnote_block)
  294. return body_blocks, caption_blocks, footnote_blocks
  295. def process_block_list(blocks, body_type, block_type):
  296. indices = [block['index'] for block in blocks]
  297. median_index = statistics.median(indices)
  298. body_bbox = next((block['bbox'] for block in blocks if block.get('type') == body_type), [])
  299. return {
  300. 'type': block_type,
  301. 'bbox': body_bbox,
  302. 'blocks': blocks,
  303. 'index': median_index,
  304. }
  305. def revert_group_blocks(blocks):
  306. image_groups = {}
  307. table_groups = {}
  308. new_blocks = []
  309. for block in blocks:
  310. if block['type'] in [BlockType.ImageBody, BlockType.ImageCaption, BlockType.ImageFootnote]:
  311. group_id = block['group_id']
  312. if group_id not in image_groups:
  313. image_groups[group_id] = []
  314. image_groups[group_id].append(block)
  315. elif block['type'] in [BlockType.TableBody, BlockType.TableCaption, BlockType.TableFootnote]:
  316. group_id = block['group_id']
  317. if group_id not in table_groups:
  318. table_groups[group_id] = []
  319. table_groups[group_id].append(block)
  320. else:
  321. new_blocks.append(block)
  322. for group_id, blocks in image_groups.items():
  323. new_blocks.append(process_block_list(blocks, BlockType.ImageBody, BlockType.Image))
  324. for group_id, blocks in table_groups.items():
  325. new_blocks.append(process_block_list(blocks, BlockType.TableBody, BlockType.Table))
  326. return new_blocks
  327. def parse_page_core(
  328. page_doc: PageableData, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode
  329. ):
  330. need_drop = False
  331. drop_reason = []
  332. """从magic_model对象中获取后面会用到的区块信息"""
  333. # img_blocks = magic_model.get_imgs(page_id)
  334. # table_blocks = magic_model.get_tables(page_id)
  335. img_groups = magic_model.get_imgs_v2(page_id)
  336. table_groups = magic_model.get_tables_v2(page_id)
  337. img_body_blocks, img_caption_blocks, img_footnote_blocks = process_groups(
  338. img_groups, 'image_body', 'image_caption_list', 'image_footnote_list'
  339. )
  340. table_body_blocks, table_caption_blocks, table_footnote_blocks = process_groups(
  341. table_groups, 'table_body', 'table_caption_list', 'table_footnote_list'
  342. )
  343. discarded_blocks = magic_model.get_discarded(page_id)
  344. text_blocks = magic_model.get_text_blocks(page_id)
  345. title_blocks = magic_model.get_title_blocks(page_id)
  346. inline_equations, interline_equations, interline_equation_blocks = (
  347. magic_model.get_equations(page_id)
  348. )
  349. page_w, page_h = magic_model.get_page_size(page_id)
  350. spans = magic_model.get_all_spans(page_id)
  351. """根据parse_mode,构造spans"""
  352. if parse_mode == SupportedPdfParseMethod.TXT:
  353. """ocr 中文本类的 span 用 pymu spans 替换!"""
  354. pymu_spans = txt_spans_extract(page_doc, inline_equations, interline_equations)
  355. spans = replace_text_span(pymu_spans, spans)
  356. elif parse_mode == SupportedPdfParseMethod.OCR:
  357. pass
  358. else:
  359. raise Exception('parse_mode must be txt or ocr')
  360. """删除重叠spans中置信度较低的那些"""
  361. spans, dropped_spans_by_confidence = remove_overlaps_low_confidence_spans(spans)
  362. """删除重叠spans中较小的那些"""
  363. spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)
  364. """对image和table截图"""
  365. spans = ocr_cut_image_and_table(
  366. spans, page_doc, page_id, pdf_bytes_md5, imageWriter
  367. )
  368. """将所有区块的bbox整理到一起"""
  369. # interline_equation_blocks参数不够准,后面切换到interline_equations上
  370. interline_equation_blocks = []
  371. if len(interline_equation_blocks) > 0:
  372. all_bboxes, all_discarded_blocks = ocr_prepare_bboxes_for_layout_split_v2(
  373. img_body_blocks, img_caption_blocks, img_footnote_blocks,
  374. table_body_blocks, table_caption_blocks, table_footnote_blocks,
  375. discarded_blocks,
  376. text_blocks,
  377. title_blocks,
  378. interline_equation_blocks,
  379. page_w,
  380. page_h,
  381. )
  382. else:
  383. all_bboxes, all_discarded_blocks = ocr_prepare_bboxes_for_layout_split_v2(
  384. img_body_blocks, img_caption_blocks, img_footnote_blocks,
  385. table_body_blocks, table_caption_blocks, table_footnote_blocks,
  386. discarded_blocks,
  387. text_blocks,
  388. title_blocks,
  389. interline_equations,
  390. page_w,
  391. page_h,
  392. )
  393. """先处理不需要排版的discarded_blocks"""
  394. discarded_block_with_spans, spans = fill_spans_in_blocks(
  395. all_discarded_blocks, spans, 0.4
  396. )
  397. fix_discarded_blocks = fix_discarded_block(discarded_block_with_spans)
  398. """如果当前页面没有bbox则跳过"""
  399. if len(all_bboxes) == 0:
  400. logger.warning(f'skip this page, not found useful bbox, page_id: {page_id}')
  401. return ocr_construct_page_component_v2(
  402. [],
  403. [],
  404. page_id,
  405. page_w,
  406. page_h,
  407. [],
  408. [],
  409. [],
  410. interline_equations,
  411. fix_discarded_blocks,
  412. need_drop,
  413. drop_reason,
  414. )
  415. """将span填入blocks中"""
  416. block_with_spans, spans = fill_spans_in_blocks(all_bboxes, spans, 0.5)
  417. """对block进行fix操作"""
  418. fix_blocks = fix_block_spans_v2(block_with_spans)
  419. """获取所有line并计算正文line的高度"""
  420. line_height = get_line_height(fix_blocks)
  421. """获取所有line并对line排序"""
  422. sorted_bboxes = sort_lines_by_model(fix_blocks, page_w, page_h, line_height)
  423. """根据line的中位数算block的序列关系"""
  424. fix_blocks = cal_block_index(fix_blocks, sorted_bboxes)
  425. """将image和table的block还原回group形式参与后续流程"""
  426. fix_blocks = revert_group_blocks(fix_blocks)
  427. """重排block"""
  428. sorted_blocks = sorted(fix_blocks, key=lambda b: b['index'])
  429. """获取QA需要外置的list"""
  430. images, tables, interline_equations = get_qa_need_list_v2(sorted_blocks)
  431. """构造pdf_info_dict"""
  432. page_info = ocr_construct_page_component_v2(
  433. sorted_blocks,
  434. [],
  435. page_id,
  436. page_w,
  437. page_h,
  438. [],
  439. images,
  440. tables,
  441. interline_equations,
  442. fix_discarded_blocks,
  443. need_drop,
  444. drop_reason,
  445. )
  446. return page_info
  447. def pdf_parse_union(
  448. dataset: Dataset,
  449. model_list,
  450. imageWriter,
  451. parse_mode,
  452. start_page_id=0,
  453. end_page_id=None,
  454. debug_mode=False,
  455. ):
  456. pdf_bytes_md5 = compute_md5(dataset.data_bits())
  457. """初始化空的pdf_info_dict"""
  458. pdf_info_dict = {}
  459. """用model_list和docs对象初始化magic_model"""
  460. magic_model = MagicModel(model_list, dataset)
  461. """根据输入的起始范围解析pdf"""
  462. # end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
  463. end_page_id = (
  464. end_page_id
  465. if end_page_id is not None and end_page_id >= 0
  466. else len(dataset) - 1
  467. )
  468. if end_page_id > len(dataset) - 1:
  469. logger.warning('end_page_id is out of range, use pdf_docs length')
  470. end_page_id = len(dataset) - 1
  471. """初始化启动时间"""
  472. start_time = time.time()
  473. for page_id, page in enumerate(dataset):
  474. """debug时输出每页解析的耗时."""
  475. if debug_mode:
  476. time_now = time.time()
  477. logger.info(
  478. f'page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}'
  479. )
  480. start_time = time_now
  481. """解析pdf中的每一页"""
  482. if start_page_id <= page_id <= end_page_id:
  483. page_info = parse_page_core(
  484. page, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode
  485. )
  486. else:
  487. page_info = page.get_page_info()
  488. page_w = page_info.w
  489. page_h = page_info.h
  490. page_info = ocr_construct_page_component_v2(
  491. [], [], page_id, page_w, page_h, [], [], [], [], [], True, 'skip page'
  492. )
  493. pdf_info_dict[f'page_{page_id}'] = page_info
  494. """分段"""
  495. para_split(pdf_info_dict, debug_mode=debug_mode)
  496. """dict转list"""
  497. pdf_info_list = dict_to_list(pdf_info_dict)
  498. new_pdf_info_dict = {
  499. 'pdf_info': pdf_info_list,
  500. }
  501. clean_memory()
  502. return new_pdf_info_dict
  503. if __name__ == '__main__':
  504. pass