pdf_parse_union_core_v2.py 18 KB

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