pdf_parse_union_core_v2.py 17 KB

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