doc_analyze_by_custom_model.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import os
  2. import time
  3. import torch
  4. os.environ['FLAGS_npu_jit_compile'] = '0' # 关闭paddle的jit编译
  5. os.environ['FLAGS_use_stride_kernel'] = '0'
  6. os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 让mps可以fallback
  7. os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新
  8. # 关闭paddle的信号处理
  9. import paddle
  10. paddle.disable_signal_handler()
  11. from loguru import logger
  12. from magic_pdf.model.batch_analyze import BatchAnalyze
  13. from magic_pdf.model.sub_modules.model_utils import get_vram
  14. try:
  15. import torchtext
  16. if torchtext.__version__ >= '0.18.0':
  17. torchtext.disable_torchtext_deprecation_warning()
  18. except ImportError:
  19. pass
  20. import magic_pdf.model as model_config
  21. from magic_pdf.data.dataset import Dataset
  22. from magic_pdf.libs.clean_memory import clean_memory
  23. from magic_pdf.libs.config_reader import (get_device, get_formula_config,
  24. get_layout_config,
  25. get_local_models_dir,
  26. get_table_recog_config)
  27. from magic_pdf.model.model_list import MODEL
  28. from magic_pdf.operators.models import InferenceResult
  29. class ModelSingleton:
  30. _instance = None
  31. _models = {}
  32. def __new__(cls, *args, **kwargs):
  33. if cls._instance is None:
  34. cls._instance = super().__new__(cls)
  35. return cls._instance
  36. def get_model(
  37. self,
  38. ocr: bool,
  39. show_log: bool,
  40. lang=None,
  41. layout_model=None,
  42. formula_enable=None,
  43. table_enable=None,
  44. ):
  45. key = (ocr, show_log, lang, layout_model, formula_enable, table_enable)
  46. if key not in self._models:
  47. self._models[key] = custom_model_init(
  48. ocr=ocr,
  49. show_log=show_log,
  50. lang=lang,
  51. layout_model=layout_model,
  52. formula_enable=formula_enable,
  53. table_enable=table_enable,
  54. )
  55. return self._models[key]
  56. def custom_model_init(
  57. ocr: bool = False,
  58. show_log: bool = False,
  59. lang=None,
  60. layout_model=None,
  61. formula_enable=None,
  62. table_enable=None,
  63. ):
  64. model = None
  65. if model_config.__model_mode__ == 'lite':
  66. logger.warning(
  67. 'The Lite mode is provided for developers to conduct testing only, and the output quality is '
  68. 'not guaranteed to be reliable.'
  69. )
  70. model = MODEL.Paddle
  71. elif model_config.__model_mode__ == 'full':
  72. model = MODEL.PEK
  73. if model_config.__use_inside_model__:
  74. model_init_start = time.time()
  75. if model == MODEL.Paddle:
  76. from magic_pdf.model.pp_structure_v2 import CustomPaddleModel
  77. custom_model = CustomPaddleModel(ocr=ocr, show_log=show_log, lang=lang)
  78. elif model == MODEL.PEK:
  79. from magic_pdf.model.pdf_extract_kit import CustomPEKModel
  80. # 从配置文件读取model-dir和device
  81. local_models_dir = get_local_models_dir()
  82. device = get_device()
  83. layout_config = get_layout_config()
  84. if layout_model is not None:
  85. layout_config['model'] = layout_model
  86. formula_config = get_formula_config()
  87. if formula_enable is not None:
  88. formula_config['enable'] = formula_enable
  89. table_config = get_table_recog_config()
  90. if table_enable is not None:
  91. table_config['enable'] = table_enable
  92. model_input = {
  93. 'ocr': ocr,
  94. 'show_log': show_log,
  95. 'models_dir': local_models_dir,
  96. 'device': device,
  97. 'table_config': table_config,
  98. 'layout_config': layout_config,
  99. 'formula_config': formula_config,
  100. 'lang': lang,
  101. }
  102. custom_model = CustomPEKModel(**model_input)
  103. else:
  104. logger.error('Not allow model_name!')
  105. exit(1)
  106. model_init_cost = time.time() - model_init_start
  107. logger.info(f'model init cost: {model_init_cost}')
  108. else:
  109. logger.error('use_inside_model is False, not allow to use inside model')
  110. exit(1)
  111. return custom_model
  112. def doc_analyze(
  113. dataset: Dataset,
  114. ocr: bool = False,
  115. show_log: bool = False,
  116. start_page_id=0,
  117. end_page_id=None,
  118. lang=None,
  119. layout_model=None,
  120. formula_enable=None,
  121. table_enable=None,
  122. ) -> InferenceResult:
  123. end_page_id = end_page_id if end_page_id is not None else len(dataset) - 1
  124. model_manager = ModelSingleton()
  125. custom_model = model_manager.get_model(
  126. ocr, show_log, lang, layout_model, formula_enable, table_enable
  127. )
  128. batch_analyze = False
  129. device = get_device()
  130. npu_support = False
  131. if str(device).startswith("npu"):
  132. import torch_npu
  133. if torch_npu.npu.is_available():
  134. npu_support = True
  135. if torch.cuda.is_available() and device != 'cpu' or npu_support:
  136. gpu_memory = int(os.getenv("VIRTUAL_VRAM_SIZE", round(get_vram(device))))
  137. if gpu_memory is not None and gpu_memory >= 8:
  138. if gpu_memory >= 40:
  139. batch_ratio = 32
  140. elif gpu_memory >=20:
  141. batch_ratio = 16
  142. elif gpu_memory >= 16:
  143. batch_ratio = 8
  144. elif gpu_memory >= 10:
  145. batch_ratio = 4
  146. else:
  147. batch_ratio = 2
  148. logger.info(f'gpu_memory: {gpu_memory} GB, batch_ratio: {batch_ratio}')
  149. batch_model = BatchAnalyze(model=custom_model, batch_ratio=batch_ratio)
  150. batch_analyze = True
  151. model_json = []
  152. doc_analyze_start = time.time()
  153. if batch_analyze:
  154. # batch analyze
  155. images = []
  156. for index in range(len(dataset)):
  157. if start_page_id <= index <= end_page_id:
  158. page_data = dataset.get_page(index)
  159. img_dict = page_data.get_image()
  160. images.append(img_dict['img'])
  161. analyze_result = batch_model(images)
  162. for index in range(len(dataset)):
  163. page_data = dataset.get_page(index)
  164. img_dict = page_data.get_image()
  165. page_width = img_dict['width']
  166. page_height = img_dict['height']
  167. if start_page_id <= index <= end_page_id:
  168. result = analyze_result.pop(0)
  169. else:
  170. result = []
  171. page_info = {'page_no': index, 'height': page_height, 'width': page_width}
  172. page_dict = {'layout_dets': result, 'page_info': page_info}
  173. model_json.append(page_dict)
  174. else:
  175. # single analyze
  176. for index in range(len(dataset)):
  177. page_data = dataset.get_page(index)
  178. img_dict = page_data.get_image()
  179. img = img_dict['img']
  180. page_width = img_dict['width']
  181. page_height = img_dict['height']
  182. if start_page_id <= index <= end_page_id:
  183. page_start = time.time()
  184. result = custom_model(img)
  185. logger.info(f'-----page_id : {index}, page total time: {round(time.time() - page_start, 2)}-----')
  186. else:
  187. result = []
  188. page_info = {'page_no': index, 'height': page_height, 'width': page_width}
  189. page_dict = {'layout_dets': result, 'page_info': page_info}
  190. model_json.append(page_dict)
  191. gc_start = time.time()
  192. clean_memory(get_device())
  193. gc_time = round(time.time() - gc_start, 2)
  194. logger.info(f'gc time: {gc_time}')
  195. doc_analyze_time = round(time.time() - doc_analyze_start, 2)
  196. doc_analyze_speed = round((end_page_id + 1 - start_page_id) / doc_analyze_time, 2)
  197. logger.info(
  198. f'doc analyze time: {round(time.time() - doc_analyze_start, 2)},'
  199. f' speed: {doc_analyze_speed} pages/second'
  200. )
  201. return InferenceResult(model_json, dataset)