pdf_parse_union_core_v2.py 35 KB

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