doc_analyze_by_custom_model.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import time
  2. import fitz
  3. import numpy as np
  4. from loguru import logger
  5. from magic_pdf.libs.clean_memory import clean_memory
  6. from magic_pdf.libs.config_reader import get_local_models_dir, get_device, get_table_recog_config
  7. from magic_pdf.model.model_list import MODEL
  8. import magic_pdf.model as model_config
  9. def dict_compare(d1, d2):
  10. return d1.items() == d2.items()
  11. def remove_duplicates_dicts(lst):
  12. unique_dicts = []
  13. for dict_item in lst:
  14. if not any(
  15. dict_compare(dict_item, existing_dict) for existing_dict in unique_dicts
  16. ):
  17. unique_dicts.append(dict_item)
  18. return unique_dicts
  19. def load_images_from_pdf(pdf_bytes: bytes, dpi=200, start_page_id=0, end_page_id=None) -> list:
  20. try:
  21. from PIL import Image
  22. except ImportError:
  23. logger.error("Pillow not installed, please install by pip.")
  24. exit(1)
  25. images = []
  26. with fitz.open("pdf", pdf_bytes) as doc:
  27. pdf_page_num = doc.page_count
  28. end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else pdf_page_num - 1
  29. if end_page_id > pdf_page_num - 1:
  30. logger.warning("end_page_id is out of range, use images length")
  31. end_page_id = pdf_page_num - 1
  32. for index in range(0, doc.page_count):
  33. if start_page_id <= index <= end_page_id:
  34. page = doc[index]
  35. mat = fitz.Matrix(dpi / 72, dpi / 72)
  36. pm = page.get_pixmap(matrix=mat, alpha=False)
  37. # If the width or height exceeds 9000 after scaling, do not scale further.
  38. if pm.width > 9000 or pm.height > 9000:
  39. pm = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
  40. img = Image.frombytes("RGB", (pm.width, pm.height), pm.samples)
  41. img = np.array(img)
  42. img_dict = {"img": img, "width": pm.width, "height": pm.height}
  43. else:
  44. img_dict = {"img": [], "width": 0, "height": 0}
  45. images.append(img_dict)
  46. return images
  47. class ModelSingleton:
  48. _instance = None
  49. _models = {}
  50. def __new__(cls, *args, **kwargs):
  51. if cls._instance is None:
  52. cls._instance = super().__new__(cls)
  53. return cls._instance
  54. def get_model(self, ocr: bool, show_log: bool, lang=None):
  55. key = (ocr, show_log, lang)
  56. if key not in self._models:
  57. self._models[key] = custom_model_init(ocr=ocr, show_log=show_log, lang=lang)
  58. return self._models[key]
  59. def custom_model_init(ocr: bool = False, show_log: bool = False, lang=None):
  60. model = None
  61. if model_config.__model_mode__ == "lite":
  62. logger.warning("The Lite mode is provided for developers to conduct testing only, and the output quality is "
  63. "not guaranteed to be reliable.")
  64. model = MODEL.Paddle
  65. elif model_config.__model_mode__ == "full":
  66. model = MODEL.PEK
  67. if model_config.__use_inside_model__:
  68. model_init_start = time.time()
  69. if model == MODEL.Paddle:
  70. from magic_pdf.model.pp_structure_v2 import CustomPaddleModel
  71. custom_model = CustomPaddleModel(ocr=ocr, show_log=show_log, lang=lang)
  72. elif model == MODEL.PEK:
  73. from magic_pdf.model.pdf_extract_kit import CustomPEKModel
  74. # 从配置文件读取model-dir和device
  75. local_models_dir = get_local_models_dir()
  76. device = get_device()
  77. table_config = get_table_recog_config()
  78. model_input = {"ocr": ocr,
  79. "show_log": show_log,
  80. "models_dir": local_models_dir,
  81. "device": device,
  82. "table_config": table_config,
  83. "lang": lang,
  84. }
  85. custom_model = CustomPEKModel(**model_input)
  86. else:
  87. logger.error("Not allow model_name!")
  88. exit(1)
  89. model_init_cost = time.time() - model_init_start
  90. logger.info(f"model init cost: {model_init_cost}")
  91. else:
  92. logger.error("use_inside_model is False, not allow to use inside model")
  93. exit(1)
  94. return custom_model
  95. def doc_analyze(pdf_bytes: bytes, ocr: bool = False, show_log: bool = False,
  96. start_page_id=0, end_page_id=None, lang=None):
  97. model_manager = ModelSingleton()
  98. custom_model = model_manager.get_model(ocr, show_log, lang)
  99. with fitz.open("pdf", pdf_bytes) as doc:
  100. pdf_page_num = doc.page_count
  101. end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else pdf_page_num - 1
  102. if end_page_id > pdf_page_num - 1:
  103. logger.warning("end_page_id is out of range, use images length")
  104. end_page_id = pdf_page_num - 1
  105. images = load_images_from_pdf(pdf_bytes, start_page_id=start_page_id, end_page_id=end_page_id)
  106. model_json = []
  107. doc_analyze_start = time.time()
  108. for index, img_dict in enumerate(images):
  109. img = img_dict["img"]
  110. page_width = img_dict["width"]
  111. page_height = img_dict["height"]
  112. if start_page_id <= index <= end_page_id:
  113. result = custom_model(img)
  114. else:
  115. result = []
  116. page_info = {"page_no": index, "height": page_height, "width": page_width}
  117. page_dict = {"layout_dets": result, "page_info": page_info}
  118. model_json.append(page_dict)
  119. gc_start = time.time()
  120. clean_memory()
  121. gc_time = round(time.time() - gc_start, 2)
  122. logger.info(f"gc time: {gc_time}")
  123. doc_analyze_time = round(time.time() - doc_analyze_start, 2)
  124. doc_analyze_speed = round( (end_page_id + 1 - start_page_id) / doc_analyze_time, 2)
  125. logger.info(f"doc analyze time: {round(time.time() - doc_analyze_start, 2)},"
  126. f" speed: {doc_analyze_speed} pages/second")
  127. return model_json