pdf_parse_union_core_v2.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import statistics
  2. import time
  3. from loguru import logger
  4. from typing import List
  5. import torch
  6. from magic_pdf.libs.commons import fitz, get_delta_time
  7. from magic_pdf.libs.convert_utils import dict_to_list
  8. from magic_pdf.libs.drop_reason import DropReason
  9. from magic_pdf.libs.hash_utils import compute_md5
  10. from magic_pdf.libs.local_math import float_equal
  11. from magic_pdf.libs.ocr_content_type import ContentType
  12. from magic_pdf.model.magic_model import MagicModel
  13. from magic_pdf.pre_proc.citationmarker_remove import remove_citation_marker
  14. from magic_pdf.pre_proc.construct_page_dict import ocr_construct_page_component_v2
  15. from magic_pdf.pre_proc.cut_image import ocr_cut_image_and_table
  16. from magic_pdf.pre_proc.equations_replace import remove_chars_in_text_blocks, replace_equations_in_textblock, \
  17. combine_chars_to_pymudict
  18. from magic_pdf.pre_proc.ocr_detect_all_bboxes import ocr_prepare_bboxes_for_layout_split_v2
  19. from magic_pdf.pre_proc.ocr_dict_merge import fill_spans_in_blocks, fix_block_spans, fix_discarded_block
  20. from magic_pdf.pre_proc.ocr_span_list_modify import remove_overlaps_min_spans, get_qa_need_list_v2, \
  21. remove_overlaps_low_confidence_spans
  22. from magic_pdf.pre_proc.resolve_bbox_conflict import check_useful_block_horizontal_overlap
  23. def remove_horizontal_overlap_block_which_smaller(all_bboxes):
  24. useful_blocks = []
  25. for bbox in all_bboxes:
  26. useful_blocks.append({
  27. "bbox": bbox[:4]
  28. })
  29. is_useful_block_horz_overlap, smaller_bbox, bigger_bbox = check_useful_block_horizontal_overlap(useful_blocks)
  30. if is_useful_block_horz_overlap:
  31. logger.warning(
  32. f"skip this page, reason: {DropReason.USEFUL_BLOCK_HOR_OVERLAP}, smaller bbox is {smaller_bbox}, bigger bbox is {bigger_bbox}")
  33. for bbox in all_bboxes.copy():
  34. if smaller_bbox == bbox[:4]:
  35. all_bboxes.remove(bbox)
  36. return is_useful_block_horz_overlap, all_bboxes
  37. def __replace_STX_ETX(text_str:str):
  38. """ Replace \u0002 and \u0003, as these characters become garbled when extracted using pymupdf. In fact, they were originally quotation marks.
  39. Drawback: This issue is only observed in English text; it has not been found in Chinese text so far.
  40. Args:
  41. text_str (str): raw text
  42. Returns:
  43. _type_: replaced text
  44. """
  45. if text_str:
  46. s = text_str.replace('\u0002', "'")
  47. s = s.replace("\u0003", "'")
  48. return s
  49. return text_str
  50. def txt_spans_extract(pdf_page, inline_equations, interline_equations):
  51. text_raw_blocks = pdf_page.get_text("dict", flags=fitz.TEXTFLAGS_TEXT)["blocks"]
  52. char_level_text_blocks = pdf_page.get_text("rawdict", flags=fitz.TEXTFLAGS_TEXT)[
  53. "blocks"
  54. ]
  55. text_blocks = combine_chars_to_pymudict(text_raw_blocks, char_level_text_blocks)
  56. text_blocks = replace_equations_in_textblock(
  57. text_blocks, inline_equations, interline_equations
  58. )
  59. text_blocks = remove_citation_marker(text_blocks)
  60. text_blocks = remove_chars_in_text_blocks(text_blocks)
  61. spans = []
  62. for v in text_blocks:
  63. for line in v["lines"]:
  64. for span in line["spans"]:
  65. bbox = span["bbox"]
  66. if float_equal(bbox[0], bbox[2]) or float_equal(bbox[1], bbox[3]):
  67. continue
  68. if span.get('type') not in (ContentType.InlineEquation, ContentType.InterlineEquation):
  69. spans.append(
  70. {
  71. "bbox": list(span["bbox"]),
  72. "content": __replace_STX_ETX(span["text"]),
  73. "type": ContentType.Text,
  74. "score": 1.0,
  75. }
  76. )
  77. return spans
  78. def replace_text_span(pymu_spans, ocr_spans):
  79. return list(filter(lambda x: x["type"] != ContentType.Text, ocr_spans)) + pymu_spans
  80. def model_init(model_name: str):
  81. from transformers import LayoutLMv3ForTokenClassification
  82. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  83. if model_name == "layoutreader":
  84. model = (
  85. LayoutLMv3ForTokenClassification.from_pretrained("hantian/layoutreader")
  86. # .bfloat16()
  87. .to(device)
  88. .eval()
  89. )
  90. else:
  91. logger.error("model name not allow")
  92. exit(1)
  93. return model
  94. class ModelSingleton:
  95. _instance = None
  96. _models = {}
  97. def __new__(cls, *args, **kwargs):
  98. if cls._instance is None:
  99. cls._instance = super().__new__(cls)
  100. return cls._instance
  101. def get_model(self, model_name: str):
  102. if model_name not in self._models:
  103. self._models[model_name] = model_init(model_name=model_name)
  104. return self._models[model_name]
  105. def do_predict(boxes: List[List[int]], model) -> List[int]:
  106. from magic_pdf.v3.helpers import prepare_inputs, boxes2inputs, parse_logits
  107. inputs = boxes2inputs(boxes)
  108. inputs = prepare_inputs(inputs, model)
  109. logits = model(**inputs).logits.cpu().squeeze(0)
  110. return parse_logits(logits, len(boxes))
  111. def parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode):
  112. need_drop = False
  113. drop_reason = []
  114. '''从magic_model对象中获取后面会用到的区块信息'''
  115. img_blocks = magic_model.get_imgs(page_id)
  116. table_blocks = magic_model.get_tables(page_id)
  117. discarded_blocks = magic_model.get_discarded(page_id)
  118. text_blocks = magic_model.get_text_blocks(page_id)
  119. title_blocks = magic_model.get_title_blocks(page_id)
  120. inline_equations, interline_equations, interline_equation_blocks = magic_model.get_equations(page_id)
  121. page_w, page_h = magic_model.get_page_size(page_id)
  122. spans = magic_model.get_all_spans(page_id)
  123. '''根据parse_mode,构造spans'''
  124. if parse_mode == "txt":
  125. """ocr 中文本类的 span 用 pymu spans 替换!"""
  126. pymu_spans = txt_spans_extract(
  127. pdf_docs[page_id], inline_equations, interline_equations
  128. )
  129. spans = replace_text_span(pymu_spans, spans)
  130. elif parse_mode == "ocr":
  131. pass
  132. else:
  133. raise Exception("parse_mode must be txt or ocr")
  134. '''删除重叠spans中置信度较低的那些'''
  135. spans, dropped_spans_by_confidence = remove_overlaps_low_confidence_spans(spans)
  136. '''删除重叠spans中较小的那些'''
  137. spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)
  138. '''对image和table截图'''
  139. spans = ocr_cut_image_and_table(spans, pdf_docs[page_id], page_id, pdf_bytes_md5, imageWriter)
  140. '''将所有区块的bbox整理到一起'''
  141. # interline_equation_blocks参数不够准,后面切换到interline_equations上
  142. interline_equation_blocks = []
  143. if len(interline_equation_blocks) > 0:
  144. all_bboxes, all_discarded_blocks = ocr_prepare_bboxes_for_layout_split_v2(
  145. img_blocks, table_blocks, discarded_blocks, text_blocks, title_blocks,
  146. interline_equation_blocks, page_w, page_h)
  147. else:
  148. all_bboxes, all_discarded_blocks = ocr_prepare_bboxes_for_layout_split_v2(
  149. img_blocks, table_blocks, discarded_blocks, text_blocks, title_blocks,
  150. interline_equations, page_w, page_h)
  151. '''先处理不需要排版的discarded_blocks'''
  152. discarded_block_with_spans, spans = fill_spans_in_blocks(all_discarded_blocks, spans, 0.4)
  153. fix_discarded_blocks = fix_discarded_block(discarded_block_with_spans)
  154. '''如果当前页面没有bbox则跳过'''
  155. if len(all_bboxes) == 0:
  156. logger.warning(f"skip this page, not found useful bbox, page_id: {page_id}")
  157. return ocr_construct_page_component_v2([], [], page_id, page_w, page_h, [],
  158. [], [], interline_equations, fix_discarded_blocks,
  159. need_drop, drop_reason)
  160. '''将span填入排好序的blocks中'''
  161. block_with_spans, spans = fill_spans_in_blocks(all_bboxes, spans, 0.3)
  162. '''对block进行fix操作'''
  163. fix_blocks = fix_block_spans(block_with_spans, img_blocks, table_blocks)
  164. '''获取所有line并对line排序'''
  165. page_line_list = []
  166. for block in fix_blocks:
  167. if block['type'] in ['text', 'title', 'interline_equation']:
  168. for line in block['lines']:
  169. bbox = line['bbox']
  170. page_line_list.append(bbox)
  171. elif block['type'] in ['table', 'image']: # 简单的把表和图都当成一个line处理
  172. bbox = block['bbox']
  173. page_line_list.append(bbox)
  174. # 使用layoutreader排序
  175. x_scale = 1000.0 / page_w
  176. y_scale = 1000.0 / page_h
  177. boxes = []
  178. # logger.info(f"Scale: {x_scale}, {y_scale}, Boxes len: {len(page_line_list)}")
  179. for left, top, right, bottom in page_line_list:
  180. left = round(left * x_scale)
  181. top = round(top * y_scale)
  182. right = round(right * x_scale)
  183. bottom = round(bottom * y_scale)
  184. assert (
  185. 1000 >= right >= left >= 0 and 1000 >= bottom >= top >= 0
  186. ), f"Invalid box. right: {right}, left: {left}, bottom: {bottom}, top: {top}"
  187. boxes.append([left, top, right, bottom])
  188. model_manager = ModelSingleton()
  189. model = model_manager.get_model("layoutreader")
  190. layoutreader_start = time.time()
  191. with torch.no_grad():
  192. orders = do_predict(boxes, model)
  193. # logger.info(f"layoutreader cost time{time.time() - layoutreader_start}")
  194. sorted_bboxes = [page_line_list[i] for i in orders]
  195. '''根据line的中位数算block的序列关系'''
  196. block_without_lines = []
  197. for block in fix_blocks:
  198. if block['type'] in ['text', 'title', 'interline_equation']:
  199. line_index_list = []
  200. if len(block['lines']) == 0:
  201. block_without_lines.append(block)
  202. continue
  203. else:
  204. for line in block['lines']:
  205. line['index'] = sorted_bboxes.index(line['bbox'])
  206. line_index_list.append(line['index'])
  207. median_value = statistics.median(line_index_list)
  208. block['index'] = median_value
  209. elif block['type'] in ['table', 'image']:
  210. block['index'] = sorted_bboxes.index(block['bbox'])
  211. '''移除没有line的block'''
  212. for block in block_without_lines:
  213. fix_blocks.remove(block)
  214. '''重排block'''
  215. sorted_blocks = sorted(fix_blocks, key=lambda b: b['index'])
  216. '''获取QA需要外置的list'''
  217. images, tables, interline_equations = get_qa_need_list_v2(sorted_blocks)
  218. '''构造pdf_info_dict'''
  219. page_info = ocr_construct_page_component_v2(sorted_blocks, [], page_id, page_w, page_h, [],
  220. images, tables, interline_equations, fix_discarded_blocks,
  221. need_drop, drop_reason)
  222. return page_info
  223. def clean_memory():
  224. import gc
  225. if torch.cuda.is_available():
  226. torch.cuda.empty_cache()
  227. torch.cuda.ipc_collect()
  228. gc.collect()
  229. def pdf_parse_union(pdf_bytes,
  230. model_list,
  231. imageWriter,
  232. parse_mode,
  233. start_page_id=0,
  234. end_page_id=None,
  235. debug_mode=False,
  236. ):
  237. pdf_bytes_md5 = compute_md5(pdf_bytes)
  238. pdf_docs = fitz.open("pdf", pdf_bytes)
  239. '''初始化空的pdf_info_dict'''
  240. pdf_info_dict = {}
  241. '''用model_list和docs对象初始化magic_model'''
  242. magic_model = MagicModel(model_list, pdf_docs)
  243. '''根据输入的起始范围解析pdf'''
  244. # end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
  245. end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else len(pdf_docs) - 1
  246. if end_page_id > len(pdf_docs) - 1:
  247. logger.warning("end_page_id is out of range, use pdf_docs length")
  248. end_page_id = len(pdf_docs) - 1
  249. '''初始化启动时间'''
  250. start_time = time.time()
  251. for page_id, page in enumerate(pdf_docs):
  252. '''debug时输出每页解析的耗时'''
  253. if debug_mode:
  254. time_now = time.time()
  255. logger.info(
  256. f"page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}"
  257. )
  258. start_time = time_now
  259. '''解析pdf中的每一页'''
  260. if start_page_id <= page_id <= end_page_id:
  261. page_info = parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode)
  262. else:
  263. page_w = page.rect.width
  264. page_h = page.rect.height
  265. page_info = ocr_construct_page_component_v2([], [], page_id, page_w, page_h, [],
  266. [], [], [], [],
  267. True, "skip page")
  268. pdf_info_dict[f"page_{page_id}"] = page_info
  269. """分段"""
  270. # para_split(pdf_info_dict, debug_mode=debug_mode)
  271. for page_num, page in pdf_info_dict.items():
  272. page['para_blocks'] = page['preproc_blocks']
  273. """dict转list"""
  274. pdf_info_list = dict_to_list(pdf_info_dict)
  275. new_pdf_info_dict = {
  276. "pdf_info": pdf_info_list,
  277. }
  278. clean_memory()
  279. return new_pdf_info_dict
  280. if __name__ == '__main__':
  281. pass