doc_analyze_by_custom_model.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import os
  2. import time
  3. import fitz
  4. import numpy as np
  5. from loguru import logger
  6. os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新
  7. os.environ['YOLO_VERBOSE'] = 'False' # disable yolo logger
  8. try:
  9. import torchtext
  10. if torchtext.__version__ >= '0.18.0':
  11. torchtext.disable_torchtext_deprecation_warning()
  12. except ImportError:
  13. pass
  14. import magic_pdf.model as model_config
  15. from magic_pdf.data.dataset import Dataset
  16. from magic_pdf.libs.clean_memory import clean_memory
  17. from magic_pdf.libs.config_reader import (get_device, get_formula_config,
  18. get_layout_config,
  19. get_local_models_dir,
  20. get_table_recog_config)
  21. from magic_pdf.model.model_list import MODEL
  22. from magic_pdf.model.operators import InferenceResult
  23. def dict_compare(d1, d2):
  24. return d1.items() == d2.items()
  25. def remove_duplicates_dicts(lst):
  26. unique_dicts = []
  27. for dict_item in lst:
  28. if not any(
  29. dict_compare(dict_item, existing_dict) for existing_dict in unique_dicts
  30. ):
  31. unique_dicts.append(dict_item)
  32. return unique_dicts
  33. def load_images_from_pdf(
  34. pdf_bytes: bytes, dpi=200, start_page_id=0, end_page_id=None
  35. ) -> list:
  36. try:
  37. from PIL import Image
  38. except ImportError:
  39. logger.error('Pillow not installed, please install by pip.')
  40. exit(1)
  41. images = []
  42. with fitz.open('pdf', pdf_bytes) as doc:
  43. pdf_page_num = doc.page_count
  44. end_page_id = (
  45. end_page_id
  46. if end_page_id is not None and end_page_id >= 0
  47. else pdf_page_num - 1
  48. )
  49. if end_page_id > pdf_page_num - 1:
  50. logger.warning('end_page_id is out of range, use images length')
  51. end_page_id = pdf_page_num - 1
  52. for index in range(0, doc.page_count):
  53. if start_page_id <= index <= end_page_id:
  54. page = doc[index]
  55. mat = fitz.Matrix(dpi / 72, dpi / 72)
  56. pm = page.get_pixmap(matrix=mat, alpha=False)
  57. # If the width or height exceeds 4500 after scaling, do not scale further.
  58. if pm.width > 4500 or pm.height > 4500:
  59. pm = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
  60. img = Image.frombytes('RGB', (pm.width, pm.height), pm.samples)
  61. img = np.array(img)
  62. img_dict = {'img': img, 'width': pm.width, 'height': pm.height}
  63. else:
  64. img_dict = {'img': [], 'width': 0, 'height': 0}
  65. images.append(img_dict)
  66. return images
  67. class ModelSingleton:
  68. _instance = None
  69. _models = {}
  70. def __new__(cls, *args, **kwargs):
  71. if cls._instance is None:
  72. cls._instance = super().__new__(cls)
  73. return cls._instance
  74. def get_model(
  75. self,
  76. ocr: bool,
  77. show_log: bool,
  78. lang=None,
  79. layout_model=None,
  80. formula_enable=None,
  81. table_enable=None,
  82. ):
  83. key = (ocr, show_log, lang, layout_model, formula_enable, table_enable)
  84. if key not in self._models:
  85. self._models[key] = custom_model_init(
  86. ocr=ocr,
  87. show_log=show_log,
  88. lang=lang,
  89. layout_model=layout_model,
  90. formula_enable=formula_enable,
  91. table_enable=table_enable,
  92. )
  93. return self._models[key]
  94. def custom_model_init(
  95. ocr: bool = False,
  96. show_log: bool = False,
  97. lang=None,
  98. layout_model=None,
  99. formula_enable=None,
  100. table_enable=None,
  101. ):
  102. model = None
  103. if model_config.__model_mode__ == 'lite':
  104. logger.warning(
  105. 'The Lite mode is provided for developers to conduct testing only, and the output quality is '
  106. 'not guaranteed to be reliable.'
  107. )
  108. model = MODEL.Paddle
  109. elif model_config.__model_mode__ == 'full':
  110. model = MODEL.PEK
  111. if model_config.__use_inside_model__:
  112. model_init_start = time.time()
  113. if model == MODEL.Paddle:
  114. from magic_pdf.model.pp_structure_v2 import CustomPaddleModel
  115. custom_model = CustomPaddleModel(ocr=ocr, show_log=show_log, lang=lang)
  116. elif model == MODEL.PEK:
  117. from magic_pdf.model.pdf_extract_kit import CustomPEKModel
  118. # 从配置文件读取model-dir和device
  119. local_models_dir = get_local_models_dir()
  120. device = get_device()
  121. layout_config = get_layout_config()
  122. if layout_model is not None:
  123. layout_config['model'] = layout_model
  124. formula_config = get_formula_config()
  125. if formula_enable is not None:
  126. formula_config['enable'] = formula_enable
  127. table_config = get_table_recog_config()
  128. if table_enable is not None:
  129. table_config['enable'] = table_enable
  130. model_input = {
  131. 'ocr': ocr,
  132. 'show_log': show_log,
  133. 'models_dir': local_models_dir,
  134. 'device': device,
  135. 'table_config': table_config,
  136. 'layout_config': layout_config,
  137. 'formula_config': formula_config,
  138. 'lang': lang,
  139. }
  140. custom_model = CustomPEKModel(**model_input)
  141. else:
  142. logger.error('Not allow model_name!')
  143. exit(1)
  144. model_init_cost = time.time() - model_init_start
  145. logger.info(f'model init cost: {model_init_cost}')
  146. else:
  147. logger.error('use_inside_model is False, not allow to use inside model')
  148. exit(1)
  149. return custom_model
  150. def doc_analyze(
  151. dataset: Dataset,
  152. ocr: bool = False,
  153. show_log: bool = False,
  154. start_page_id=0,
  155. end_page_id=None,
  156. lang=None,
  157. layout_model=None,
  158. formula_enable=None,
  159. table_enable=None,
  160. ) -> InferenceResult:
  161. if lang == '':
  162. lang = None
  163. model_manager = ModelSingleton()
  164. custom_model = model_manager.get_model(
  165. ocr, show_log, lang, layout_model, formula_enable, table_enable
  166. )
  167. model_json = []
  168. doc_analyze_start = time.time()
  169. if end_page_id is None:
  170. end_page_id = len(dataset)
  171. for index in range(len(dataset)):
  172. page_data = dataset.get_page(index)
  173. img_dict = page_data.get_image()
  174. img = img_dict['img']
  175. page_width = img_dict['width']
  176. page_height = img_dict['height']
  177. if start_page_id <= index <= end_page_id:
  178. page_start = time.time()
  179. result = custom_model(img)
  180. logger.info(f'-----page_id : {index}, page total time: {round(time.time() - page_start, 2)}-----')
  181. else:
  182. result = []
  183. page_info = {'page_no': index, 'height': page_height, 'width': page_width}
  184. page_dict = {'layout_dets': result, 'page_info': page_info}
  185. model_json.append(page_dict)
  186. gc_start = time.time()
  187. clean_memory()
  188. gc_time = round(time.time() - gc_start, 2)
  189. logger.info(f'gc time: {gc_time}')
  190. doc_analyze_time = round(time.time() - doc_analyze_start, 2)
  191. doc_analyze_speed = round((end_page_id + 1 - start_page_id) / doc_analyze_time, 2)
  192. logger.info(
  193. f'doc analyze time: {round(time.time() - doc_analyze_start, 2)},'
  194. f' speed: {doc_analyze_speed} pages/second'
  195. )
  196. return InferenceResult(model_json, dataset)