pipeline_analyze.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import os
  2. import time
  3. import numpy as np
  4. import torch
  5. from .model_init import MineruPipelineModel
  6. from .config_reader import get_local_models_dir, get_device, get_formula_config, get_table_recog_config
  7. from ...utils.pdf_classify import classify
  8. from ...utils.pdf_image_tools import load_images_from_pdf
  9. from loguru import logger
  10. from ...utils.model_utils import get_vram, clean_memory
  11. os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 让mps可以fallback
  12. os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新
  13. class ModelSingleton:
  14. _instance = None
  15. _models = {}
  16. def __new__(cls, *args, **kwargs):
  17. if cls._instance is None:
  18. cls._instance = super().__new__(cls)
  19. return cls._instance
  20. def get_model(
  21. self,
  22. lang=None,
  23. formula_enable=None,
  24. table_enable=None,
  25. ):
  26. key = (lang, formula_enable, table_enable)
  27. if key not in self._models:
  28. self._models[key] = custom_model_init(
  29. lang=lang,
  30. formula_enable=formula_enable,
  31. table_enable=table_enable,
  32. )
  33. return self._models[key]
  34. def custom_model_init(
  35. lang=None,
  36. formula_enable=None,
  37. table_enable=None,
  38. ):
  39. model_init_start = time.time()
  40. # 从配置文件读取model-dir和device
  41. local_models_dir = get_local_models_dir()
  42. device = get_device()
  43. formula_config = get_formula_config()
  44. if formula_enable is not None:
  45. formula_config['enable'] = formula_enable
  46. table_config = get_table_recog_config()
  47. if table_enable is not None:
  48. table_config['enable'] = table_enable
  49. model_input = {
  50. 'models_dir': local_models_dir,
  51. 'device': device,
  52. 'table_config': table_config,
  53. 'formula_config': formula_config,
  54. 'lang': lang,
  55. }
  56. custom_model = MineruPipelineModel(**model_input)
  57. model_init_cost = time.time() - model_init_start
  58. logger.info(f'model init cost: {model_init_cost}')
  59. return custom_model
  60. def doc_analyze(
  61. pdf_bytes_list,
  62. lang_list,
  63. parse_method: str = 'auto',
  64. formula_enable=None,
  65. table_enable=None,
  66. ):
  67. MIN_BATCH_INFERENCE_SIZE = int(os.environ.get('MINERU_MIN_BATCH_INFERENCE_SIZE', 100))
  68. # 收集所有页面信息
  69. all_pages_info = [] # 存储(dataset_index, page_index, img, ocr, lang, width, height)
  70. all_image_lists = []
  71. all_pdf_docs = []
  72. ocr_enabled_list = []
  73. for pdf_idx, pdf_bytes in enumerate(pdf_bytes_list):
  74. # 确定OCR设置
  75. _ocr_enable = False
  76. if parse_method == 'auto':
  77. if classify(pdf_bytes) == 'ocr':
  78. _ocr_enable = True
  79. elif parse_method == 'ocr':
  80. _ocr_enable = True
  81. ocr_enabled_list.append(_ocr_enable)
  82. _lang = lang_list[pdf_idx]
  83. # 收集每个数据集中的页面
  84. images_list, pdf_doc = load_images_from_pdf(pdf_bytes)
  85. all_image_lists.append(images_list)
  86. all_pdf_docs.append(pdf_doc)
  87. for page_idx in range(len(images_list)):
  88. img_dict = images_list[page_idx]
  89. all_pages_info.append((
  90. pdf_idx, page_idx,
  91. img_dict['img_pil'], _ocr_enable, _lang,
  92. ))
  93. # 准备批处理
  94. images_with_extra_info = [(info[2], info[3], info[4]) for info in all_pages_info]
  95. batch_size = MIN_BATCH_INFERENCE_SIZE
  96. batch_images = [
  97. images_with_extra_info[i:i + batch_size]
  98. for i in range(0, len(images_with_extra_info), batch_size)
  99. ]
  100. # 执行批处理
  101. results = []
  102. processed_images_count = 0
  103. for index, batch_image in enumerate(batch_images):
  104. processed_images_count += len(batch_image)
  105. logger.info(
  106. f'Batch {index + 1}/{len(batch_images)}: '
  107. f'{processed_images_count} pages/{len(images_with_extra_info)} pages'
  108. )
  109. batch_results = batch_image_analyze(batch_image, formula_enable, table_enable)
  110. results.extend(batch_results)
  111. # 构建返回结果
  112. infer_results = []
  113. for _ in range(len(pdf_bytes_list)):
  114. infer_results.append([])
  115. for i, page_info in enumerate(all_pages_info):
  116. pdf_idx, page_idx, pil_img, _, _ = page_info
  117. result = results[i]
  118. page_info_dict = {'page_no': page_idx, 'width': pil_img.width, 'height': pil_img.height}
  119. page_dict = {'layout_dets': result, 'page_info': page_info_dict}
  120. infer_results[pdf_idx].append(page_dict)
  121. return infer_results, all_image_lists, all_pdf_docs, lang_list, ocr_enabled_list
  122. def batch_image_analyze(
  123. images_with_extra_info: list[(np.ndarray, bool, str)],
  124. formula_enable=None,
  125. table_enable=None):
  126. # os.environ['CUDA_VISIBLE_DEVICES'] = str(idx)
  127. from .batch_analyze import BatchAnalyze
  128. model_manager = ModelSingleton()
  129. batch_ratio = 1
  130. device = get_device()
  131. if str(device).startswith('npu'):
  132. import torch_npu
  133. if torch_npu.npu.is_available():
  134. torch.npu.set_compile_mode(jit_compile=False)
  135. if str(device).startswith('npu') or str(device).startswith('cuda'):
  136. vram = get_vram(device)
  137. if vram is not None:
  138. gpu_memory = int(os.getenv('MINERU_VIRTUAL_VRAM_SIZE', round(vram)))
  139. if gpu_memory >= 16:
  140. batch_ratio = 16
  141. elif gpu_memory >= 12:
  142. batch_ratio = 8
  143. elif gpu_memory >= 8:
  144. batch_ratio = 4
  145. elif gpu_memory >= 6:
  146. batch_ratio = 2
  147. else:
  148. batch_ratio = 1
  149. logger.info(f'gpu_memory: {gpu_memory} GB, batch_ratio: {batch_ratio}')
  150. else:
  151. # Default batch_ratio when VRAM can't be determined
  152. batch_ratio = 1
  153. logger.info(f'Could not determine GPU memory, using default batch_ratio: {batch_ratio}')
  154. batch_model = BatchAnalyze(model_manager, batch_ratio, formula_enable, table_enable)
  155. results = batch_model(images_with_extra_info)
  156. clean_memory(get_device())
  157. return results