pipeline_analyze.py 6.1 KB

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