pdf_parse_union_core.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import time
  2. from loguru import logger
  3. from magic_pdf.config.drop_reason import DropReason
  4. from magic_pdf.config.ocr_content_type import ContentType
  5. from magic_pdf.layout.layout_sort import (LAYOUT_UNPROC, get_bboxes_layout,
  6. get_columns_cnt_of_layout)
  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.hash_utils import compute_md5
  10. from magic_pdf.libs.local_math import float_equal
  11. from magic_pdf.model.magic_model import MagicModel
  12. from magic_pdf.para.para_split_v2 import para_split
  13. from magic_pdf.pre_proc.citationmarker_remove import remove_citation_marker
  14. from magic_pdf.pre_proc.construct_page_dict import \
  15. 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 (
  18. combine_chars_to_pymudict, remove_chars_in_text_blocks,
  19. replace_equations_in_textblock)
  20. from magic_pdf.pre_proc.ocr_detect_all_bboxes import \
  21. ocr_prepare_bboxes_for_layout_split
  22. from magic_pdf.pre_proc.ocr_dict_merge import (fill_spans_in_blocks,
  23. fix_block_spans,
  24. fix_discarded_block,
  25. sort_blocks_by_layout)
  26. from magic_pdf.pre_proc.ocr_span_list_modify import (
  27. get_qa_need_list_v2, remove_overlaps_low_confidence_spans,
  28. remove_overlaps_min_spans)
  29. from magic_pdf.pre_proc.resolve_bbox_conflict import \
  30. 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({'bbox': bbox[:4]})
  35. is_useful_block_horz_overlap, smaller_bbox, bigger_bbox = (
  36. check_useful_block_horizontal_overlap(useful_blocks)
  37. )
  38. if is_useful_block_horz_overlap:
  39. logger.warning(
  40. f'skip this page, reason: {DropReason.USEFUL_BLOCK_HOR_OVERLAP}, smaller bbox is {smaller_bbox}, bigger bbox is {bigger_bbox}'
  41. )
  42. for bbox in all_bboxes.copy():
  43. if smaller_bbox == bbox[:4]:
  44. all_bboxes.remove(bbox)
  45. return is_useful_block_horz_overlap, all_bboxes
  46. def __replace_STX_ETX(text_str: str):
  47. """Replace \u0002 and \u0003, as these characters become garbled when extracted using pymupdf. In fact, they were originally quotation marks.
  48. Drawback: This issue is only observed in English text; it has not been found in Chinese text so far.
  49. Args:
  50. text_str (str): raw text
  51. Returns:
  52. _type_: replaced text
  53. """
  54. if text_str:
  55. s = text_str.replace('\u0002', "'")
  56. s = s.replace('\u0003', "'")
  57. return s
  58. return text_str
  59. def txt_spans_extract(pdf_page, inline_equations, interline_equations):
  60. text_raw_blocks = pdf_page.get_text('dict', flags=fitz.TEXTFLAGS_TEXT)['blocks']
  61. char_level_text_blocks = pdf_page.get_text('rawdict', flags=fitz.TEXTFLAGS_TEXT)[
  62. 'blocks'
  63. ]
  64. text_blocks = combine_chars_to_pymudict(text_raw_blocks, char_level_text_blocks)
  65. text_blocks = replace_equations_in_textblock(
  66. text_blocks, inline_equations, interline_equations
  67. )
  68. text_blocks = remove_citation_marker(text_blocks)
  69. text_blocks = remove_chars_in_text_blocks(text_blocks)
  70. spans = []
  71. for v in text_blocks:
  72. for line in v['lines']:
  73. for span in line['spans']:
  74. bbox = span['bbox']
  75. if float_equal(bbox[0], bbox[2]) or float_equal(bbox[1], bbox[3]):
  76. continue
  77. if span.get('type') not in (
  78. ContentType.InlineEquation,
  79. ContentType.InterlineEquation,
  80. ):
  81. spans.append(
  82. {
  83. 'bbox': list(span['bbox']),
  84. 'content': __replace_STX_ETX(span['text']),
  85. 'type': ContentType.Text,
  86. 'score': 1.0,
  87. }
  88. )
  89. return spans
  90. def replace_text_span(pymu_spans, ocr_spans):
  91. return list(filter(lambda x: x['type'] != ContentType.Text, ocr_spans)) + pymu_spans
  92. def parse_page_core(
  93. pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode
  94. ):
  95. need_drop = False
  96. drop_reason = []
  97. """从magic_model对象中获取后面会用到的区块信息"""
  98. img_blocks = magic_model.get_imgs(page_id)
  99. table_blocks = magic_model.get_tables(page_id)
  100. discarded_blocks = magic_model.get_discarded(page_id)
  101. text_blocks = magic_model.get_text_blocks(page_id)
  102. title_blocks = magic_model.get_title_blocks(page_id)
  103. inline_equations, interline_equations, interline_equation_blocks = (
  104. magic_model.get_equations(page_id)
  105. )
  106. page_w, page_h = magic_model.get_page_size(page_id)
  107. spans = magic_model.get_all_spans(page_id)
  108. """根据parse_mode,构造spans"""
  109. if parse_mode == 'txt':
  110. """ocr 中文本类的 span 用 pymu spans 替换!"""
  111. pymu_spans = txt_spans_extract(
  112. pdf_docs[page_id], inline_equations, interline_equations
  113. )
  114. spans = replace_text_span(pymu_spans, spans)
  115. elif parse_mode == 'ocr':
  116. pass
  117. else:
  118. raise Exception('parse_mode must be txt or ocr')
  119. """删除重叠spans中置信度较低的那些"""
  120. spans, dropped_spans_by_confidence = remove_overlaps_low_confidence_spans(spans)
  121. """删除重叠spans中较小的那些"""
  122. spans, dropped_spans_by_span_overlap = remove_overlaps_min_spans(spans)
  123. """对image和table截图"""
  124. spans = ocr_cut_image_and_table(
  125. spans, pdf_docs[page_id], page_id, pdf_bytes_md5, imageWriter
  126. )
  127. """将所有区块的bbox整理到一起"""
  128. # interline_equation_blocks参数不够准,后面切换到interline_equations上
  129. interline_equation_blocks = []
  130. if len(interline_equation_blocks) > 0:
  131. all_bboxes, all_discarded_blocks, drop_reasons = (
  132. ocr_prepare_bboxes_for_layout_split(
  133. img_blocks,
  134. table_blocks,
  135. discarded_blocks,
  136. text_blocks,
  137. title_blocks,
  138. interline_equation_blocks,
  139. page_w,
  140. page_h,
  141. )
  142. )
  143. else:
  144. all_bboxes, all_discarded_blocks, drop_reasons = (
  145. ocr_prepare_bboxes_for_layout_split(
  146. img_blocks,
  147. table_blocks,
  148. discarded_blocks,
  149. text_blocks,
  150. title_blocks,
  151. interline_equations,
  152. page_w,
  153. page_h,
  154. )
  155. )
  156. if len(drop_reasons) > 0:
  157. need_drop = True
  158. drop_reason.append(DropReason.OVERLAP_BLOCKS_CAN_NOT_SEPARATION)
  159. """先处理不需要排版的discarded_blocks"""
  160. discarded_block_with_spans, spans = fill_spans_in_blocks(
  161. all_discarded_blocks, spans, 0.4
  162. )
  163. fix_discarded_blocks = fix_discarded_block(discarded_block_with_spans)
  164. """如果当前页面没有bbox则跳过"""
  165. if len(all_bboxes) == 0:
  166. logger.warning(f'skip this page, not found useful bbox, page_id: {page_id}')
  167. return ocr_construct_page_component_v2(
  168. [],
  169. [],
  170. page_id,
  171. page_w,
  172. page_h,
  173. [],
  174. [],
  175. [],
  176. interline_equations,
  177. fix_discarded_blocks,
  178. need_drop,
  179. drop_reason,
  180. )
  181. """在切分之前,先检查一下bbox是否有左右重叠的情况,如果有,那么就认为这个pdf暂时没有能力处理好,这种左右重叠的情况大概率是由于pdf里的行间公式、表格没有被正确识别出来造成的 """
  182. while True: # 循环检查左右重叠的情况,如果存在就删除掉较小的那个bbox,直到不存在左右重叠的情况
  183. is_useful_block_horz_overlap, all_bboxes = (
  184. remove_horizontal_overlap_block_which_smaller(all_bboxes)
  185. )
  186. if is_useful_block_horz_overlap:
  187. need_drop = True
  188. drop_reason.append(DropReason.USEFUL_BLOCK_HOR_OVERLAP)
  189. else:
  190. break
  191. """根据区块信息计算layout"""
  192. page_boundry = [0, 0, page_w, page_h]
  193. layout_bboxes, layout_tree = get_bboxes_layout(all_bboxes, page_boundry, page_id)
  194. if len(text_blocks) > 0 and len(all_bboxes) > 0 and len(layout_bboxes) == 0:
  195. logger.warning(
  196. f'skip this page, page_id: {page_id}, reason: {DropReason.CAN_NOT_DETECT_PAGE_LAYOUT}'
  197. )
  198. need_drop = True
  199. drop_reason.append(DropReason.CAN_NOT_DETECT_PAGE_LAYOUT)
  200. """以下去掉复杂的布局和超过2列的布局"""
  201. if any(
  202. [lay['layout_label'] == LAYOUT_UNPROC for lay in layout_bboxes]
  203. ): # 复杂的布局
  204. logger.warning(
  205. f'skip this page, page_id: {page_id}, reason: {DropReason.COMPLICATED_LAYOUT}'
  206. )
  207. need_drop = True
  208. drop_reason.append(DropReason.COMPLICATED_LAYOUT)
  209. layout_column_width = get_columns_cnt_of_layout(layout_tree)
  210. if layout_column_width > 2: # 去掉超过2列的布局pdf
  211. logger.warning(
  212. f'skip this page, page_id: {page_id}, reason: {DropReason.TOO_MANY_LAYOUT_COLUMNS}'
  213. )
  214. need_drop = True
  215. drop_reason.append(DropReason.TOO_MANY_LAYOUT_COLUMNS)
  216. """根据layout顺序,对当前页面所有需要留下的block进行排序"""
  217. sorted_blocks = sort_blocks_by_layout(all_bboxes, layout_bboxes)
  218. """将span填入排好序的blocks中"""
  219. block_with_spans, spans = fill_spans_in_blocks(sorted_blocks, spans, 0.3)
  220. """对block进行fix操作"""
  221. fix_blocks = fix_block_spans(block_with_spans, img_blocks, table_blocks)
  222. """获取QA需要外置的list"""
  223. images, tables, interline_equations = get_qa_need_list_v2(fix_blocks)
  224. """构造pdf_info_dict"""
  225. page_info = ocr_construct_page_component_v2(
  226. fix_blocks,
  227. layout_bboxes,
  228. page_id,
  229. page_w,
  230. page_h,
  231. layout_tree,
  232. images,
  233. tables,
  234. interline_equations,
  235. fix_discarded_blocks,
  236. need_drop,
  237. drop_reason,
  238. )
  239. return page_info
  240. def pdf_parse_union(
  241. pdf_bytes,
  242. model_list,
  243. imageWriter,
  244. parse_mode,
  245. start_page_id=0,
  246. end_page_id=None,
  247. debug_mode=False,
  248. ):
  249. pdf_bytes_md5 = compute_md5(pdf_bytes)
  250. pdf_docs = fitz.open('pdf', pdf_bytes)
  251. """初始化空的pdf_info_dict"""
  252. pdf_info_dict = {}
  253. """用model_list和docs对象初始化magic_model"""
  254. magic_model = MagicModel(model_list, pdf_docs)
  255. """根据输入的起始范围解析pdf"""
  256. # end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
  257. end_page_id = (
  258. end_page_id
  259. if end_page_id is not None and end_page_id >= 0
  260. else len(pdf_docs) - 1
  261. )
  262. if end_page_id > len(pdf_docs) - 1:
  263. logger.warning('end_page_id is out of range, use pdf_docs length')
  264. end_page_id = len(pdf_docs) - 1
  265. """初始化启动时间"""
  266. start_time = time.time()
  267. for page_id, page in enumerate(pdf_docs):
  268. """debug时输出每页解析的耗时."""
  269. if debug_mode:
  270. time_now = time.time()
  271. logger.info(
  272. f'page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}'
  273. )
  274. start_time = time_now
  275. """解析pdf中的每一页"""
  276. if start_page_id <= page_id <= end_page_id:
  277. page_info = parse_page_core(
  278. pdf_docs, magic_model, page_id, pdf_bytes_md5, imageWriter, parse_mode
  279. )
  280. else:
  281. page_w = page.rect.width
  282. page_h = page.rect.height
  283. page_info = ocr_construct_page_component_v2(
  284. [], [], page_id, page_w, page_h, [], [], [], [], [], True, 'skip page'
  285. )
  286. pdf_info_dict[f'page_{page_id}'] = page_info
  287. """分段"""
  288. para_split(pdf_info_dict, debug_mode=debug_mode)
  289. """dict转list"""
  290. pdf_info_list = dict_to_list(pdf_info_dict)
  291. new_pdf_info_dict = {
  292. 'pdf_info': pdf_info_list,
  293. }
  294. return new_pdf_info_dict
  295. if __name__ == '__main__':
  296. pass