demo.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import os
  3. from magic_pdf.data.data_reader_writer import FileBasedDataWriter, FileBasedDataReader
  4. from magic_pdf.data.dataset import PymuDocDataset
  5. from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
  6. from magic_pdf.config.enums import SupportedPdfParseMethod
  7. # args
  8. pdf_file_name = "demo1.pdf" # replace with the real pdf path
  9. name_without_suff = pdf_file_name.split(".")[0]
  10. # prepare env
  11. local_image_dir, local_md_dir = "output/images", "output"
  12. image_dir = str(os.path.basename(local_image_dir))
  13. os.makedirs(local_image_dir, exist_ok=True)
  14. image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(
  15. local_md_dir
  16. )
  17. # read bytes
  18. reader1 = FileBasedDataReader("")
  19. pdf_bytes = reader1.read(pdf_file_name) # read the pdf content
  20. # proc
  21. ## Create Dataset Instance
  22. ds = PymuDocDataset(pdf_bytes)
  23. ## inference
  24. if ds.classify() == SupportedPdfParseMethod.OCR:
  25. infer_result = ds.apply(doc_analyze, ocr=True)
  26. ## pipeline
  27. pipe_result = infer_result.pipe_ocr_mode(image_writer)
  28. else:
  29. infer_result = ds.apply(doc_analyze, ocr=False)
  30. ## pipeline
  31. pipe_result = infer_result.pipe_txt_mode(image_writer)
  32. ### draw model result on each page
  33. infer_result.draw_model(os.path.join(local_md_dir, f"{name_without_suff}_model.pdf"))
  34. ### get model inference result
  35. model_inference_result = infer_result.get_infer_res()
  36. ### draw layout result on each page
  37. pipe_result.draw_layout(os.path.join(local_md_dir, f"{name_without_suff}_layout.pdf"))
  38. ### draw spans result on each page
  39. pipe_result.draw_span(os.path.join(local_md_dir, f"{name_without_suff}_spans.pdf"))
  40. ### get markdown content
  41. md_content = pipe_result.get_markdown(image_dir)
  42. ### dump markdown
  43. pipe_result.dump_md(md_writer, f"{name_without_suff}.md", image_dir)
  44. ### get content list content
  45. content_list_content = pipe_result.get_content_list(image_dir)
  46. ### dump content list
  47. pipe_result.dump_content_list(md_writer, f"{name_without_suff}_content_list.json", image_dir)
  48. ### get middle json
  49. middle_json_content = pipe_result.get_middle_json()
  50. ### dump middle json
  51. pipe_result.dump_middle_json(md_writer, f'{name_without_suff}_middle.json')