pdf_parse_union_core_v2.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import os
  2. import statistics
  3. import time
  4. from loguru import logger
  5. from typing import List
  6. import torch
  7. from magic_pdf.libs.clean_memory import clean_memory
  8. from magic_pdf.libs.commons import fitz, get_delta_time
  9. from magic_pdf.libs.config_reader import get_local_layoutreader_model_dir
  10. from magic_pdf.libs.convert_utils import dict_to_list
  11. from magic_pdf.libs.drop_reason import DropReason
  12. from magic_pdf.libs.hash_utils import compute_md5
  13. from magic_pdf.libs.local_math import float_equal
  14. from magic_pdf.libs.ocr_content_type import ContentType
  15. from magic_pdf.model.magic_model import MagicModel
  16. from magic_pdf.para.para_split_v3 import para_split
  17. from magic_pdf.pre_proc.citationmarker_remove import remove_citation_marker
  18. from magic_pdf.pre_proc.construct_page_dict import ocr_construct_page_component_v2
  19. from magic_pdf.pre_proc.cut_image import ocr_cut_image_and_table
  20. from magic_pdf.pre_proc.equations_replace import remove_chars_in_text_blocks, replace_equations_in_textblock, \
  21. combine_chars_to_pymudict
  22. from magic_pdf.pre_proc.ocr_detect_all_bboxes import ocr_prepare_bboxes_for_layout_split_v2
  23. from magic_pdf.pre_proc.ocr_dict_merge import fill_spans_in_blocks, fix_block_spans, fix_discarded_block
  24. from magic_pdf.pre_proc.ocr_span_list_modify import remove_overlaps_min_spans, get_qa_need_list_v2, \
  25. remove_overlaps_low_confidence_spans
  26. from magic_pdf.pre_proc.resolve_bbox_conflict import check_useful_block_horizontal_overlap
  27. def remove_horizontal_overlap_block_which_smaller(all_bboxes):
  28. useful_blocks = []
  29. for bbox in all_bboxes:
  30. useful_blocks.append({
  31. "bbox": bbox[:4]
  32. })
  33. is_useful_block_horz_overlap, smaller_bbox, bigger_bbox = check_useful_block_horizontal_overlap(useful_blocks)
  34. if is_useful_block_horz_overlap:
  35. logger.warning(
  36. f"skip this page, reason: {DropReason.USEFUL_BLOCK_HOR_OVERLAP}, smaller bbox is {smaller_bbox}, bigger bbox is {bigger_bbox}")
  37. for bbox in all_bboxes.copy():
  38. if smaller_bbox == bbox[:4]:
  39. all_bboxes.remove(bbox)
  40. return is_useful_block_horz_overlap, all_bboxes
  41. def __replace_STX_ETX(text_str:str):
  42. """ Replace \u0002 and \u0003, as these characters become garbled when extracted using pymupdf. In fact, they were originally quotation marks.
  43. Drawback: This issue is only observed in English text; it has not been found in Chinese text so far.
  44. Args:
  45. text_str (str): raw text
  46. Returns:
  47. _type_: replaced text
  48. """
  49. if text_str:
  50. s = text_str.replace('\u0002', "'")
  51. s = s.replace("\u0003", "'")
  52. return s
  53. return text_str
  54. def txt_spans_extract(pdf_page, inline_equations, interline_equations):
  55. text_raw_blocks = pdf_page.get_text("dict", flags=fitz.TEXTFLAGS_TEXT)["blocks"]
  56. char_level_text_blocks = pdf_page.get_text("rawdict", flags=fitz.TEXTFLAGS_TEXT)[
  57. "blocks"
  58. ]
  59. text_blocks = combine_chars_to_pymudict(text_raw_blocks, char_level_text_blocks)
  60. text_blocks = replace_equations_in_textblock(
  61. text_blocks, inline_equations, interline_equations
  62. )
  63. text_blocks = remove_citation_marker(text_blocks)
  64. text_blocks = remove_chars_in_text_blocks(text_blocks)
  65. spans = []
  66. for v in text_blocks:
  67. for line in v["lines"]:
  68. for span in line["spans"]:
  69. bbox = span["bbox"]
  70. if float_equal(bbox[0], bbox[2]) or float_equal(bbox[1], bbox[3]):
  71. continue
  72. if span.get('type') not in (ContentType.InlineEquation, ContentType.InterlineEquation):
  73. spans.append(
  74. {
  75. "bbox": list(span["bbox"]),
  76. "content": __replace_STX_ETX(span["text"]),
  77. "type": ContentType.Text,
  78. "score": 1.0,
  79. }
  80. )
  81. return spans
  82. def replace_text_span(pymu_spans, ocr_spans):
  83. return list(filter(lambda x: x["type"] != ContentType.Text, ocr_spans)) + pymu_spans
  84. def model_init(model_name: str):
  85. from transformers import LayoutLMv3ForTokenClassification
  86. if torch.cuda.is_available():
  87. device = torch.device("cuda")
  88. if torch.cuda.is_bf16_supported():
  89. supports_bfloat16 = True
  90. else:
  91. supports_bfloat16 = False
  92. else:
  93. device = torch.device("cpu")
  94. supports_bfloat16 = False
  95. if model_name == "layoutreader":
  96. # 检测modelscope的缓存目录是否存在
  97. layoutreader_model_dir = get_local_layoutreader_model_dir()
  98. if os.path.exists(layoutreader_model_dir):
  99. model = LayoutLMv3ForTokenClassification.from_pretrained(layoutreader_model_dir)
  100. else:
  101. logger.warning(
  102. f"local layoutreader model not exists, use online model from huggingface")
  103. model = LayoutLMv3ForTokenClassification.from_pretrained("hantian/layoutreader")
  104. # 检查设备是否支持 bfloat16
  105. if supports_bfloat16:
  106. model.bfloat16()
  107. model.to(device).eval()
  108. else:
  109. logger.error("model name not allow")
  110. exit(1)
  111. return model
  112. class ModelSingleton:
  113. _instance = None
  114. _models = {}
  115. def __new__(cls, *args, **kwargs):
  116. if cls._instance is None:
  117. cls._instance = super().__new__(cls)
  118. return cls._instance
  119. def get_model(self, model_name: str):
  120. if model_name not in self._models:
  121. self._models[model_name] = model_init(model_name=model_name)
  122. return self._models[model_name]
  123. def do_predict(boxes: List[List[int]], model) -> List[int]:
  124. from magic_pdf.model.v3.helpers import prepare_inputs, boxes2inputs, parse_logits
  125. inputs = boxes2inputs(boxes)
  126. inputs = prepare_inputs(inputs, model)
  127. logits = model(**inputs).logits.cpu().squeeze(0)
  128. return parse_logits(logits, len(boxes))
  129. def cal_block_index(fix_blocks, sorted_bboxes):
  130. for block in fix_blocks:
  131. # if block['type'] in ['text', 'title', 'interline_equation']:
  132. # line_index_list = []
  133. # if len(block['lines']) == 0:
  134. # block['index'] = sorted_bboxes.index(block['bbox'])
  135. # else:
  136. # for line in block['lines']:
  137. # line['index'] = sorted_bboxes.index(line['bbox'])
  138. # line_index_list.append(line['index'])
  139. # median_value = statistics.median(line_index_list)
  140. # block['index'] = median_value
  141. #
  142. # elif block['type'] in ['table', 'image']:
  143. # block['index'] = sorted_bboxes.index(block['bbox'])
  144. line_index_list = []
  145. if len(block['lines']) == 0:
  146. block['index'] = sorted_bboxes.index(block['bbox'])
  147. else:
  148. for line in block['lines']:
  149. line['index'] = sorted_bboxes.index(line['bbox'])
  150. line_index_list.append(line['index'])
  151. median_value = statistics.median(line_index_list)
  152. block['index'] = median_value
  153. # 删除图表block中的虚拟line信息
  154. if block['type'] in ['table', 'image']:
  155. del block['lines']
  156. return fix_blocks
  157. def insert_lines_into_block(block_bbox, line_height, page_w, page_h):
  158. # block_bbox是一个元组(x0, y0, x1, y1),其中(x0, y0)是左下角坐标,(x1, y1)是右上角坐标
  159. x0, y0, x1, y1 = block_bbox
  160. block_height = y1 - y0
  161. block_weight = x1 - x0
  162. # 如果block高度小于n行正文,则直接返回block的bbox
  163. if line_height*3 < block_height:
  164. if block_height > page_h*0.25 and page_w*0.5 > block_weight > page_w*0.25: # 可能是双列结构,可以切细点
  165. lines = int(block_height/line_height)+1
  166. else:
  167. # 如果block的宽度超过0.4页面宽度,则将block分成3行
  168. if block_weight > page_w*0.4:
  169. line_height = (y1 - y0) / 3
  170. lines = 3
  171. elif block_weight > page_w*0.25: # 否则将block分成两行
  172. line_height = (y1 - y0) / 2
  173. lines = 2
  174. else: # 判断长宽比
  175. if block_height/block_weight > 1.2: # 细长的不分
  176. return [[x0, y0, x1, y1]]
  177. else: # 不细长的还是分成两行
  178. line_height = (y1 - y0) / 2
  179. lines = 2
  180. # 确定从哪个y位置开始绘制线条
  181. current_y = y0
  182. # 用于存储线条的位置信息[(x0, y), ...]
  183. lines_positions = []
  184. for i in range(lines):
  185. lines_positions.append([x0, current_y, x1, current_y + line_height])
  186. current_y += line_height
  187. return lines_positions
  188. else:
  189. return [[x0, y0, x1, y1]]
  190. def sort_lines_by_model(fix_blocks, page_w, page_h, line_height):
  191. page_line_list = []
  192. for block in fix_blocks:
  193. if block['type'] in ['text', 'title', 'interline_equation']:
  194. if len(block['lines']) == 0:
  195. bbox = block['bbox']
  196. lines = insert_lines_into_block(bbox, line_height, page_w, page_h)
  197. for line in lines:
  198. block['lines'].append({'bbox': line, 'spans': []})
  199. page_line_list.extend(lines)
  200. else:
  201. for line in block['lines']:
  202. bbox = line['bbox']
  203. page_line_list.append(bbox)
  204. elif block['type'] in ['table', 'image']:
  205. bbox = block['bbox']
  206. lines = insert_lines_into_block(bbox, line_height, page_w, page_h)
  207. block['lines'] = []
  208. for line in lines:
  209. block['lines'].append({'bbox': line, 'spans': []})
  210. page_line_list.extend(lines)
  211. # 使用layoutreader排序
  212. x_scale = 1000.0 / page_w
  213. y_scale = 1000.0 / page_h
  214. boxes = []
  215. # logger.info(f"Scale: {x_scale}, {y_scale}, Boxes len: {len(page_line_list)}")
  216. for left, top, right, bottom in page_line_list:
  217. if left < 0:
  218. logger.warning(
  219. f"left < 0, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}")
  220. left = 0
  221. if right > page_w:
  222. logger.warning(
  223. f"right > page_w, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}")
  224. right = page_w
  225. if top < 0:
  226. logger.warning(
  227. f"top < 0, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}")
  228. top = 0
  229. if bottom > page_h:
  230. logger.warning(
  231. f"bottom > page_h, left: {left}, right: {right}, top: {top}, bottom: {bottom}, page_w: {page_w}, page_h: {page_h}")
  232. bottom = page_h
  233. left = round(left * x_scale)
  234. top = round(top * y_scale)
  235. right = round(right * x_scale)
  236. bottom = round(bottom * y_scale)
  237. assert (
  238. 1000 >= right >= left >= 0 and 1000 >= bottom >= top >= 0
  239. ), f"Invalid box. right: {right}, left: {left}, bottom: {bottom}, top: {top}"
  240. boxes.append([left, top, right, bottom])
  241. model_manager = ModelSingleton()
  242. model = model_manager.get_model("layoutreader")
  243. with torch.no_grad():
  244. orders = do_predict(boxes, model)
  245. sorted_bboxes = [page_line_list[i] for i in orders]
  246. return sorted_bboxes
  247. def get_line_height(blocks):
  248. page_line_height_list = []
  249. for block in blocks:
  250. if block['type'] in ['text', 'title', 'interline_equation']:
  251. for line in block['lines']:
  252. bbox = line['bbox']
  253. page_line_height_list.append(int(bbox[3]-bbox[1]))
  254. if len(page_line_height_list) > 0:
  255. return statistics.median(page_line_height_list)
  256. else:
  257. return 10
  258. def parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode):
  259. need_drop = False
  260. drop_reason = []
  261. '''从magic_model对象中获取后面会用到的区块信息'''
  262. img_blocks = magic_model.get_imgs(page_id)
  263. table_blocks = magic_model.get_tables(page_id)
  264. discarded_blocks = magic_model.get_discarded(page_id)
  265. text_blocks = magic_model.get_text_blocks(page_id)
  266. title_blocks = magic_model.get_title_blocks(page_id)
  267. inline_equations, interline_equations, interline_equation_blocks = magic_model.get_equations(page_id)
  268. page_w, page_h = magic_model.get_page_size(page_id)
  269. spans = magic_model.get_all_spans(page_id)
  270. '''根据parse_mode,构造spans'''
  271. if parse_mode == "txt":
  272. """ocr 中文本类的 span 用 pymu spans 替换!"""
  273. pymu_spans = txt_spans_extract(
  274. pdf_docs[page_id], inline_equations, interline_equations
  275. )
  276. spans = replace_text_span(pymu_spans, spans)
  277. elif parse_mode == "ocr":
  278. pass
  279. else:
  280. raise Exception("parse_mode must be txt or ocr")
  281. '''删除重叠spans中置信度较低的那些'''
  282. spans, dropped_spans_by_confidence = remove_overlaps_low_confidence_spans(spans)
  283. '''删除重叠spans中较小的那些'''
  284. spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)
  285. '''对image和table截图'''
  286. spans = ocr_cut_image_and_table(spans, pdf_docs[page_id], page_id, pdf_bytes_md5, imageWriter)
  287. '''将所有区块的bbox整理到一起'''
  288. # interline_equation_blocks参数不够准,后面切换到interline_equations上
  289. interline_equation_blocks = []
  290. if len(interline_equation_blocks) > 0:
  291. all_bboxes, all_discarded_blocks = ocr_prepare_bboxes_for_layout_split_v2(
  292. img_blocks, table_blocks, discarded_blocks, text_blocks, title_blocks,
  293. interline_equation_blocks, page_w, page_h)
  294. else:
  295. all_bboxes, all_discarded_blocks = ocr_prepare_bboxes_for_layout_split_v2(
  296. img_blocks, table_blocks, discarded_blocks, text_blocks, title_blocks,
  297. interline_equations, page_w, page_h)
  298. '''先处理不需要排版的discarded_blocks'''
  299. discarded_block_with_spans, spans = fill_spans_in_blocks(all_discarded_blocks, spans, 0.4)
  300. fix_discarded_blocks = fix_discarded_block(discarded_block_with_spans)
  301. '''如果当前页面没有bbox则跳过'''
  302. if len(all_bboxes) == 0:
  303. logger.warning(f"skip this page, not found useful bbox, page_id: {page_id}")
  304. return ocr_construct_page_component_v2([], [], page_id, page_w, page_h, [],
  305. [], [], interline_equations, fix_discarded_blocks,
  306. need_drop, drop_reason)
  307. '''将span填入blocks中'''
  308. block_with_spans, spans = fill_spans_in_blocks(all_bboxes, spans, 0.5)
  309. '''对block进行fix操作'''
  310. fix_blocks = fix_block_spans(block_with_spans, img_blocks, table_blocks)
  311. '''获取所有line并计算正文line的高度'''
  312. line_height = get_line_height(fix_blocks)
  313. '''获取所有line并对line排序'''
  314. sorted_bboxes = sort_lines_by_model(fix_blocks, page_w, page_h, line_height)
  315. '''根据line的中位数算block的序列关系'''
  316. fix_blocks = cal_block_index(fix_blocks, sorted_bboxes)
  317. '''重排block'''
  318. sorted_blocks = sorted(fix_blocks, key=lambda b: b['index'])
  319. '''获取QA需要外置的list'''
  320. images, tables, interline_equations = get_qa_need_list_v2(sorted_blocks)
  321. '''构造pdf_info_dict'''
  322. page_info = ocr_construct_page_component_v2(sorted_blocks, [], page_id, page_w, page_h, [],
  323. images, tables, interline_equations, fix_discarded_blocks,
  324. need_drop, drop_reason)
  325. return page_info
  326. def pdf_parse_union(pdf_bytes,
  327. model_list,
  328. imageWriter,
  329. parse_mode,
  330. start_page_id=0,
  331. end_page_id=None,
  332. debug_mode=False,
  333. ):
  334. pdf_bytes_md5 = compute_md5(pdf_bytes)
  335. pdf_docs = fitz.open("pdf", pdf_bytes)
  336. '''初始化空的pdf_info_dict'''
  337. pdf_info_dict = {}
  338. '''用model_list和docs对象初始化magic_model'''
  339. magic_model = MagicModel(model_list, pdf_docs)
  340. '''根据输入的起始范围解析pdf'''
  341. # end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
  342. end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else len(pdf_docs) - 1
  343. if end_page_id > len(pdf_docs) - 1:
  344. logger.warning("end_page_id is out of range, use pdf_docs length")
  345. end_page_id = len(pdf_docs) - 1
  346. '''初始化启动时间'''
  347. start_time = time.time()
  348. for page_id, page in enumerate(pdf_docs):
  349. '''debug时输出每页解析的耗时'''
  350. if debug_mode:
  351. time_now = time.time()
  352. logger.info(
  353. f"page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}"
  354. )
  355. start_time = time_now
  356. '''解析pdf中的每一页'''
  357. if start_page_id <= page_id <= end_page_id:
  358. page_info = parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode)
  359. else:
  360. page_w = page.rect.width
  361. page_h = page.rect.height
  362. page_info = ocr_construct_page_component_v2([], [], page_id, page_w, page_h, [],
  363. [], [], [], [],
  364. True, "skip page")
  365. pdf_info_dict[f"page_{page_id}"] = page_info
  366. """分段"""
  367. para_split(pdf_info_dict, debug_mode=debug_mode)
  368. """dict转list"""
  369. pdf_info_list = dict_to_list(pdf_info_dict)
  370. new_pdf_info_dict = {
  371. "pdf_info": pdf_info_list,
  372. }
  373. clean_memory()
  374. return new_pdf_info_dict
  375. if __name__ == '__main__':
  376. pass