common.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import io
  3. import json
  4. import os
  5. import copy
  6. from pathlib import Path
  7. from loguru import logger
  8. import pypdfium2 as pdfium
  9. from mineru.data.data_reader_writer import FileBasedDataWriter
  10. from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox, draw_line_sort_bbox
  11. from mineru.utils.enum_class import MakeMode
  12. from mineru.utils.guess_suffix_or_lang import guess_suffix_by_bytes
  13. from mineru.utils.pdf_image_tools import images_bytes_to_pdf_bytes
  14. from mineru.backend.vlm.vlm_middle_json_mkcontent import union_make as vlm_union_make
  15. from mineru.backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze
  16. from mineru.backend.vlm.vlm_analyze import aio_doc_analyze as aio_vlm_doc_analyze
  17. from mineru.utils.pdf_page_id import get_end_page_id
  18. pdf_suffixes = ["pdf"]
  19. image_suffixes = ["png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"]
  20. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  21. def read_fn(path):
  22. if not isinstance(path, Path):
  23. path = Path(path)
  24. with open(str(path), "rb") as input_file:
  25. file_bytes = input_file.read()
  26. file_suffix = guess_suffix_by_bytes(file_bytes, path)
  27. if file_suffix in image_suffixes:
  28. return images_bytes_to_pdf_bytes(file_bytes)
  29. elif file_suffix in pdf_suffixes:
  30. return file_bytes
  31. else:
  32. raise Exception(f"Unknown file suffix: {file_suffix}")
  33. def prepare_env(output_dir, pdf_file_name, parse_method):
  34. local_md_dir = str(os.path.join(output_dir, pdf_file_name, parse_method))
  35. local_image_dir = os.path.join(str(local_md_dir), "images")
  36. os.makedirs(local_image_dir, exist_ok=True)
  37. os.makedirs(local_md_dir, exist_ok=True)
  38. return local_image_dir, local_md_dir
  39. def convert_pdf_bytes_to_bytes_by_pypdfium2(pdf_bytes, start_page_id=0, end_page_id=None):
  40. pdf = pdfium.PdfDocument(pdf_bytes)
  41. output_pdf = pdfium.PdfDocument.new()
  42. try:
  43. end_page_id = get_end_page_id(end_page_id, len(pdf))
  44. # 逐页导入,失败则跳过
  45. output_index = 0
  46. for page_index in range(start_page_id, end_page_id + 1):
  47. try:
  48. output_pdf.import_pages(pdf, pages=[page_index])
  49. output_index += 1
  50. except Exception as page_error:
  51. output_pdf.del_page(output_index)
  52. logger.warning(f"Failed to import page {page_index}: {page_error}, skipping this page.")
  53. continue
  54. # 将新PDF保存到内存缓冲区
  55. output_buffer = io.BytesIO()
  56. output_pdf.save(output_buffer)
  57. # 获取字节数据
  58. output_bytes = output_buffer.getvalue()
  59. except Exception as e:
  60. logger.warning(f"Error in converting PDF bytes: {e}, Using original PDF bytes.")
  61. output_bytes = pdf_bytes
  62. pdf.close()
  63. output_pdf.close()
  64. return output_bytes
  65. def _prepare_pdf_bytes(pdf_bytes_list, start_page_id, end_page_id):
  66. """准备处理PDF字节数据"""
  67. result = []
  68. for pdf_bytes in pdf_bytes_list:
  69. new_pdf_bytes = convert_pdf_bytes_to_bytes_by_pypdfium2(pdf_bytes, start_page_id, end_page_id)
  70. result.append(new_pdf_bytes)
  71. return result
  72. def _process_output(
  73. pdf_info,
  74. pdf_bytes,
  75. pdf_file_name,
  76. local_md_dir,
  77. local_image_dir,
  78. md_writer,
  79. f_draw_layout_bbox,
  80. f_draw_span_bbox,
  81. f_dump_orig_pdf,
  82. f_dump_md,
  83. f_dump_content_list,
  84. f_dump_middle_json,
  85. f_dump_model_output,
  86. f_make_md_mode,
  87. middle_json,
  88. model_output=None,
  89. is_pipeline=True
  90. ):
  91. f_draw_line_sort_bbox = False
  92. from mineru.backend.pipeline.pipeline_middle_json_mkcontent import union_make as pipeline_union_make
  93. """处理输出文件"""
  94. if f_draw_layout_bbox:
  95. draw_layout_bbox(pdf_info, pdf_bytes, local_md_dir, f"{pdf_file_name}_layout.pdf")
  96. if f_draw_span_bbox:
  97. draw_span_bbox(pdf_info, pdf_bytes, local_md_dir, f"{pdf_file_name}_span.pdf")
  98. if f_dump_orig_pdf:
  99. md_writer.write(
  100. f"{pdf_file_name}_origin.pdf",
  101. pdf_bytes,
  102. )
  103. if f_draw_line_sort_bbox:
  104. draw_line_sort_bbox(pdf_info, pdf_bytes, local_md_dir, f"{pdf_file_name}_line_sort.pdf")
  105. image_dir = str(os.path.basename(local_image_dir))
  106. if f_dump_md:
  107. make_func = pipeline_union_make if is_pipeline else vlm_union_make
  108. md_content_str = make_func(pdf_info, f_make_md_mode, image_dir)
  109. md_writer.write_string(
  110. f"{pdf_file_name}.md",
  111. md_content_str,
  112. )
  113. if f_dump_content_list:
  114. make_func = pipeline_union_make if is_pipeline else vlm_union_make
  115. content_list = make_func(pdf_info, MakeMode.CONTENT_LIST, image_dir)
  116. md_writer.write_string(
  117. f"{pdf_file_name}_content_list.json",
  118. json.dumps(content_list, ensure_ascii=False, indent=4),
  119. )
  120. if f_dump_middle_json:
  121. md_writer.write_string(
  122. f"{pdf_file_name}_middle.json",
  123. json.dumps(middle_json, ensure_ascii=False, indent=4),
  124. )
  125. if f_dump_model_output:
  126. md_writer.write_string(
  127. f"{pdf_file_name}_model.json",
  128. json.dumps(model_output, ensure_ascii=False, indent=4),
  129. )
  130. logger.info(f"local output dir is {local_md_dir}")
  131. def _process_pipeline(
  132. output_dir,
  133. pdf_file_names,
  134. pdf_bytes_list,
  135. p_lang_list,
  136. parse_method,
  137. p_formula_enable,
  138. p_table_enable,
  139. f_draw_layout_bbox,
  140. f_draw_span_bbox,
  141. f_dump_md,
  142. f_dump_middle_json,
  143. f_dump_model_output,
  144. f_dump_orig_pdf,
  145. f_dump_content_list,
  146. f_make_md_mode,
  147. ):
  148. """处理pipeline后端逻辑"""
  149. from mineru.backend.pipeline.model_json_to_middle_json import result_to_middle_json as pipeline_result_to_middle_json
  150. from mineru.backend.pipeline.pipeline_analyze import doc_analyze as pipeline_doc_analyze
  151. infer_results, all_image_lists, all_pdf_docs, lang_list, ocr_enabled_list = (
  152. pipeline_doc_analyze(
  153. pdf_bytes_list, p_lang_list, parse_method=parse_method,
  154. formula_enable=p_formula_enable, table_enable=p_table_enable
  155. )
  156. )
  157. for idx, model_list in enumerate(infer_results):
  158. model_json = copy.deepcopy(model_list)
  159. pdf_file_name = pdf_file_names[idx]
  160. local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
  161. image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
  162. images_list = all_image_lists[idx]
  163. pdf_doc = all_pdf_docs[idx]
  164. _lang = lang_list[idx]
  165. _ocr_enable = ocr_enabled_list[idx]
  166. middle_json = pipeline_result_to_middle_json(
  167. model_list, images_list, pdf_doc, image_writer,
  168. _lang, _ocr_enable, p_formula_enable
  169. )
  170. pdf_info = middle_json["pdf_info"]
  171. pdf_bytes = pdf_bytes_list[idx]
  172. _process_output(
  173. pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
  174. md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
  175. f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
  176. f_make_md_mode, middle_json, model_json, is_pipeline=True
  177. )
  178. async def _async_process_vlm(
  179. output_dir,
  180. pdf_file_names,
  181. pdf_bytes_list,
  182. backend,
  183. f_draw_layout_bbox,
  184. f_draw_span_bbox,
  185. f_dump_md,
  186. f_dump_middle_json,
  187. f_dump_model_output,
  188. f_dump_orig_pdf,
  189. f_dump_content_list,
  190. f_make_md_mode,
  191. server_url=None,
  192. **kwargs,
  193. ):
  194. """异步处理VLM后端逻辑"""
  195. parse_method = "vlm"
  196. f_draw_span_bbox = False
  197. if not backend.endswith("client"):
  198. server_url = None
  199. for idx, pdf_bytes in enumerate(pdf_bytes_list):
  200. pdf_file_name = pdf_file_names[idx]
  201. local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
  202. image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
  203. middle_json, infer_result = await aio_vlm_doc_analyze(
  204. pdf_bytes, image_writer=image_writer, backend=backend, server_url=server_url, **kwargs,
  205. )
  206. pdf_info = middle_json["pdf_info"]
  207. _process_output(
  208. pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
  209. md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
  210. f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
  211. f_make_md_mode, middle_json, infer_result, is_pipeline=False
  212. )
  213. def _process_vlm(
  214. output_dir,
  215. pdf_file_names,
  216. pdf_bytes_list,
  217. backend,
  218. f_draw_layout_bbox,
  219. f_draw_span_bbox,
  220. f_dump_md,
  221. f_dump_middle_json,
  222. f_dump_model_output,
  223. f_dump_orig_pdf,
  224. f_dump_content_list,
  225. f_make_md_mode,
  226. server_url=None,
  227. **kwargs,
  228. ):
  229. """同步处理VLM后端逻辑"""
  230. parse_method = "vlm"
  231. f_draw_span_bbox = False
  232. if not backend.endswith("client"):
  233. server_url = None
  234. for idx, pdf_bytes in enumerate(pdf_bytes_list):
  235. pdf_file_name = pdf_file_names[idx]
  236. local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
  237. image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
  238. middle_json, infer_result = vlm_doc_analyze(
  239. pdf_bytes, image_writer=image_writer, backend=backend, server_url=server_url, **kwargs,
  240. )
  241. pdf_info = middle_json["pdf_info"]
  242. _process_output(
  243. pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
  244. md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
  245. f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
  246. f_make_md_mode, middle_json, infer_result, is_pipeline=False
  247. )
  248. def do_parse(
  249. output_dir,
  250. pdf_file_names: list[str],
  251. pdf_bytes_list: list[bytes],
  252. p_lang_list: list[str],
  253. backend="pipeline",
  254. parse_method="auto",
  255. formula_enable=True,
  256. table_enable=True,
  257. server_url=None,
  258. f_draw_layout_bbox=True,
  259. f_draw_span_bbox=True,
  260. f_dump_md=True,
  261. f_dump_middle_json=True,
  262. f_dump_model_output=True,
  263. f_dump_orig_pdf=True,
  264. f_dump_content_list=True,
  265. f_make_md_mode=MakeMode.MM_MD,
  266. start_page_id=0,
  267. end_page_id=None,
  268. **kwargs,
  269. ):
  270. # 预处理PDF字节数据
  271. pdf_bytes_list = _prepare_pdf_bytes(pdf_bytes_list, start_page_id, end_page_id)
  272. if backend == "pipeline":
  273. _process_pipeline(
  274. output_dir, pdf_file_names, pdf_bytes_list, p_lang_list,
  275. parse_method, formula_enable, table_enable,
  276. f_draw_layout_bbox, f_draw_span_bbox, f_dump_md, f_dump_middle_json,
  277. f_dump_model_output, f_dump_orig_pdf, f_dump_content_list, f_make_md_mode
  278. )
  279. else:
  280. if backend.startswith("vlm-"):
  281. backend = backend[4:]
  282. if backend == "vllm-async-engine":
  283. raise Exception("vlm-vllm-async-engine backend is not supported in sync mode, please use vlm-vllm-engine backend")
  284. os.environ['MINERU_VLM_FORMULA_ENABLE'] = str(formula_enable)
  285. os.environ['MINERU_VLM_TABLE_ENABLE'] = str(table_enable)
  286. _process_vlm(
  287. output_dir, pdf_file_names, pdf_bytes_list, backend,
  288. f_draw_layout_bbox, f_draw_span_bbox, f_dump_md, f_dump_middle_json,
  289. f_dump_model_output, f_dump_orig_pdf, f_dump_content_list, f_make_md_mode,
  290. server_url, **kwargs,
  291. )
  292. async def aio_do_parse(
  293. output_dir,
  294. pdf_file_names: list[str],
  295. pdf_bytes_list: list[bytes],
  296. p_lang_list: list[str],
  297. backend="pipeline",
  298. parse_method="auto",
  299. formula_enable=True,
  300. table_enable=True,
  301. server_url=None,
  302. f_draw_layout_bbox=True,
  303. f_draw_span_bbox=True,
  304. f_dump_md=True,
  305. f_dump_middle_json=True,
  306. f_dump_model_output=True,
  307. f_dump_orig_pdf=True,
  308. f_dump_content_list=True,
  309. f_make_md_mode=MakeMode.MM_MD,
  310. start_page_id=0,
  311. end_page_id=None,
  312. **kwargs,
  313. ):
  314. # 预处理PDF字节数据
  315. pdf_bytes_list = _prepare_pdf_bytes(pdf_bytes_list, start_page_id, end_page_id)
  316. if backend == "pipeline":
  317. # pipeline模式暂不支持异步,使用同步处理方式
  318. _process_pipeline(
  319. output_dir, pdf_file_names, pdf_bytes_list, p_lang_list,
  320. parse_method, formula_enable, table_enable,
  321. f_draw_layout_bbox, f_draw_span_bbox, f_dump_md, f_dump_middle_json,
  322. f_dump_model_output, f_dump_orig_pdf, f_dump_content_list, f_make_md_mode
  323. )
  324. else:
  325. if backend.startswith("vlm-"):
  326. backend = backend[4:]
  327. if backend == "vllm-engine":
  328. raise Exception("vlm-vllm-engine backend is not supported in async mode, please use vlm-vllm-async-engine backend")
  329. os.environ['MINERU_VLM_FORMULA_ENABLE'] = str(formula_enable)
  330. os.environ['MINERU_VLM_TABLE_ENABLE'] = str(table_enable)
  331. await _async_process_vlm(
  332. output_dir, pdf_file_names, pdf_bytes_list, backend,
  333. f_draw_layout_bbox, f_draw_span_bbox, f_dump_md, f_dump_middle_json,
  334. f_dump_model_output, f_dump_orig_pdf, f_dump_content_list, f_make_md_mode,
  335. server_url, **kwargs,
  336. )
  337. if __name__ == "__main__":
  338. # pdf_path = "../../demo/pdfs/demo3.pdf"
  339. pdf_path = "C:/Users/zhaoxiaomeng/Downloads/4546d0e2-ba60-40a5-a17e-b68555cec741.pdf"
  340. try:
  341. do_parse("./output", [Path(pdf_path).stem], [read_fn(Path(pdf_path))],["ch"],
  342. end_page_id=10,
  343. backend='vlm-huggingface'
  344. # backend = 'pipeline'
  345. )
  346. except Exception as e:
  347. logger.exception(e)