UNIPipe.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import json
  2. from loguru import logger
  3. from magic_pdf.io.AbsReaderWriter import AbsReaderWriter
  4. from magic_pdf.io.DiskReaderWriter import DiskReaderWriter
  5. from magic_pdf.libs.commons import join_path
  6. from magic_pdf.libs.json_compressor import JsonCompressor
  7. from magic_pdf.pipe.AbsPipe import AbsPipe
  8. from magic_pdf.user_api import parse_union_pdf, parse_ocr_pdf
  9. class UNIPipe(AbsPipe):
  10. def __init__(self, pdf_bytes: bytes, model_list: list, image_writer: AbsReaderWriter, img_bucket_path: str):
  11. self.pdf_type = "ocr"
  12. self.compressed_pdf_mid_data = None
  13. self.pdf_mid_data = None
  14. self.pdf_bytes = pdf_bytes
  15. self.model_list = model_list
  16. self.image_writer = image_writer
  17. self.img_bucket_path = img_bucket_path
  18. def pipe_classify(self):
  19. self.pdf_type = UNIPipe.classify(self.pdf_bytes)
  20. def pipe_parse(self):
  21. if self.pdf_type == "txt":
  22. self.pdf_mid_data = parse_union_pdf(pdf_bytes, self.model_list, self.image_writer)
  23. elif self.pdf_type == "ocr":
  24. self.pdf_mid_data = parse_ocr_pdf(pdf_bytes, self.model_list, self.image_writer)
  25. self.compressed_pdf_mid_data = JsonCompressor.compress_json(self.pdf_mid_data)
  26. def pipe_mk_uni_format(self):
  27. content_list = AbsPipe.mk_uni_format(self.compressed_pdf_mid_data, self.img_bucket_path)
  28. return content_list
  29. def pipe_mk_markdown(self):
  30. markdown_content = AbsPipe.mk_markdown(self.compressed_pdf_mid_data, self.img_bucket_path)
  31. return markdown_content
  32. if __name__ == '__main__':
  33. # 测试
  34. drw = DiskReaderWriter(r"D:/project/20231108code-clean")
  35. pdf_file_path = r"linshixuqiu\19983-00.pdf"
  36. model_file_path = r"linshixuqiu\19983-00.json"
  37. pdf_bytes = drw.read(pdf_file_path, AbsReaderWriter.MODE_BIN)
  38. model_json_txt = drw.read(model_file_path, AbsReaderWriter.MODE_TXT)
  39. model_list = json.loads(model_json_txt)
  40. write_path = r"D:\project\20231108code-clean\linshixuqiu\19983-00"
  41. img_bucket_path = "imgs"
  42. img_writer = DiskReaderWriter(join_path(write_path, img_bucket_path))
  43. pipe = UNIPipe(pdf_bytes, model_list, img_writer, img_bucket_path)
  44. pipe.pipe_classify()
  45. pipe.pipe_parse()
  46. md_content = pipe.pipe_mk_markdown()
  47. try:
  48. content_list = pipe.pipe_mk_uni_format()
  49. except Exception as e:
  50. logger.exception(e)
  51. md_writer = DiskReaderWriter(write_path)
  52. md_writer.write(md_content, "19983-00.md", AbsReaderWriter.MODE_TXT)
  53. md_writer.write(json.dumps(pipe.pdf_mid_data, ensure_ascii=False, indent=4), "19983-00.json", AbsReaderWriter.MODE_TXT)
  54. md_writer.write(str(content_list), "19983-00.txt", AbsReaderWriter.MODE_TXT)