pipeline_analyze.py 6.0 KB

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