demo.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. image_dir = str(os.path.basename(local_image_dir))
  18. # read bytes
  19. reader1 = FileBasedDataReader("")
  20. pdf_bytes = reader1.read(pdf_file_name) # read the pdf content
  21. # proc
  22. ## Create Dataset Instance
  23. ds = PymuDocDataset(pdf_bytes)
  24. ## inference
  25. if ds.classify() == SupportedPdfParseMethod.OCR:
  26. infer_result = ds.apply(doc_analyze, ocr=True)
  27. ## pipeline
  28. pipe_result = infer_result.pipe_ocr_mode(image_writer)
  29. else:
  30. infer_result = ds.apply(doc_analyze, ocr=False)
  31. ## pipeline
  32. pipe_result = infer_result.pipe_txt_mode(image_writer)
  33. ### draw model result on each page
  34. infer_result.draw_model(os.path.join(local_md_dir, f"{name_without_suff}_model.pdf"))
  35. ### draw layout result on each page
  36. pipe_result.draw_layout(os.path.join(local_md_dir, f"{name_without_suff}_layout.pdf"))
  37. ### draw spans result on each page
  38. pipe_result.draw_span(os.path.join(local_md_dir, f"{name_without_suff}_spans.pdf"))
  39. ### dump markdown
  40. pipe_result.dump_md(md_writer, f"{name_without_suff}.md", image_dir)
  41. ### dump content list
  42. pipe_result.dump_content_list(md_writer, f"{name_without_suff}_content_list.json", image_dir)