demo.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. __dir__ = os.path.dirname(os.path.abspath(__file__))
  9. pdf_file_name = os.path.join(__dir__, "pdfs", "demo1.pdf") # replace with the real pdf path
  10. name_without_extension = os.path.basename(pdf_file_name).split('.')[0]
  11. # prepare env
  12. local_image_dir = os.path.join(__dir__, "output", name_without_extension, "images")
  13. local_md_dir = os.path.join(__dir__, "output", name_without_extension)
  14. image_dir = str(os.path.basename(local_image_dir))
  15. os.makedirs(local_image_dir, exist_ok=True)
  16. image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
  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. ### get model inference result
  33. model_inference_result = infer_result.get_infer_res()
  34. ### draw layout result on each page
  35. pipe_result.draw_layout(os.path.join(local_md_dir, f"{name_without_extension}_layout.pdf"))
  36. ### draw spans result on each page
  37. pipe_result.draw_span(os.path.join(local_md_dir, f"{name_without_extension}_spans.pdf"))
  38. ### get markdown content
  39. md_content = pipe_result.get_markdown(image_dir)
  40. ### dump markdown
  41. pipe_result.dump_md(md_writer, f"{name_without_extension}.md", image_dir)
  42. ### get content list content
  43. content_list_content = pipe_result.get_content_list(image_dir)
  44. ### dump content list
  45. pipe_result.dump_content_list(md_writer, f"{name_without_extension}_content_list.json", image_dir)
  46. ### get middle json
  47. middle_json_content = pipe_result.get_middle_json()
  48. ### dump middle json
  49. pipe_result.dump_middle_json(md_writer, f'{name_without_extension}_middle.json')