pdf_parse_union_core_v2.py 38 KB

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