Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
refactor: streamline OCR detection and model initialization in hybrid_analyze.py and model_init.py
myhloli25df92c6282e
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex b9fdeb0b..d0aa910e 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -1,203 +1,33 @@# Copyright (c) Opendatalab. All rights reserved.import osimport time+from collections import defaultdictimport cv2import numpy as npfrom PIL import Image-from lmdeploy import PytorchEngineConfig, TurbomindEngineConfig-from lmdeploy.serve.vl_async_engine import VLAsyncEnginefrom loguru import loggerfrom mineru_vl_utils import MinerUClientfrom mineru_vl_utils.structs import BlockType-from packaging import version+from tqdm import tqdmfrom mineru.backend.hybrid.hybrid_model_output_to_middle_json import result_to_middle_json-from mineru.backend.hybrid.utils import set_default_batch_size, set_default_gpu_memory_utilization, \- enable_custom_logits_processors, set_lmdeploy_backend-from mineru.backend.pipeline.model_init import MineruFormulaModel+from mineru.backend.pipeline.model_init import HybridModelSingleton+from mineru.backend.vlm.vlm_analyze import ModelSingletonfrom mineru.data.data_reader_writer import DataWriter-from mineru.utils.check_sys_env import is_mac_os_version_supportedfrom mineru.utils.config_reader import get_devicefrom mineru.utils.enum_class import ImageType-from mineru.utils.models_download_utils import auto_download_and_get_model_root_path+from mineru.utils.model_utils import crop_img+from mineru.utils.ocr_utils import get_adjusted_mfdetrec_res, get_ocr_result_list, sorted_boxes, merge_det_boxes, \+ update_det_boxes, OcrConfidencefrom mineru.utils.pdf_classify import classifyfrom mineru.utils.pdf_image_tools import load_images_from_pdfos.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1' # 让mps可以fallbackos.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新--class ModelSingleton:- _instance = None- _models = {}-- def __new__(cls, *args, **kwargs):- if cls._instance is None:- cls._instance = super().__new__(cls)- return cls._instance-- def get_model(- self,- backend: str,- model_path: str | None,- server_url: str | None,- **kwargs,- ) -> MinerUClient:- key = (backend, model_path, server_url)- if key not in self._models:- start_time = time.time()- model = None- processor = None- vllm_llm = None- lmdeploy_engine = None- vllm_async_llm = None- batch_size = kwargs.get("batch_size", 0) # for transformers backend only- max_concurrency = kwargs.get("max_concurrency", 100) # for http-client backend only- http_timeout = kwargs.get("http_timeout", 600) # for http-client backend only- server_headers = kwargs.get("server_headers", None) # for http-client backend only- max_retries = kwargs.get("max_retries", 3) # for http-client backend only- retry_backoff_factor = kwargs.get("retry_backoff_factor", 0.5) # for http-client backend only- # 从kwargs中移除这些参数,避免传递给不相关的初始化函数- for param in ["batch_size", "max_concurrency", "http_timeout", "server_headers", "max_retries", "retry_backoff_factor"]:- if param in kwargs:- del kwargs[param]- if backend not in ["http-client"] and not model_path:- model_path = auto_download_and_get_model_root_path("/","vlm")- if backend == "transformers":- try:- from transformers import (- AutoProcessor,- Qwen2VLForConditionalGeneration,- )- from transformers import __version__ as transformers_version- except ImportError:- raise ImportError("Please install transformers to use the transformers backend.")-- if version.parse(transformers_version) >= version.parse("4.56.0"):- dtype_key = "dtype"- else:- dtype_key = "torch_dtype"- device = get_device()- model = Qwen2VLForConditionalGeneration.from_pretrained(- model_path,- device_map={"": device},- **{dtype_key: "auto"}, # type: ignore- )- processor = AutoProcessor.from_pretrained(- model_path,- use_fast=True,- )- if batch_size == 0:- batch_size = set_default_batch_size()- elif backend == "mlx-engine":- mlx_supported = is_mac_os_version_supported()- if not mlx_supported:- raise EnvironmentError("mlx-engine backend is only supported on macOS 13.5+ with Apple Silicon.")- try:- from mlx_vlm import load as mlx_load- except ImportError:- raise ImportError("Please install mlx-vlm to use the mlx-engine backend.")- model, processor = mlx_load(model_path)- else:- if os.getenv('OMP_NUM_THREADS') is None:- os.environ["OMP_NUM_THREADS"] = "1"-- if backend == "vllm-engine":- try:- import vllm- except ImportError:- raise ImportError("Please install vllm to use the vllm-engine backend.")- if "gpu_memory_utilization" not in kwargs:- kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization()- if "model" not in kwargs:- kwargs["model"] = model_path- if enable_custom_logits_processors() and ("logits_processors" not in kwargs):- from mineru_vl_utils import MinerULogitsProcessor- kwargs["logits_processors"] = [MinerULogitsProcessor]- # 使用kwargs为 vllm初始化参数- vllm_llm = vllm.LLM(**kwargs)- elif backend == "vllm-async-engine":- try:- from vllm.engine.arg_utils import AsyncEngineArgs- from vllm.v1.engine.async_llm import AsyncLLM- except ImportError:- raise ImportError("Please install vllm to use the vllm-async-engine backend.")- if "gpu_memory_utilization" not in kwargs:- kwargs["gpu_memory_utilization"] = set_default_gpu_memory_utilization()- if "model" not in kwargs:- kwargs["model"] = model_path- if enable_custom_logits_processors() and ("logits_processors" not in kwargs):- from mineru_vl_utils import MinerULogitsProcessor- kwargs["logits_processors"] = [MinerULogitsProcessor]- # 使用kwargs为 vllm初始化参数- vllm_async_llm = AsyncLLM.from_engine_args(AsyncEngineArgs(**kwargs))- elif backend == "lmdeploy-engine":- try:- from lmdeploy import PytorchEngineConfig, TurbomindEngineConfig- from lmdeploy.serve.vl_async_engine import VLAsyncEngine- except ImportError:- raise ImportError("Please install lmdeploy to use the lmdeploy-engine backend.")- if "cache_max_entry_count" not in kwargs:- kwargs["cache_max_entry_count"] = 0.5-- device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")- if device_type == "":- if "lmdeploy_device" in kwargs:- device_type = kwargs.pop("lmdeploy_device")- if device_type not in ["cuda", "ascend", "maca", "camb"]:- raise ValueError(f"Unsupported lmdeploy device type: {device_type}")- else:- device_type = "cuda"- lm_backend = os.getenv("MINERU_LMDEPLOY_BACKEND", "")- if lm_backend == "":- if "lmdeploy_backend" in kwargs:- lm_backend = kwargs.pop("lmdeploy_backend")- if lm_backend not in ["pytorch", "turbomind"]:- raise ValueError(f"Unsupported lmdeploy backend: {lm_backend}")- else:- lm_backend = set_lmdeploy_backend(device_type)- logger.info(f"lmdeploy device is: {device_type}, lmdeploy backend is: {lm_backend}")-- if lm_backend == "pytorch":- kwargs["device_type"] = device_type- backend_config = PytorchEngineConfig(**kwargs)- elif lm_backend == "turbomind":- backend_config = TurbomindEngineConfig(**kwargs)- else:- raise ValueError(f"Unsupported lmdeploy backend: {lm_backend}")-- log_level = 'ERROR'- from lmdeploy.utils import get_logger- lm_logger = get_logger('lmdeploy')- lm_logger.setLevel(log_level)- if os.getenv('TM_LOG_LEVEL') is None:- os.environ['TM_LOG_LEVEL'] = log_level-- lmdeploy_engine = VLAsyncEngine(- model_path,- backend=lm_backend,- backend_config=backend_config,- )- self._models[key] = MinerUClient(- backend=backend,- model=model,- processor=processor,- lmdeploy_engine=lmdeploy_engine,- vllm_llm=vllm_llm,- vllm_async_llm=vllm_async_llm,- server_url=server_url,- batch_size=batch_size,- max_concurrency=max_concurrency,- http_timeout=http_timeout,- server_headers=server_headers,- max_retries=max_retries,- retry_backoff_factor=retry_backoff_factor,- )- elapsed = round(time.time() - start_time, 2)- logger.info(f"get {backend} predictor cost: {elapsed}s")- return self._models[key]-+MFR_BASE_BATCH_SIZE = 16+OCR_DET_BASE_BATCH_SIZE = 16not_extract_list = [BlockType.TEXT,@@ -224,129 +54,153 @@ def ocr_classify(pdf_bytes, parse_method: str = 'auto',) -> bool:_ocr_enable = Truereturn _ocr_enable-def ocr_det_batch_setting():- device = get_device()- # 检测torch的版本号- import torch- from packaging import version- if version.parse(torch.__version__) >= version.parse("2.8.0") or str(device).startswith('mps'):- enable_ocr_det_batch = False+def ocr_det(+ hybrid_pipeline_model,+ np_images,+ results,+ mfd_res,+ _ocr_enable+):+ ocr_res_list = []+ if not hybrid_pipeline_model.enable_ocr_det_batch:+ # 非批处理模式 - 逐页处理+ for np_image, page_mfd_res, page_results in tqdm(+ zip(np_images, mfd_res, results),+ total=len(np_images),+ desc="OCR-det"+ ):+ ocr_res_list.append([])+ img_height, img_width = np_image.shape[:2]+ for res in page_results:+ if res['type'] not in not_extract_list:+ continue+ x0 = max(0, int(res['bbox'][0] * img_width))+ y0 = max(0, int(res['bbox'][1] * img_height))+ x1 = min(img_width, int(res['bbox'][2] * img_width))+ y1 = min(img_height, int(res['bbox'][3] * img_height))+ if x1 <= x0 or y1 <= y0:+ continue+ res['poly'] = [x0, y0, x1, y0, x1, y1, x0, y1]+ new_image, useful_list = crop_img(+ res, np_image, crop_paste_x=50, crop_paste_y=50+ )+ adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(+ page_mfd_res, useful_list+ )+ bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)+ ocr_res = hybrid_pipeline_model.ocr_model.ocr(+ bgr_image, mfd_res=adjusted_mfdetrec_res, rec=False+ )[0]+ if ocr_res:+ ocr_result_list = get_ocr_result_list(+ ocr_res, useful_list, _ocr_enable, bgr_image, hybrid_pipeline_model.lang+ )++ ocr_res_list[-1].extend(ocr_result_list)else:- enable_ocr_det_batch = True- return enable_ocr_det_batch--# def ocr_det(enable_ocr_det_batch, lang):-# # OCR det-# if enable_ocr_det_batch:-# # 批处理模式 - 按语言和分辨率分组-# # 收集所有需要OCR检测的裁剪图像-# all_cropped_images_info = []-#-# for res in ocr_res_list_dict['ocr_res_list']:-# new_image, useful_list = crop_img(-# res, ocr_res_list_dict['np_img'], crop_paste_x=50, crop_paste_y=50-# )-# adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(-# ocr_res_list_dict['single_page_mfdetrec_res'], useful_list-# )-#-# # BGR转换-# bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)-#-# all_cropped_images_info.append((-# bgr_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang-# ))-#-# # 获取OCR模型-# ocr_model = atom_model_manager.get_atom_model(-# atom_model_name=AtomicModel.OCR,-# det_db_box_thresh=0.3,-# lang=lang-# )-#-# # 按分辨率分组并同时完成padding-# # RESOLUTION_GROUP_STRIDE = 32-# RESOLUTION_GROUP_STRIDE = 64-#-# resolution_groups = defaultdict(list)-# for crop_info in lang_crop_list:-# cropped_img = crop_info[0]-# h, w = cropped_img.shape[:2]-# # 直接计算目标尺寸并用作分组键-# target_h = ((h + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE-# target_w = ((w + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE-# group_key = (target_h, target_w)-# resolution_groups[group_key].append(crop_info)-#-# # 对每个分辨率组进行批处理-# for (target_h, target_w), group_crops in tqdm(resolution_groups.items(), desc=f"OCR-det {lang}"):-# # 对所有图像进行padding到统一尺寸-# batch_images = []-# for crop_info in group_crops:-# img = crop_info[0]-# h, w = img.shape[:2]-# # 创建目标尺寸的白色背景-# padded_img = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255-# padded_img[:h, :w] = img-# batch_images.append(padded_img)-#-# # 批处理检测-# det_batch_size = min(len(batch_images), self.batch_ratio * OCR_DET_BASE_BATCH_SIZE)-# batch_results = ocr_model.text_detector.batch_predict(batch_images, det_batch_size)-#-# # 处理批处理结果-# for crop_info, (dt_boxes, _) in zip(group_crops, batch_results):-# bgr_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang = crop_info-#-# if dt_boxes is not None and len(dt_boxes) > 0:-# # 处理检测框-# dt_boxes_sorted = sorted_boxes(dt_boxes)-# dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []-#-# # 根据公式位置更新检测框-# dt_boxes_final = (update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)-# if dt_boxes_merged and adjusted_mfdetrec_res-# else dt_boxes_merged)-#-# if dt_boxes_final:-# ocr_res = [box.tolist() if hasattr(box, 'tolist') else box for box in dt_boxes_final]-# ocr_result_list = get_ocr_result_list(-# ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], bgr_image, _lang-# )-# ocr_res_list_dict['layout_res'].extend(ocr_result_list)-#-# else:-# # 原始单张处理模式-# for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):-# # Process each area that requires OCR processing-# _lang = ocr_res_list_dict['lang']-# # Get OCR results for this language's images-# ocr_model = atom_model_manager.get_atom_model(-# atom_model_name=AtomicModel.OCR,-# ocr_show_log=False,-# det_db_box_thresh=0.3,-# lang=_lang-# )-# for res in ocr_res_list_dict['ocr_res_list']:-# new_image, useful_list = crop_img(-# res, ocr_res_list_dict['np_img'], crop_paste_x=50, crop_paste_y=50-# )-# adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(-# ocr_res_list_dict['single_page_mfdetrec_res'], useful_list-# )-# # OCR-det-# bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)-# ocr_res = ocr_model.ocr(-# bgr_image, mfd_res=adjusted_mfdetrec_res, rec=False-# )[0]-#-# # Integration results-# if ocr_res:-# ocr_result_list = get_ocr_result_list(-# ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], bgr_image, _lang-# )-#-# ocr_res_list_dict['layout_res'].extend(ocr_result_list)+ # 批处理模式 - 按语言和分辨率分组+ # 收集所有需要OCR检测的裁剪图像+ all_cropped_images_info = []++ for np_image, page_mfd_res, page_results in zip(+ np_images, mfd_res, results+ ):+ ocr_res_list.append([])+ img_height, img_width = np_image.shape[:2]+ for res in page_results:+ if res['type'] not in not_extract_list:+ continue+ x0 = max(0, int(res['bbox'][0] * img_width))+ y0 = max(0, int(res['bbox'][1] * img_height))+ x1 = min(img_width, int(res['bbox'][2] * img_width))+ y1 = min(img_height, int(res['bbox'][3] * img_height))+ if x1 <= x0 or y1 <= y0:+ continue+ res['poly'] = [x0, y0, x1, y0, x1, y1, x0, y1]+ new_image, useful_list = crop_img(+ res, np_image, crop_paste_x=50, crop_paste_y=50+ )+ adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(+ page_mfd_res, useful_list+ )+ bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)+ all_cropped_images_info.append((+ bgr_image, useful_list, adjusted_mfdetrec_res, ocr_res_list[-1]+ ))++ # 按分辨率分组并同时完成padding+ RESOLUTION_GROUP_STRIDE = 64 # 32++ resolution_groups = defaultdict(list)+ for crop_info in all_cropped_images_info:+ cropped_img = crop_info[0]+ h, w = cropped_img.shape[:2]+ # 直接计算目标尺寸并用作分组键+ target_h = ((h + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE+ target_w = ((w + RESOLUTION_GROUP_STRIDE - 1) // RESOLUTION_GROUP_STRIDE) * RESOLUTION_GROUP_STRIDE+ group_key = (target_h, target_w)+ resolution_groups[group_key].append(crop_info)++ # 对每个分辨率组进行批处理+ for (target_h, target_w), group_crops in tqdm(resolution_groups.items(), desc=f"OCR-det"):+ # 对所有图像进行padding到统一尺寸+ batch_images = []+ for crop_info in group_crops:+ img = crop_info[0]+ h, w = img.shape[:2]+ # 创建目标尺寸的白色背景+ padded_img = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255+ padded_img[:h, :w] = img+ batch_images.append(padded_img)++ # 批处理检测+ det_batch_size = min(len(batch_images), OCR_DET_BASE_BATCH_SIZE)+ batch_results = hybrid_pipeline_model.ocr_model.text_detector.batch_predict(batch_images, det_batch_size)++ # 处理批处理结果+ for crop_info, (dt_boxes, _) in zip(group_crops, batch_results):+ bgr_image, useful_list, adjusted_mfdetrec_res, ocr_page_res_list = crop_info++ if dt_boxes is not None and len(dt_boxes) > 0:+ # 处理检测框+ dt_boxes_sorted = sorted_boxes(dt_boxes)+ dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []++ # 根据公式位置更新检测框+ dt_boxes_final = (update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)+ if dt_boxes_merged and adjusted_mfdetrec_res+ else dt_boxes_merged)++ if dt_boxes_final:+ ocr_res = [box.tolist() if hasattr(box, 'tolist') else box for box in dt_boxes_final]+ ocr_result_list = get_ocr_result_list(+ ocr_res, useful_list, _ocr_enable, bgr_image, hybrid_pipeline_model.lang+ )+ ocr_page_res_list.extend(ocr_result_list)+ return ocr_res_list++def mask_image_regions(np_images, results):+ # 根据vlm返回的结果,在每一页中将image、table、equation块mask成白色背景图像+ for np_image, vlm_page_results in zip(np_images, results):+ img_height, img_width = np_image.shape[:2]+ # 收集需要mask的区域+ mask_regions = []+ for block in vlm_page_results:+ if block['type'] in [BlockType.IMAGE, BlockType.TABLE, BlockType.EQUATION]:+ bbox = block['bbox']+ # 批量转换归一化坐标到像素坐标,并进行边界检查+ x0 = max(0, int(bbox[0] * img_width))+ y0 = max(0, int(bbox[1] * img_height))+ x1 = min(img_width, int(bbox[2] * img_width))+ y1 = min(img_height, int(bbox[3] * img_height))+ # 只添加有效区域+ if x1 > x0 and y1 > y0:+ mask_regions.append((y0, y1, x0, x1))+ # 批量应用mask+ for y0, y1, x0, x1 in mask_regions:+ np_image[y0:y1, x0:x1, :] = 255+ return np_images+async def doc_analyze_core(pdf_bytes,@@ -370,11 +224,8 @@ async def doc_analyze_core(# load_images_time = round(time.time() - load_images_start, 2)# logger.debug(f"load images cost: {load_images_time}, speed: {round(len(images_pil_list)/load_images_time, 3)} images/s")- # infer_start = time.time()_ocr_enable = ocr_classify(pdf_bytes, parse_method=parse_method)-_vlm_ocr_enable = False-if _ocr_enable and language in ["ch", "chinese_cht", "ch_lite", "ch_server", "en"] and inline_formula_enable:_vlm_ocr_enable = Trueif is_async:@@ -386,35 +237,83 @@ async def doc_analyze_core(results = await predictor.aio_batch_two_step_extract(images=images_pil_list, not_extract_list=not_extract_list)else:results = predictor.batch_two_step_extract(images=images_pil_list, not_extract_list=not_extract_list)- # 遍历results,对文本块截图交由OCR识别- # 根据_ocr_enable决定ocr只开det还是det+rec- # 根据inline_formula_enable决定是使用mfd和ocr结合的方式,还是纯ocr方式+ # 遍历results,对文本块截图交由OCR识别+ # 根据_ocr_enable决定ocr只开det还是det+rec+ # 根据inline_formula_enable决定是使用mfd和ocr结合的方式,还是纯ocr方式if not _vlm_ocr_enable:- np_images = [np.asarray(pil_image) for pil_image in images_pil_list]- # 如果开启行内公式识别,则进行公式检测和识别+ # 将PIL图片转换为numpy数组+ np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]+ hybrid_model_singleton = HybridModelSingleton()+ hybrid_pipeline_model = hybrid_model_singleton.get_model(+ lang=language,+ formula_enable=inline_formula_enable,+ )if inline_formula_enable:- formula_model = MineruFormulaModel()+ # 在进行`行内`公式检测和识别前,先将图像中的图片、表格、`行间`公式区域mask掉+ np_images = mask_image_regions(np_images, results)# 公式检测- images_mfd_res = formula_model.mfd_model.batch_predict(- np_images, 1- )-+ images_mfd_res = hybrid_pipeline_model.mfd_model.batch_predict(np_images, 1)# 公式识别- images_formula_list = formula_model.mfr_model.batch_predict(+ images_formula_list = hybrid_pipeline_model.mfr_model.batch_predict(images_mfd_res,np_images,- batch_size=4 * 16,+ batch_size=MFR_BASE_BATCH_SIZE,+ interline_enable=False,)- mfr_count = 0- for image_index in range(len(np_images)):- mfr_count += len(images_formula_list[image_index])- logger.debug(f"formula count: {mfr_count}")+ else:+ images_formula_list = [[] for _ in range(len(np_images))]++ mfd_res = []+ for page_images_formula_list in images_formula_list:+ page_mfd_res = []+ for formula in page_images_formula_list:+ page_mfd_res.append({+ "bbox": [int(formula['poly'][0]), int(formula['poly'][1]),+ int(formula['poly'][4]), int(formula['poly'][5])],+ })+ mfd_res.append(page_mfd_res)# vlm没有执行ocr,需要ocr_det- enable_ocr_det_batch = ocr_det_batch_setting()- # ocr_det(enable_ocr_det_batch, language)-+ ocr_res_list = ocr_det(+ hybrid_pipeline_model,+ np_images,+ results,+ mfd_res,+ _ocr_enable+ )++ # 如果需要ocr则做ocr_rec+ if _ocr_enable:+ need_ocr_list = []+ img_crop_list = []+ for page_ocr_res_list in ocr_res_list:+ for ocr_res in page_ocr_res_list:+ if 'np_img' in ocr_res:+ need_ocr_list.append(ocr_res)+ img_crop_list.append(ocr_res.pop('np_img'))+ if len(img_crop_list) > 0:+ # Process OCR+ ocr_result_list = hybrid_pipeline_model.ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]++ # Verify we have matching counts+ assert len(ocr_result_list) == len(need_ocr_list), f'ocr_result_list: {len(ocr_result_list)}, need_ocr_list: {len(need_ocr_list)}'++ # Process OCR results for this language+ for index, need_ocr_res in enumerate(need_ocr_list):+ ocr_text, ocr_score = ocr_result_list[index]+ need_ocr_res['text'] = ocr_text+ need_ocr_res['score'] = float(f"{ocr_score:.3f}")+ if ocr_score < OcrConfidence.min_confidence:+ need_ocr_res['category_id'] = 16+ else:+ layout_res_bbox = [need_ocr_res['poly'][0], need_ocr_res['poly'][1],+ need_ocr_res['poly'][4], need_ocr_res['poly'][5]]+ layout_res_width = layout_res_bbox[2] - layout_res_bbox[0]+ layout_res_height = layout_res_bbox[3] - layout_res_bbox[1]+ if ocr_text in ['(204号', '(20', '(2', '(2号', '(20号', '号',+ '(204'] and ocr_score < 0.8 and layout_res_width < layout_res_height:+ need_ocr_res['category_id'] = 16middle_json = result_to_middle_json(results, images_list, pdf_doc, image_writer)return middle_json, results@@ -475,43 +374,3 @@ async def aio_doc_analyze(**kwargs,)--if __name__ == "__main__":- kwargs = {}- kwargs["cache_max_entry_count"] = 0.5- os.environ["MINERU_MODEL_SOURCE"] = "local"- model_path = auto_download_and_get_model_root_path("/", "vlm")-- log_level = 'ERROR'- from lmdeploy.utils import get_logger-- lm_logger = get_logger('lmdeploy')- lm_logger.setLevel(log_level)- if os.getenv('TM_LOG_LEVEL') is None:- os.environ['TM_LOG_LEVEL'] = log_level-- lmdeploy_engine = VLAsyncEngine(- model_path,- backend="turbomind",- backend_config=TurbomindEngineConfig(**kwargs),- )-- client = MinerUClient(- backend="lmdeploy-engine",- lmdeploy_engine=lmdeploy_engine,- )- not_extract_list = ["text", "title"]- image = Image.open(r"C:\Users\zhaoxiaomeng\Downloads\ch_hand_writer.jpg")- def run_sync():- extracted_blocks = client.two_step_extract(image=image, not_extract_list=not_extract_list)- return extracted_blocks- async def run_async():- extracted_blocks = await client.aio_two_step_extract(image=image, not_extract_list=not_extract_list)- return extracted_blocks-- extracted_blocks = run_sync()- print(f"extracted_blocks: {extracted_blocks}")-- import asyncio- async_extracted_blocks = asyncio.run(run_async())- print(f"async_extracted_blocks: {async_extracted_blocks}")diff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/pipeline/model_init.pyindex a84db116..5ed2b8c9 100644--- a/mineru/backend/pipeline/model_init.py+++ b/mineru/backend/pipeline/model_init.py@@ -271,9 +271,53 @@ class MineruPipelineModel:logger.info('DocAnalysis init done!')-class MineruFormulaModel:- def __init__(self):- self.device = get_device()+class HybridModelSingleton:+ _instance = None+ _models = {}++ def __new__(cls, *args, **kwargs):+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ return cls._instance++ def get_model(+ self,+ lang=None,+ formula_enable=None,+ ):+ key = (lang, formula_enable)+ if key not in self._models:+ self._models[key] = MineruHybridModel(+ lang=lang,+ formula_enable=formula_enable,+ )+ return self._models[key]++def ocr_det_batch_setting(device):+ # 检测torch的版本号+ import torch+ from packaging import version+ if version.parse(torch.__version__) >= version.parse("2.8.0") or str(device).startswith('mps'):+ enable_ocr_det_batch = False+ else:+ enable_ocr_det_batch = True+ return enable_ocr_det_batch++class MineruHybridModel:+ def __init__(+ self,+ device=None,+ lang=None,+ formula_enable=True,+ ):+ if device is not None:+ self.device = device+ else:+ self.device = get_device()++ self.lang = lang++ self.enable_ocr_det_batch = ocr_det_batch_setting(self.device)if str(self.device).startswith('npu'):try:@@ -286,28 +330,36 @@ class MineruFormulaModel:"Please ensure that the torch_npu package is installed correctly.") from e- atom_model_manager = AtomModelSingleton()+ self.atom_model_manager = AtomModelSingleton()- # 初始化公式检测模型- self.mfd_model = atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.MFD,- mfd_weights=str(- os.path.join(auto_download_and_get_model_root_path(ModelPath.yolo_v8_mfd), ModelPath.yolo_v8_mfd)- ),- device=self.device,+ # 初始化OCR模型+ self.ocr_model = self.atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.OCR,+ det_db_box_thresh=0.3,+ lang=self.lang)- # 初始化公式解析模型- if MFR_MODEL == "unimernet_small":- mfr_model_path = ModelPath.unimernet_small- elif MFR_MODEL == "pp_formulanet_plus_m":- mfr_model_path = ModelPath.pp_formulanet_plus_m- else:- logger.error('MFR model name not allow')- exit(1)+ if formula_enable:+ # 初始化公式检测模型+ self.mfd_model = self.atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.MFD,+ mfd_weights=str(+ os.path.join(auto_download_and_get_model_root_path(ModelPath.yolo_v8_mfd), ModelPath.yolo_v8_mfd)+ ),+ device=self.device,+ )- self.mfr_model = atom_model_manager.get_atom_model(- atom_model_name=AtomicModel.MFR,- mfr_weight_dir=str(os.path.join(auto_download_and_get_model_root_path(mfr_model_path), mfr_model_path)),- device=self.device,- )\ No newline at end of file+ # 初始化公式解析模型+ if MFR_MODEL == "unimernet_small":+ mfr_model_path = ModelPath.unimernet_small+ elif MFR_MODEL == "pp_formulanet_plus_m":+ mfr_model_path = ModelPath.pp_formulanet_plus_m+ else:+ logger.error('MFR model name not allow')+ exit(1)++ self.mfr_model = self.atom_model_manager.get_atom_model(+ atom_model_name=AtomicModel.MFR,+ mfr_weight_dir=str(os.path.join(auto_download_and_get_model_root_path(mfr_model_path), mfr_model_path)),+ device=self.device,+ )\ No newline at end of filediff --git a/mineru/model/mfr/unimernet/Unimernet.py b/mineru/model/mfr/unimernet/Unimernet.pyindex 0cabfc30..7c3ce7a9 100644--- a/mineru/model/mfr/unimernet/Unimernet.py+++ b/mineru/model/mfr/unimernet/Unimernet.py@@ -61,7 +61,13 @@ class UnimernetModel(object):res["latex"] = latexreturn formula_list- def batch_predict(self, images_mfd_res: list, images: list, batch_size: int = 64) -> list:+ def batch_predict(+ self,+ images_mfd_res: list,+ images: list,+ batch_size: int = 64,+ interline_enable: bool = True,+ ) -> list:images_formula_list = []mf_image_list = []backfill_list = []@@ -76,6 +82,8 @@ class UnimernetModel(object):for idx, (xyxy, conf, cla) in enumerate(zip(mfd_res.boxes.xyxy, mfd_res.boxes.conf, mfd_res.boxes.cls)):+ if not interline_enable and cla.item() == 1:+ continue # Skip interline regions if not enabledxmin, ymin, xmax, ymax = [int(p.item()) for p in xyxy]new_item = {"category_id": 13 + int(cla.item()),