pdf_parse_by_txt_v2.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import time
  2. from loguru import logger
  3. from magic_pdf.layout.layout_sort import get_bboxes_layout, LAYOUT_UNPROC, get_columns_cnt_of_layout
  4. from magic_pdf.libs.convert_utils import dict_to_list
  5. from magic_pdf.libs.drop_reason import DropReason
  6. from magic_pdf.libs.hash_utils import compute_md5
  7. from magic_pdf.libs.commons import fitz, get_delta_time
  8. from magic_pdf.model.magic_model import MagicModel
  9. from magic_pdf.pre_proc.construct_page_dict import ocr_construct_page_component_v2
  10. from magic_pdf.pre_proc.cut_image import ocr_cut_image_and_table
  11. from magic_pdf.pre_proc.ocr_detect_all_bboxes import ocr_prepare_bboxes_for_layout_split
  12. from magic_pdf.pre_proc.ocr_dict_merge import (
  13. sort_blocks_by_layout,
  14. fill_spans_in_blocks,
  15. fix_block_spans,
  16. )
  17. from magic_pdf.libs.ocr_content_type import ContentType
  18. from magic_pdf.pre_proc.ocr_span_list_modify import (
  19. remove_overlaps_min_spans,
  20. get_qa_need_list_v2,
  21. )
  22. from magic_pdf.pre_proc.equations_replace import (
  23. combine_chars_to_pymudict,
  24. remove_chars_in_text_blocks,
  25. replace_equations_in_textblock,
  26. )
  27. from magic_pdf.pre_proc.citationmarker_remove import remove_citation_marker
  28. from magic_pdf.libs.math import float_equal
  29. from magic_pdf.para.para_split_v2 import para_split
  30. from magic_pdf.pre_proc.resolve_bbox_conflict import check_useful_block_horizontal_overlap
  31. def remove_horizontal_overlap_block_which_smaller(all_bboxes):
  32. useful_blocks = []
  33. for bbox in all_bboxes:
  34. useful_blocks.append({
  35. "bbox": bbox[:4]
  36. })
  37. is_useful_block_horz_overlap, smaller_bbox = check_useful_block_horizontal_overlap(useful_blocks)
  38. if is_useful_block_horz_overlap:
  39. logger.warning(
  40. f"skip this page, reason: {DropReason.USEFUL_BLOCK_HOR_OVERLAP}")
  41. for bbox in all_bboxes.copy():
  42. if smaller_bbox == bbox[:4]:
  43. all_bboxes.remove(bbox)
  44. return is_useful_block_horz_overlap, all_bboxes
  45. def txt_spans_extract(pdf_page, inline_equations, interline_equations):
  46. text_raw_blocks = pdf_page.get_text("dict", flags=fitz.TEXTFLAGS_TEXT)["blocks"]
  47. char_level_text_blocks = pdf_page.get_text("rawdict", flags=fitz.TEXTFLAGS_TEXT)[
  48. "blocks"
  49. ]
  50. text_blocks = combine_chars_to_pymudict(text_raw_blocks, char_level_text_blocks)
  51. text_blocks = replace_equations_in_textblock(
  52. text_blocks, inline_equations, interline_equations
  53. )
  54. text_blocks = remove_citation_marker(text_blocks)
  55. text_blocks = remove_chars_in_text_blocks(text_blocks)
  56. spans = []
  57. for v in text_blocks:
  58. for line in v["lines"]:
  59. for span in line["spans"]:
  60. bbox = span["bbox"]
  61. if float_equal(bbox[0], bbox[2]) or float_equal(bbox[1], bbox[3]):
  62. continue
  63. if span.get('type') == ContentType.InlineEquation:
  64. spans.append(
  65. {
  66. "bbox": list(span["bbox"]),
  67. "content": span["latex"],
  68. "type": ContentType.InlineEquation,
  69. }
  70. )
  71. elif span.get('type') == ContentType.InterlineEquation:
  72. spans.append(
  73. {
  74. "bbox": list(span["bbox"]),
  75. "content": span["latex"],
  76. "type": ContentType.InterlineEquation,
  77. }
  78. )
  79. else:
  80. spans.append(
  81. {
  82. "bbox": list(span["bbox"]),
  83. "content": span["text"],
  84. "type": ContentType.Text,
  85. }
  86. )
  87. return spans
  88. def replace_text_span(pymu_spans, ocr_spans):
  89. return list(filter(lambda x: x["type"] != ContentType.Text, ocr_spans)) + pymu_spans
  90. def parse_pdf_by_txt(
  91. pdf_bytes,
  92. model_list,
  93. imageWriter,
  94. start_page_id=0,
  95. end_page_id=None,
  96. debug_mode=False,
  97. ):
  98. need_drop = False
  99. drop_reason = ""
  100. pdf_bytes_md5 = compute_md5(pdf_bytes)
  101. pdf_docs = fitz.open("pdf", pdf_bytes)
  102. """初始化空的pdf_info_dict"""
  103. pdf_info_dict = {}
  104. """用model_list和docs对象初始化magic_model"""
  105. magic_model = MagicModel(model_list, pdf_docs)
  106. """根据输入的起始范围解析pdf"""
  107. end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
  108. """初始化启动时间"""
  109. start_time = time.time()
  110. for page_id in range(start_page_id, end_page_id + 1):
  111. """debug时输出每页解析的耗时"""
  112. if debug_mode:
  113. time_now = time.time()
  114. logger.info(
  115. f"page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}"
  116. )
  117. start_time = time_now
  118. """从magic_model对象中获取后面会用到的区块信息"""
  119. img_blocks = magic_model.get_imgs(page_id)
  120. table_blocks = magic_model.get_tables(page_id)
  121. discarded_blocks = magic_model.get_discarded(page_id)
  122. text_blocks = magic_model.get_text_blocks(page_id)
  123. title_blocks = magic_model.get_title_blocks(page_id)
  124. inline_equations, interline_equations, interline_equation_blocks = (
  125. magic_model.get_equations(page_id)
  126. )
  127. page_w, page_h = magic_model.get_page_size(page_id)
  128. """将所有区块的bbox整理到一起"""
  129. all_bboxes = ocr_prepare_bboxes_for_layout_split(
  130. img_blocks,
  131. table_blocks,
  132. discarded_blocks,
  133. text_blocks,
  134. title_blocks,
  135. interline_equations,
  136. page_w,
  137. page_h,
  138. )
  139. """在切分之前,先检查一下bbox是否有左右重叠的情况,如果有,那么就认为这个pdf暂时没有能力处理好,这种左右重叠的情况大概率是由于pdf里的行间公式、表格没有被正确识别出来造成的 """
  140. while True: # 循环检查左右重叠的情况,如果存在就删除掉较小的那个bbox,直到不存在左右重叠的情况
  141. is_useful_block_horz_overlap, all_bboxes = remove_horizontal_overlap_block_which_smaller(all_bboxes)
  142. if is_useful_block_horz_overlap:
  143. need_drop = True
  144. drop_reason = DropReason.USEFUL_BLOCK_HOR_OVERLAP
  145. else:
  146. break
  147. '''根据区块信息计算layout'''
  148. page_boundry = [0, 0, page_w, page_h]
  149. layout_bboxes, layout_tree = get_bboxes_layout(all_bboxes, page_boundry, page_id)
  150. if len(text_blocks) > 0 and len(all_bboxes) > 0 and len(layout_bboxes) == 0:
  151. logger.warning(
  152. f"pdf: {pdf_bytes_md5}, skip this page, page_id: {page_id}, reason: {DropReason.CAN_NOT_DETECT_PAGE_LAYOUT}")
  153. need_drop = True
  154. drop_reason = DropReason.CAN_NOT_DETECT_PAGE_LAYOUT
  155. """以下去掉复杂的布局和超过2列的布局"""
  156. if any([lay["layout_label"] == LAYOUT_UNPROC for lay in layout_bboxes]): # 复杂的布局
  157. logger.warning(
  158. f"pdf: {pdf_bytes_md5}, skip this page, page_id: {page_id}, reason: {DropReason.COMPLICATED_LAYOUT}")
  159. need_drop = True
  160. drop_reason = DropReason.COMPLICATED_LAYOUT
  161. layout_column_width = get_columns_cnt_of_layout(layout_tree)
  162. if layout_column_width > 2: # 去掉超过2列的布局pdf
  163. logger.warning(
  164. f"pdf: {pdf_bytes_md5}, skip this page, page_id: {page_id}, reason: {DropReason.TOO_MANY_LAYOUT_COLUMNS}")
  165. need_drop = True
  166. drop_reason = DropReason.TOO_MANY_LAYOUT_COLUMNS
  167. """根据layout顺序,对当前页面所有需要留下的block进行排序"""
  168. sorted_blocks = sort_blocks_by_layout(all_bboxes, layout_bboxes)
  169. """ocr 中文本类的 span 用 pymu spans 替换!"""
  170. ocr_spans = magic_model.get_all_spans(page_id)
  171. pymu_spans = txt_spans_extract(
  172. pdf_docs[page_id], inline_equations, interline_equations
  173. )
  174. spans = replace_text_span(pymu_spans, ocr_spans)
  175. """删除重叠spans中较小的那些"""
  176. spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)
  177. """对image和table截图"""
  178. spans = ocr_cut_image_and_table(
  179. spans, pdf_docs[page_id], page_id, pdf_bytes_md5, imageWriter
  180. )
  181. """将span填入排好序的blocks中"""
  182. block_with_spans = fill_spans_in_blocks(sorted_blocks, spans)
  183. """对block进行fix操作"""
  184. fix_blocks = fix_block_spans(block_with_spans, img_blocks, table_blocks)
  185. """获取QA需要外置的list"""
  186. images, tables, interline_equations = get_qa_need_list_v2(fix_blocks)
  187. """构造pdf_info_dict"""
  188. page_info = ocr_construct_page_component_v2(
  189. fix_blocks,
  190. layout_bboxes,
  191. page_id,
  192. page_w,
  193. page_h,
  194. layout_tree,
  195. images,
  196. tables,
  197. interline_equations,
  198. discarded_blocks,
  199. need_drop,
  200. drop_reason
  201. )
  202. pdf_info_dict[f"page_{page_id}"] = page_info
  203. """分段"""
  204. try:
  205. para_split(pdf_info_dict, debug_mode=debug_mode)
  206. except Exception as e:
  207. logger.exception(e)
  208. raise e
  209. """dict转list"""
  210. pdf_info_list = dict_to_list(pdf_info_dict)
  211. new_pdf_info_dict = {
  212. "pdf_info": pdf_info_list,
  213. }
  214. return new_pdf_info_dict
  215. if __name__ == "__main__":
  216. if 1:
  217. import fitz
  218. import json
  219. with open("/opt/data/pdf/20240418/25536-00.pdf", "rb") as f:
  220. pdf_bytes = f.read()
  221. pdf_docs = fitz.open("pdf", pdf_bytes)
  222. with open("/opt/data/pdf/20240418/25536-00.json") as f:
  223. model_list = json.loads(f.readline())
  224. magic_model = MagicModel(model_list, pdf_docs)
  225. for i in range(7):
  226. print(magic_model.get_imgs(i))
  227. for page_no, page in enumerate(pdf_docs):
  228. inline_equations, interline_equations, interline_equation_blocks = (
  229. magic_model.get_equations(page_no)
  230. )
  231. text_raw_blocks = page.get_text("dict", flags=fitz.TEXTFLAGS_TEXT)["blocks"]
  232. char_level_text_blocks = page.get_text(
  233. "rawdict", flags=fitz.TEXTFLAGS_TEXT
  234. )["blocks"]
  235. text_blocks = combine_chars_to_pymudict(
  236. text_raw_blocks, char_level_text_blocks
  237. )
  238. text_blocks = replace_equations_in_textblock(
  239. text_blocks, inline_equations, interline_equations
  240. )
  241. text_blocks = remove_citation_marker(text_blocks)
  242. text_blocks = remove_chars_in_text_blocks(text_blocks)