doc_analyze_by_custom_model.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import os
  2. import time
  3. import numpy as np
  4. import torch
  5. os.environ['FLAGS_npu_jit_compile'] = '0' # 关闭paddle的jit编译
  6. os.environ['FLAGS_use_stride_kernel'] = '0'
  7. os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 让mps可以fallback
  8. os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新
  9. from loguru import logger
  10. from magic_pdf.model.sub_modules.model_utils import get_vram
  11. from magic_pdf.config.enums import SupportedPdfParseMethod
  12. import magic_pdf.model as model_config
  13. from magic_pdf.data.dataset import Dataset
  14. from magic_pdf.libs.clean_memory import clean_memory
  15. from magic_pdf.libs.config_reader import (get_device, get_formula_config,
  16. get_layout_config,
  17. get_local_models_dir,
  18. get_table_recog_config)
  19. from magic_pdf.model.model_list import MODEL
  20. class ModelSingleton:
  21. _instance = None
  22. _models = {}
  23. def __new__(cls, *args, **kwargs):
  24. if cls._instance is None:
  25. cls._instance = super().__new__(cls)
  26. return cls._instance
  27. def get_model(
  28. self,
  29. ocr: bool,
  30. show_log: bool,
  31. lang=None,
  32. layout_model=None,
  33. formula_enable=None,
  34. table_enable=None,
  35. ):
  36. key = (ocr, show_log, lang, layout_model, formula_enable, table_enable)
  37. if key not in self._models:
  38. self._models[key] = custom_model_init(
  39. ocr=ocr,
  40. show_log=show_log,
  41. lang=lang,
  42. layout_model=layout_model,
  43. formula_enable=formula_enable,
  44. table_enable=table_enable,
  45. )
  46. return self._models[key]
  47. def custom_model_init(
  48. ocr: bool = False,
  49. show_log: bool = False,
  50. lang=None,
  51. layout_model=None,
  52. formula_enable=None,
  53. table_enable=None,
  54. ):
  55. model = None
  56. if model_config.__model_mode__ == 'lite':
  57. logger.warning(
  58. 'The Lite mode is provided for developers to conduct testing only, and the output quality is '
  59. 'not guaranteed to be reliable.'
  60. )
  61. model = MODEL.Paddle
  62. elif model_config.__model_mode__ == 'full':
  63. model = MODEL.PEK
  64. if model_config.__use_inside_model__:
  65. model_init_start = time.time()
  66. if model == MODEL.Paddle:
  67. from magic_pdf.model.pp_structure_v2 import CustomPaddleModel
  68. custom_model = CustomPaddleModel(ocr=ocr, show_log=show_log, lang=lang)
  69. elif model == MODEL.PEK:
  70. from magic_pdf.model.pdf_extract_kit import CustomPEKModel
  71. # 从配置文件读取model-dir和device
  72. local_models_dir = get_local_models_dir()
  73. device = get_device()
  74. layout_config = get_layout_config()
  75. if layout_model is not None:
  76. layout_config['model'] = layout_model
  77. formula_config = get_formula_config()
  78. if formula_enable is not None:
  79. formula_config['enable'] = formula_enable
  80. table_config = get_table_recog_config()
  81. if table_enable is not None:
  82. table_config['enable'] = table_enable
  83. model_input = {
  84. 'ocr': ocr,
  85. 'show_log': show_log,
  86. 'models_dir': local_models_dir,
  87. 'device': device,
  88. 'table_config': table_config,
  89. 'layout_config': layout_config,
  90. 'formula_config': formula_config,
  91. 'lang': lang,
  92. }
  93. custom_model = CustomPEKModel(**model_input)
  94. else:
  95. logger.error('Not allow model_name!')
  96. exit(1)
  97. model_init_cost = time.time() - model_init_start
  98. logger.info(f'model init cost: {model_init_cost}')
  99. else:
  100. logger.error('use_inside_model is False, not allow to use inside model')
  101. exit(1)
  102. return custom_model
  103. def doc_analyze(
  104. dataset: Dataset,
  105. ocr: bool = False,
  106. show_log: bool = False,
  107. start_page_id=0,
  108. end_page_id=None,
  109. lang=None,
  110. layout_model=None,
  111. formula_enable=None,
  112. table_enable=None,
  113. ):
  114. end_page_id = (
  115. end_page_id
  116. if end_page_id is not None and end_page_id >= 0
  117. else len(dataset) - 1
  118. )
  119. MIN_BATCH_INFERENCE_SIZE = int(os.environ.get('MINERU_MIN_BATCH_INFERENCE_SIZE', 200))
  120. batch_size = MIN_BATCH_INFERENCE_SIZE
  121. images = []
  122. page_wh_list = []
  123. images_with_extra_info = []
  124. results = []
  125. for index in range(len(dataset)):
  126. if start_page_id <= index <= end_page_id:
  127. page_data = dataset.get_page(index)
  128. img_dict = page_data.get_image()
  129. images.append(img_dict['img'])
  130. page_wh_list.append((img_dict['width'], img_dict['height']))
  131. if lang is None or lang == 'auto':
  132. images_with_extra_info.append((images[index], ocr, dataset._lang))
  133. else:
  134. images_with_extra_info.append((images[index], ocr, lang))
  135. if len(images_with_extra_info) == batch_size:
  136. _, result = may_batch_image_analyze(images_with_extra_info, 0, ocr, show_log, layout_model, formula_enable, table_enable)
  137. results.extend(result)
  138. images_with_extra_info = []
  139. if len(images_with_extra_info) > 0:
  140. _, result = may_batch_image_analyze(images_with_extra_info, 0, ocr, show_log, layout_model, formula_enable, table_enable)
  141. results.extend(result)
  142. images_with_extra_info = []
  143. model_json = []
  144. for index in range(len(dataset)):
  145. if start_page_id <= index <= end_page_id:
  146. result = results.pop(0)
  147. page_width, page_height = page_wh_list.pop(0)
  148. else:
  149. result = []
  150. page_height = 0
  151. page_width = 0
  152. page_info = {'page_no': index, 'width': page_width, 'height': page_height}
  153. page_dict = {'layout_dets': result, 'page_info': page_info}
  154. model_json.append(page_dict)
  155. from magic_pdf.operators.models import InferenceResult
  156. return InferenceResult(model_json, dataset)
  157. def batch_doc_analyze(
  158. datasets: list[Dataset],
  159. parse_method: str,
  160. show_log: bool = False,
  161. lang=None,
  162. layout_model=None,
  163. formula_enable=None,
  164. table_enable=None,
  165. ):
  166. MIN_BATCH_INFERENCE_SIZE = int(os.environ.get('MINERU_MIN_BATCH_INFERENCE_SIZE', 200))
  167. batch_size = MIN_BATCH_INFERENCE_SIZE
  168. images = []
  169. page_wh_list = []
  170. results = []
  171. images_with_extra_info = []
  172. for dataset in datasets:
  173. for index in range(len(dataset)):
  174. if lang is None or lang == 'auto':
  175. _lang = dataset._lang
  176. else:
  177. _lang = lang
  178. page_data = dataset.get_page(index)
  179. img_dict = page_data.get_image()
  180. images.append(img_dict['img'])
  181. page_wh_list.append((img_dict['width'], img_dict['height']))
  182. if parse_method == 'auto':
  183. images_with_extra_info.append((images[-1], dataset.classify() == SupportedPdfParseMethod.OCR, _lang))
  184. else:
  185. images_with_extra_info.append((images[-1], parse_method == 'ocr', _lang))
  186. if len(images_with_extra_info) == batch_size:
  187. _, result = may_batch_image_analyze(images_with_extra_info, 0, True, show_log, layout_model, formula_enable, table_enable)
  188. results.extend(result)
  189. images_with_extra_info = []
  190. if len(images_with_extra_info) > 0:
  191. _, result = may_batch_image_analyze(images_with_extra_info, 0, True, show_log, layout_model, formula_enable, table_enable)
  192. results.extend(result)
  193. images_with_extra_info = []
  194. infer_results = []
  195. from magic_pdf.operators.models import InferenceResult
  196. for index in range(len(datasets)):
  197. dataset = datasets[index]
  198. model_json = []
  199. for i in range(len(dataset)):
  200. result = results.pop(0)
  201. page_width, page_height = page_wh_list.pop(0)
  202. page_info = {'page_no': i, 'width': page_width, 'height': page_height}
  203. page_dict = {'layout_dets': result, 'page_info': page_info}
  204. model_json.append(page_dict)
  205. infer_results.append(InferenceResult(model_json, dataset))
  206. return infer_results
  207. def may_batch_image_analyze(
  208. images_with_extra_info: list[(np.ndarray, bool, str)],
  209. idx: int,
  210. ocr: bool,
  211. show_log: bool = False,
  212. layout_model=None,
  213. formula_enable=None,
  214. table_enable=None):
  215. # os.environ['CUDA_VISIBLE_DEVICES'] = str(idx)
  216. from magic_pdf.model.batch_analyze import BatchAnalyze
  217. model_manager = ModelSingleton()
  218. # images = [image for image, _, _ in images_with_extra_info]
  219. batch_ratio = 1
  220. device = get_device()
  221. if str(device).startswith('npu'):
  222. import torch_npu
  223. if torch_npu.npu.is_available():
  224. torch.npu.set_compile_mode(jit_compile=False)
  225. if str(device).startswith('npu') or str(device).startswith('cuda'):
  226. vram = get_vram(device)
  227. if vram is not None:
  228. gpu_memory = int(os.getenv('VIRTUAL_VRAM_SIZE', round(vram)))
  229. if gpu_memory >= 16:
  230. batch_ratio = 16
  231. elif gpu_memory >= 12:
  232. batch_ratio = 8
  233. elif gpu_memory >= 8:
  234. batch_ratio = 4
  235. elif gpu_memory >= 6:
  236. batch_ratio = 2
  237. else:
  238. batch_ratio = 1
  239. logger.info(f'gpu_memory: {gpu_memory} GB, batch_ratio: {batch_ratio}')
  240. else:
  241. # Default batch_ratio when VRAM can't be determined
  242. batch_ratio = 1
  243. logger.info(f'Could not determine GPU memory, using default batch_ratio: {batch_ratio}')
  244. # doc_analyze_start = time.time()
  245. batch_model = BatchAnalyze(model_manager, batch_ratio, show_log, layout_model, formula_enable, table_enable)
  246. results = batch_model(images_with_extra_info)
  247. # gc_start = time.time()
  248. clean_memory(get_device())
  249. # gc_time = round(time.time() - gc_start, 2)
  250. # logger.debug(f'gc time: {gc_time}')
  251. # doc_analyze_time = round(time.time() - doc_analyze_start, 2)
  252. # doc_analyze_speed = round(len(images) / doc_analyze_time, 2)
  253. # logger.debug(
  254. # f'doc analyze time: {round(time.time() - doc_analyze_start, 2)},'
  255. # f' speed: {doc_analyze_speed} pages/second'
  256. # )
  257. return idx, results