pdf_parse_by_ocr.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import json
  2. import os
  3. import time
  4. from loguru import logger
  5. from magic_pdf.libs.draw_bbox import draw_layout_bbox, draw_text_bbox
  6. from magic_pdf.libs.commons import (
  7. read_file,
  8. join_path,
  9. fitz,
  10. get_img_s3_client,
  11. get_delta_time,
  12. get_docx_model_output,
  13. )
  14. from magic_pdf.libs.coordinate_transform import get_scale_ratio
  15. from magic_pdf.libs.ocr_content_type import ContentType
  16. from magic_pdf.libs.safe_filename import sanitize_filename
  17. from magic_pdf.para.para_split import para_split
  18. from magic_pdf.pre_proc.detect_footer_by_model import parse_footers
  19. from magic_pdf.pre_proc.detect_footnote import parse_footnotes_by_model
  20. from magic_pdf.pre_proc.detect_header import parse_headers
  21. from magic_pdf.pre_proc.detect_page_number import parse_pageNos
  22. from magic_pdf.pre_proc.ocr_cut_image import cut_image_and_table
  23. from magic_pdf.pre_proc.ocr_detect_layout import layout_detect
  24. from magic_pdf.pre_proc.ocr_dict_merge import (
  25. merge_spans_to_line_by_layout, merge_lines_to_block,
  26. )
  27. from magic_pdf.pre_proc.ocr_span_list_modify import remove_spans_by_bboxes, remove_overlaps_min_spans, \
  28. adjust_bbox_for_standalone_block, modify_y_axis, modify_inline_equation, get_qa_need_list, \
  29. remove_spans_by_bboxes_dict
  30. from magic_pdf.pre_proc.remove_bbox_overlap import remove_overlap_between_bbox
  31. def construct_page_component(blocks, para_blocks, layout_bboxes, page_id, page_w, page_h, layout_tree,
  32. images, tables, interline_equations, inline_equations,
  33. dropped_text_block, dropped_image_block, dropped_table_block,
  34. need_remove_spans_bboxes_dict):
  35. return_dict = {
  36. 'preproc_blocks': blocks,
  37. "para_blocks": para_blocks, # 分好段落的blocks
  38. 'layout_bboxes': layout_bboxes,
  39. 'page_idx': page_id,
  40. 'page_size': [page_w, page_h],
  41. '_layout_tree': layout_tree,
  42. 'images': images,
  43. 'tables': tables,
  44. 'interline_equations': interline_equations,
  45. 'inline_equations': inline_equations,
  46. 'droped_text_block': dropped_text_block,
  47. 'droped_image_block': dropped_image_block,
  48. 'droped_table_block': dropped_table_block,
  49. 'droped_bboxes': need_remove_spans_bboxes_dict,
  50. }
  51. return return_dict
  52. def parse_pdf_by_ocr(
  53. pdf_path,
  54. s3_pdf_profile,
  55. pdf_model_output,
  56. save_path,
  57. book_name,
  58. pdf_model_profile=None,
  59. image_s3_config=None,
  60. start_page_id=0,
  61. end_page_id=None,
  62. debug_mode=False,
  63. ):
  64. pdf_bytes = read_file(pdf_path, s3_pdf_profile)
  65. save_tmp_path = os.path.join(os.path.dirname(__file__), "../..", "tmp", "unittest")
  66. book_name = sanitize_filename(book_name)
  67. md_bookname_save_path = ""
  68. if debug_mode:
  69. save_path = join_path(save_tmp_path, "md")
  70. pdf_local_path = join_path(save_tmp_path, "download-pdfs", book_name)
  71. if not os.path.exists(os.path.dirname(pdf_local_path)):
  72. # 如果目录不存在,创建它
  73. os.makedirs(os.path.dirname(pdf_local_path))
  74. md_bookname_save_path = join_path(save_tmp_path, "md", book_name)
  75. if not os.path.exists(md_bookname_save_path):
  76. # 如果目录不存在,创建它
  77. os.makedirs(md_bookname_save_path)
  78. with open(pdf_local_path + ".pdf", "wb") as pdf_file:
  79. pdf_file.write(pdf_bytes)
  80. pdf_docs = fitz.open("pdf", pdf_bytes)
  81. # 初始化空的pdf_info_dict
  82. pdf_info_dict = {}
  83. img_s3_client = get_img_s3_client(save_path, image_s3_config)
  84. start_time = time.time()
  85. end_page_id = end_page_id if end_page_id else len(pdf_docs) - 1
  86. for page_id in range(start_page_id, end_page_id + 1):
  87. # 获取当前页的page对象
  88. page = pdf_docs[page_id]
  89. # 获取当前页的宽高
  90. page_w = page.rect.width
  91. page_h = page.rect.height
  92. if debug_mode:
  93. time_now = time.time()
  94. logger.info(
  95. f"page_id: {page_id}, last_page_cost_time: {get_delta_time(start_time)}"
  96. )
  97. start_time = time_now
  98. # 获取当前页的模型数据
  99. ocr_page_info = get_docx_model_output(
  100. pdf_model_output, pdf_model_profile, page_id
  101. )
  102. """从json中获取每页的页码、页眉、页脚的bbox"""
  103. page_no_bboxes = parse_pageNos(page_id, page, ocr_page_info)
  104. header_bboxes = parse_headers(page_id, page, ocr_page_info)
  105. footer_bboxes = parse_footers(page_id, page, ocr_page_info)
  106. footnote_bboxes = parse_footnotes_by_model(
  107. page_id, page, ocr_page_info, md_bookname_save_path, debug_mode=debug_mode
  108. )
  109. # 构建需要remove的bbox列表
  110. # need_remove_spans_bboxes = []
  111. # need_remove_spans_bboxes.extend(page_no_bboxes)
  112. # need_remove_spans_bboxes.extend(header_bboxes)
  113. # need_remove_spans_bboxes.extend(footer_bboxes)
  114. # need_remove_spans_bboxes.extend(footnote_bboxes)
  115. # 构建需要remove的bbox字典
  116. need_remove_spans_bboxes_dict = {
  117. "page_no": page_no_bboxes,
  118. "header": header_bboxes,
  119. "footer": footer_bboxes,
  120. "footnote": footnote_bboxes,
  121. }
  122. layout_dets = ocr_page_info["layout_dets"]
  123. spans = []
  124. # 计算模型坐标和pymu坐标的缩放比例
  125. horizontal_scale_ratio, vertical_scale_ratio = get_scale_ratio(
  126. ocr_page_info, page
  127. )
  128. for layout_det in layout_dets:
  129. category_id = layout_det["category_id"]
  130. allow_category_id_list = [1, 7, 13, 14, 15]
  131. if category_id in allow_category_id_list:
  132. x0, y0, _, _, x1, y1, _, _ = layout_det["poly"]
  133. bbox = [
  134. int(x0 / horizontal_scale_ratio),
  135. int(y0 / vertical_scale_ratio),
  136. int(x1 / horizontal_scale_ratio),
  137. int(y1 / vertical_scale_ratio),
  138. ]
  139. # 删除高度或者宽度为0的spans
  140. if bbox[2] - bbox[0] == 0 or bbox[3] - bbox[1] == 0:
  141. continue
  142. """要删除的"""
  143. # 3: 'header', # 页眉
  144. # 4: 'page number', # 页码
  145. # 5: 'footnote', # 脚注
  146. # 6: 'footer', # 页脚
  147. """当成span拼接的"""
  148. # 1: 'image', # 图片
  149. # 7: 'table', # 表格
  150. # 13: 'inline_equation', # 行内公式
  151. # 14: 'interline_equation', # 行间公式
  152. # 15: 'text', # ocr识别文本
  153. """layout信息"""
  154. # 11: 'full column', # 单栏
  155. # 12: 'sub column', # 多栏
  156. span = {
  157. "bbox": bbox,
  158. }
  159. if category_id == 1:
  160. span["type"] = ContentType.Image
  161. elif category_id == 7:
  162. span["type"] = ContentType.Table
  163. elif category_id == 13:
  164. span["content"] = layout_det["latex"]
  165. span["type"] = ContentType.InlineEquation
  166. elif category_id == 14:
  167. span["content"] = layout_det["latex"]
  168. span["type"] = ContentType.InterlineEquation
  169. elif category_id == 15:
  170. span["content"] = layout_det["text"]
  171. span["type"] = ContentType.Text
  172. # print(span)
  173. spans.append(span)
  174. else:
  175. continue
  176. # 删除重叠spans中较小的那些
  177. spans = remove_overlaps_min_spans(spans)
  178. # 删除remove_span_block_bboxes中的bbox
  179. # spans = remove_spans_by_bboxes(spans, need_remove_spans_bboxes)
  180. # 按qa要求,增加drop相关数据
  181. spans, dropped_text_block, dropped_image_block, dropped_table_block = remove_spans_by_bboxes_dict(spans, need_remove_spans_bboxes_dict)
  182. # 对image和table截图
  183. spans = cut_image_and_table(spans, page, page_id, book_name, save_path, img_s3_client)
  184. # 行内公式调整, 高度调整至与同行文字高度一致(优先左侧, 其次右侧)
  185. displayed_list = []
  186. text_inline_lines = []
  187. modify_y_axis(spans, displayed_list, text_inline_lines)
  188. # 模型识别错误的行间公式, type类型转换成行内公式
  189. spans = modify_inline_equation(spans, displayed_list, text_inline_lines)
  190. # bbox去除粘连
  191. spans = remove_overlap_between_bbox(spans)
  192. # 对tpye=["interline_equation", "image", "table"]进行额外处理,如果左边有字的话,将该span的bbox中y0调整至不高于文字的y0
  193. spans = adjust_bbox_for_standalone_block(spans)
  194. # 从ocr_page_info中解析layout信息(按自然阅读方向排序,并修复重叠和交错的bad case)
  195. layout_bboxes, layout_tree = layout_detect(ocr_page_info['subfield_dets'], page, ocr_page_info)
  196. # 将spans合并成line(在layout内,从上到下,从左到右)
  197. lines = merge_spans_to_line_by_layout(spans, layout_bboxes)
  198. # 将lines合并成block
  199. blocks = merge_lines_to_block(lines)
  200. # 根据block合并段落
  201. para_blocks = para_split(blocks, layout_bboxes)
  202. # 获取QA需要外置的list
  203. images, tables, interline_equations, inline_equations = get_qa_need_list(blocks)
  204. # 构造pdf_info_dict
  205. page_info = construct_page_component(blocks, para_blocks, layout_bboxes, page_id, page_w, page_h, layout_tree,
  206. images, tables, interline_equations, inline_equations,
  207. dropped_text_block, dropped_image_block, dropped_table_block,
  208. need_remove_spans_bboxes_dict)
  209. pdf_info_dict[f"page_{page_id}"] = page_info
  210. # 在测试时,保存调试信息
  211. if debug_mode:
  212. params_file_save_path = join_path(
  213. save_tmp_path, "md", book_name, "preproc_out.json"
  214. )
  215. with open(params_file_save_path, "w", encoding="utf-8") as f:
  216. json.dump(pdf_info_dict, f, ensure_ascii=False, indent=4)
  217. # drow_bbox
  218. draw_layout_bbox(pdf_info_dict, pdf_path, md_bookname_save_path)
  219. draw_text_bbox(pdf_info_dict, pdf_path, md_bookname_save_path)
  220. return pdf_info_dict