pdf_parse_union_core.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import time
  2. from loguru import logger
  3. from magic_pdf.libs.commons import fitz, get_delta_time
  4. from magic_pdf.layout.layout_sort import get_bboxes_layout, LAYOUT_UNPROC, get_columns_cnt_of_layout
  5. from magic_pdf.libs.convert_utils import dict_to_list
  6. from magic_pdf.libs.drop_reason import DropReason
  7. from magic_pdf.libs.hash_utils import compute_md5
  8. from magic_pdf.libs.local_math import float_equal
  9. from magic_pdf.libs.ocr_content_type import ContentType
  10. from magic_pdf.model.magic_model import MagicModel
  11. from magic_pdf.para.para_split_v2 import para_split
  12. from magic_pdf.pre_proc.citationmarker_remove import remove_citation_marker
  13. from magic_pdf.pre_proc.construct_page_dict import ocr_construct_page_component_v2
  14. from magic_pdf.pre_proc.cut_image import ocr_cut_image_and_table
  15. from magic_pdf.pre_proc.equations_replace import remove_chars_in_text_blocks, replace_equations_in_textblock, \
  16. combine_chars_to_pymudict
  17. from magic_pdf.pre_proc.ocr_detect_all_bboxes import ocr_prepare_bboxes_for_layout_split
  18. from magic_pdf.pre_proc.ocr_dict_merge import sort_blocks_by_layout, fill_spans_in_blocks, fix_block_spans, \
  19. 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 parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode):
  81. need_drop = False
  82. drop_reason = []
  83. '''从magic_model对象中获取后面会用到的区块信息'''
  84. img_blocks = magic_model.get_imgs(page_id)
  85. table_blocks = magic_model.get_tables(page_id)
  86. discarded_blocks = magic_model.get_discarded(page_id)
  87. text_blocks = magic_model.get_text_blocks(page_id)
  88. title_blocks = magic_model.get_title_blocks(page_id)
  89. inline_equations, interline_equations, interline_equation_blocks = magic_model.get_equations(page_id)
  90. page_w, page_h = magic_model.get_page_size(page_id)
  91. spans = magic_model.get_all_spans(page_id)
  92. '''根据parse_mode,构造spans'''
  93. if parse_mode == "txt":
  94. """ocr 中文本类的 span 用 pymu spans 替换!"""
  95. pymu_spans = txt_spans_extract(
  96. pdf_docs[page_id], inline_equations, interline_equations
  97. )
  98. spans = replace_text_span(pymu_spans, spans)
  99. elif parse_mode == "ocr":
  100. pass
  101. else:
  102. raise Exception("parse_mode must be txt or ocr")
  103. '''删除重叠spans中置信度较低的那些'''
  104. spans, dropped_spans_by_confidence = remove_overlaps_low_confidence_spans(spans)
  105. '''删除重叠spans中较小的那些'''
  106. spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)
  107. '''对image和table截图'''
  108. spans = ocr_cut_image_and_table(spans, pdf_docs[page_id], page_id, pdf_bytes_md5, imageWriter)
  109. '''将所有区块的bbox整理到一起'''
  110. # interline_equation_blocks参数不够准,后面切换到interline_equations上
  111. interline_equation_blocks = []
  112. if len(interline_equation_blocks) > 0:
  113. all_bboxes, all_discarded_blocks, drop_reasons = ocr_prepare_bboxes_for_layout_split(
  114. img_blocks, table_blocks, discarded_blocks, text_blocks, title_blocks,
  115. interline_equation_blocks, page_w, page_h)
  116. else:
  117. all_bboxes, all_discarded_blocks, drop_reasons = ocr_prepare_bboxes_for_layout_split(
  118. img_blocks, table_blocks, discarded_blocks, text_blocks, title_blocks,
  119. interline_equations, page_w, page_h)
  120. if len(drop_reasons) > 0:
  121. need_drop = True
  122. drop_reason.append(DropReason.OVERLAP_BLOCKS_CAN_NOT_SEPARATION)
  123. '''先处理不需要排版的discarded_blocks'''
  124. discarded_block_with_spans, spans = fill_spans_in_blocks(all_discarded_blocks, spans, 0.4)
  125. fix_discarded_blocks = fix_discarded_block(discarded_block_with_spans)
  126. '''如果当前页面没有bbox则跳过'''
  127. if len(all_bboxes) == 0:
  128. logger.warning(f"skip this page, not found useful bbox, page_id: {page_id}")
  129. return ocr_construct_page_component_v2([], [], page_id, page_w, page_h, [],
  130. [], [], interline_equations, fix_discarded_blocks,
  131. need_drop, drop_reason)
  132. """在切分之前,先检查一下bbox是否有左右重叠的情况,如果有,那么就认为这个pdf暂时没有能力处理好,这种左右重叠的情况大概率是由于pdf里的行间公式、表格没有被正确识别出来造成的 """
  133. while True: # 循环检查左右重叠的情况,如果存在就删除掉较小的那个bbox,直到不存在左右重叠的情况
  134. is_useful_block_horz_overlap, all_bboxes = remove_horizontal_overlap_block_which_smaller(all_bboxes)
  135. if is_useful_block_horz_overlap:
  136. need_drop = True
  137. drop_reason.append(DropReason.USEFUL_BLOCK_HOR_OVERLAP)
  138. else:
  139. break
  140. '''根据区块信息计算layout'''
  141. page_boundry = [0, 0, page_w, page_h]
  142. layout_bboxes, layout_tree = get_bboxes_layout(all_bboxes, page_boundry, page_id)
  143. if len(text_blocks) > 0 and len(all_bboxes) > 0 and len(layout_bboxes) == 0:
  144. logger.warning(
  145. f"skip this page, page_id: {page_id}, reason: {DropReason.CAN_NOT_DETECT_PAGE_LAYOUT}")
  146. need_drop = True
  147. drop_reason.append(DropReason.CAN_NOT_DETECT_PAGE_LAYOUT)
  148. """以下去掉复杂的布局和超过2列的布局"""
  149. if any([lay["layout_label"] == LAYOUT_UNPROC for lay in layout_bboxes]): # 复杂的布局
  150. logger.warning(
  151. f"skip this page, page_id: {page_id}, reason: {DropReason.COMPLICATED_LAYOUT}")
  152. need_drop = True
  153. drop_reason.append(DropReason.COMPLICATED_LAYOUT)
  154. layout_column_width = get_columns_cnt_of_layout(layout_tree)
  155. if layout_column_width > 2: # 去掉超过2列的布局pdf
  156. logger.warning(
  157. f"skip this page, page_id: {page_id}, reason: {DropReason.TOO_MANY_LAYOUT_COLUMNS}")
  158. need_drop = True
  159. drop_reason.append(DropReason.TOO_MANY_LAYOUT_COLUMNS)
  160. '''根据layout顺序,对当前页面所有需要留下的block进行排序'''
  161. sorted_blocks = sort_blocks_by_layout(all_bboxes, layout_bboxes)
  162. '''将span填入排好序的blocks中'''
  163. block_with_spans, spans = fill_spans_in_blocks(sorted_blocks, spans, 0.3)
  164. '''对block进行fix操作'''
  165. fix_blocks = fix_block_spans(block_with_spans, img_blocks, table_blocks)
  166. '''获取QA需要外置的list'''
  167. images, tables, interline_equations = get_qa_need_list_v2(fix_blocks)
  168. '''构造pdf_info_dict'''
  169. page_info = ocr_construct_page_component_v2(fix_blocks, layout_bboxes, page_id, page_w, page_h, layout_tree,
  170. images, tables, interline_equations, fix_discarded_blocks,
  171. need_drop, drop_reason)
  172. return page_info
  173. def pdf_parse_union(pdf_bytes,
  174. model_list,
  175. imageWriter,
  176. parse_mode,
  177. start_page_id=0,
  178. end_page_id=None,
  179. debug_mode=False,
  180. ):
  181. pdf_bytes_md5 = compute_md5(pdf_bytes)
  182. pdf_docs = fitz.open("pdf", pdf_bytes)
  183. '''初始化空的pdf_info_dict'''
  184. pdf_info_dict = {}
  185. '''用model_list和docs对象初始化magic_model'''
  186. magic_model = MagicModel(model_list, pdf_docs)
  187. '''根据输入的起始范围解析pdf'''
  188. # end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
  189. end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else len(pdf_docs) - 1
  190. if end_page_id > len(pdf_docs) - 1:
  191. logger.warning("end_page_id is out of range, use pdf_docs length")
  192. end_page_id = len(pdf_docs) - 1
  193. '''初始化启动时间'''
  194. start_time = time.time()
  195. for page_id, page in enumerate(pdf_docs):
  196. '''debug时输出每页解析的耗时'''
  197. if debug_mode:
  198. time_now = time.time()
  199. logger.info(
  200. f"page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}"
  201. )
  202. start_time = time_now
  203. '''解析pdf中的每一页'''
  204. if start_page_id <= page_id <= end_page_id:
  205. page_info = parse_page_core(pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode)
  206. else:
  207. page_w = page.rect.width
  208. page_h = page.rect.height
  209. page_info = ocr_construct_page_component_v2([], [], page_id, page_w, page_h, [],
  210. [], [], [], [],
  211. True, "skip page")
  212. pdf_info_dict[f"page_{page_id}"] = page_info
  213. """分段"""
  214. para_split(pdf_info_dict, debug_mode=debug_mode)
  215. """dict转list"""
  216. pdf_info_list = dict_to_list(pdf_info_dict)
  217. new_pdf_info_dict = {
  218. "pdf_info": pdf_info_list,
  219. }
  220. return new_pdf_info_dict
  221. if __name__ == '__main__':
  222. pass