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
fix: refactor inference calls to use dedicated run functions for layout, MFR, and OCR detection/recognition
myhloli8b4c1d3683da
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex da70bbbd..617a1193 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -19,7 +19,13 @@ from mineru.backend.hybrid.hybrid_model_output_to_middle_json import (init_middle_json,)from mineru.backend.utils.runtime_utils import exclude_progress_bar_idle_time-from mineru.backend.pipeline.model_init import HybridModelSingleton+from mineru.backend.pipeline.model_init import (+ HybridModelSingleton,+ run_layout_inference,+ run_mfr_inference,+ run_ocr_det_inference,+ run_ocr_rec_inference,+)from mineru.backend.vlm.vlm_analyze import (ModelSingleton,aio_predictor_execution_guard,@@ -119,8 +125,11 @@ def ocr_det(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+ ocr_res = run_ocr_det_inference(+ 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(@@ -193,7 +202,11 @@ def ocr_det(# 批处理检测det_batch_size = min(len(batch_images), batch_ratio * OCR_DET_BASE_BATCH_SIZE)- batch_results = hybrid_pipeline_model.ocr_model.text_detector.batch_predict(batch_images, det_batch_size)+ batch_results = run_ocr_det_inference(+ 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):@@ -392,7 +405,8 @@ def _predict_layout_for_title_split(batch_ratio,):"""执行layout小模型检测,专门为Hybrid标题拆分提供页面layout结果。"""- return hybrid_pipeline_model.layout_model.batch_predict(+ return run_layout_inference(+ hybrid_pipeline_model.layout_model.batch_predict,images,batch_size=min(8, batch_ratio * LAYOUT_BASE_BATCH_SIZE),)@@ -433,7 +447,8 @@ def _process_ocr_and_formulas(if inline_formula_enable:images_mfd_res = _build_inline_formula_inputs(images_layout_res)# 公式识别- inline_formula_list = hybrid_pipeline_model.mfr_model.batch_predict(+ inline_formula_list = run_mfr_inference(+ hybrid_pipeline_model.mfr_model.batch_predict,images_mfd_res,np_images,batch_size=batch_ratio * MFR_BASE_BATCH_SIZE,@@ -473,7 +488,12 @@ def _process_ocr_and_formulas(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]+ ocr_result_list = run_ocr_rec_inference(+ hybrid_pipeline_model.ocr_model.ocr,+ img_crop_list,+ det=False,+ tqdm_enable=True,+ )[0]# Verify we have matching countsassert len(ocr_result_list) == len(need_ocr_list), f'ocr_result_list: {len(ocr_result_list)}, need_ocr_list: {len(need_ocr_list)}'diff --git a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.pyindex 80b75c3f..c8891561 100644--- a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py+++ b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py@@ -14,6 +14,7 @@ from mineru.backend.utils.para_block_utils import ()from mineru.backend.hybrid.hybrid_magic_model import MagicModelfrom mineru.backend.utils.runtime_utils import cross_page_table_merge+from mineru.backend.pipeline.model_init import run_ocr_rec_inferencefrom mineru.utils.config_reader import get_table_enablefrom mineru.utils.cut_image import cut_image_and_tablefrom mineru.utils.enum_class import ContentType, BlockType@@ -138,7 +139,12 @@ def _apply_post_ocr(pdf_info_list, hybrid_pipeline_model):img_crop_list.append(rotate_vertical_crop_if_needed(span['np_img']))span.pop('np_img')if len(img_crop_list) > 0:- ocr_res_list = hybrid_pipeline_model.ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]+ ocr_res_list = run_ocr_rec_inference(+ hybrid_pipeline_model.ocr_model.ocr,+ img_crop_list,+ det=False,+ tqdm_enable=True,+ )[0]assert len(ocr_res_list) == len(need_ocr_list), f'ocr_res_list: {len(ocr_res_list)}, need_ocr_list: {len(need_ocr_list)}'for index, span in enumerate(need_ocr_list):diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.pyindex 82d40a77..78f3f1a0 100644--- a/mineru/backend/pipeline/batch_analyze.py+++ b/mineru/backend/pipeline/batch_analyze.py@@ -9,7 +9,13 @@ from tqdm import tqdmfrom collections import defaultdictimport numpy as np-from .model_init import AtomModelSingleton+from .model_init import (+ AtomModelSingleton,+ run_layout_inference,+ run_mfr_inference,+ run_ocr_det_inference,+ run_ocr_rec_inference,+)from .model_list import AtomicModelfrom ...utils.config_reader import (get_formula_enable,@@ -362,9 +368,10 @@ class BatchAnalyze:np_images = [np.asarray(image) for image, _, _ in images_with_extra_info]# pp-doclayout_v2- images_layout_res += self.model.layout_model.batch_predict(+ images_layout_res += run_layout_inference(+ self.model.layout_model.batch_predict,pil_images,- batch_size=min(8, self.batch_ratio * LAYOUT_BASE_BATCH_SIZE)+ batch_size=min(8, self.batch_ratio * LAYOUT_BASE_BATCH_SIZE),)# 清理显存clean_vram(self.model.device, vram_threshold=8)@@ -380,7 +387,8 @@ class BatchAnalyze:images_mfd_res.append(page_formula_res)# 公式识别- images_formula_list = self.model.mfr_model.batch_predict(+ images_formula_list = run_mfr_inference(+ self.model.mfr_model.batch_predict,images_mfd_res,np_images,batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,@@ -526,7 +534,9 @@ class BatchAnalyze:if inline_mask_boxeselse bgr_image)- ocr_result = det_ocr_engine.ocr(det_image, rec=False)[0]+ ocr_result = run_ocr_det_inference(+ det_ocr_engine.ocr, det_image, rec=False+ )[0]if ocr_result and formula_mask_boxes:ocr_result = update_det_boxes(ocr_result, formula_mask_boxes)if ocr_result:@@ -555,7 +565,13 @@ class BatchAnalyze:enable_merge_det_boxes=False,)cropped_img_list = [item["cropped_img"] for item in rec_img_list]- ocr_res_list = ocr_engine.ocr(cropped_img_list, det=False, tqdm_enable=True, tqdm_desc=f"Table-ocr rec {_lang}")[0]+ ocr_res_list = run_ocr_rec_inference(+ ocr_engine.ocr,+ cropped_img_list,+ det=False,+ tqdm_enable=True,+ tqdm_desc=f"Table-ocr rec {_lang}",+ )[0]# 按照 table_id 将识别结果进行回填for img_dict, ocr_res in zip(rec_img_list, ocr_res_list):ocr_text = self._normalize_table_ocr_rec_text(ocr_res[0])@@ -715,7 +731,9 @@ class BatchAnalyze:# 批处理检测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)+ batch_results = run_ocr_det_inference(+ ocr_model.text_detector.batch_predict, batch_images, det_batch_size+ )# 处理批处理结果for crop_info, (dt_boxes, _) in zip(group_crops, batch_results):@@ -775,8 +793,11 @@ class BatchAnalyze:bgr_image,adjusted_mfdetrec_res,)- ocr_res = ocr_model.ocr(- det_image, mfd_res=adjusted_mfdetrec_res, rec=False+ ocr_res = run_ocr_det_inference(+ ocr_model.ocr,+ det_image,+ mfd_res=adjusted_mfdetrec_res,+ rec=False,)[0]# Integration results@@ -831,7 +852,9 @@ class BatchAnalyze:atom_model_name=AtomicModel.OCR,lang=lang)- ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]+ ocr_res_list = run_ocr_rec_inference(+ ocr_model.ocr, img_crop_list, det=False, tqdm_enable=True+ )[0]# Verify we have matching countsassert len(ocr_res_list) == len(@@ -900,7 +923,9 @@ class BatchAnalyze:)seal_crop_bgr = cv2.cvtColor(seal_crop_rgb, cv2.COLOR_RGB2BGR)- seal_ocr_res = seal_ocr_model.ocr(seal_crop_bgr, det=True, rec=True)[0]+ seal_ocr_res = run_ocr_det_inference(+ seal_ocr_model.ocr, seal_crop_bgr, det=True, rec=True+ )[0]if not seal_ocr_res:continuediff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/pipeline/model_init.pyindex e2c98b66..2006402a 100644--- a/mineru/backend/pipeline/model_init.py+++ b/mineru/backend/pipeline/model_init.py@@ -19,6 +19,45 @@ from ...utils.enum_class import ModelPathfrom ...utils.models_download_utils import auto_download_and_get_model_root_pathPIPELINE_MODEL_INIT_LOCK = threading.RLock()+# 这些锁保护 pipeline 与 hybrid 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。+PIPELINE_LAYOUT_INFERENCE_LOCK = threading.RLock()+PIPELINE_MFR_INFERENCE_LOCK = threading.RLock()+PIPELINE_OCR_DET_INFERENCE_LOCK = threading.RLock()+PIPELINE_OCR_REC_INFERENCE_LOCK = threading.RLock()+++def _run_with_inference_lock(inference_lock, inference_callable, *args, **kwargs):+ """在指定推理锁内执行真实 native 模型调用。"""+ with inference_lock:+ return inference_callable(*args, **kwargs)+++def run_layout_inference(inference_callable, *args, **kwargs):+ """在共享 Layout 推理锁内执行模型调用。"""+ return _run_with_inference_lock(+ PIPELINE_LAYOUT_INFERENCE_LOCK, inference_callable, *args, **kwargs+ )+++def run_mfr_inference(inference_callable, *args, **kwargs):+ """在共享 MFR 推理锁内执行模型调用。"""+ return _run_with_inference_lock(+ PIPELINE_MFR_INFERENCE_LOCK, inference_callable, *args, **kwargs+ )+++def run_ocr_det_inference(inference_callable, *args, **kwargs):+ """在共享 OCR det 推理锁内执行模型调用。"""+ return _run_with_inference_lock(+ PIPELINE_OCR_DET_INFERENCE_LOCK, inference_callable, *args, **kwargs+ )+++def run_ocr_rec_inference(inference_callable, *args, **kwargs):+ """在共享 OCR rec 推理锁内执行模型调用。"""+ return _run_with_inference_lock(+ PIPELINE_OCR_REC_INFERENCE_LOCK, inference_callable, *args, **kwargs+ )MFR_MODEL = os.getenv('MINERU_FORMULA_CH_SUPPORT', 'False')if MFR_MODEL.lower() in ['true', '1', 'yes']:diff --git a/mineru/backend/pipeline/model_json_to_middle_json.py b/mineru/backend/pipeline/model_json_to_middle_json.pyindex 4025af06..d51c5875 100644--- a/mineru/backend/pipeline/model_json_to_middle_json.py+++ b/mineru/backend/pipeline/model_json_to_middle_json.py@@ -7,7 +7,10 @@ from tqdm import tqdmfrom mineru.backend.utils.html_image_utils import replace_inline_table_imagesfrom mineru.backend.utils.runtime_utils import cross_page_table_mergefrom mineru.utils.config_reader import get_device-from mineru.backend.pipeline.model_init import AtomModelSingleton+from mineru.backend.pipeline.model_init import (+ AtomModelSingleton,+ run_ocr_rec_inference,+)from mineru.backend.pipeline.para_split import para_splitfrom mineru.utils.char_utils import full_to_halffrom mineru.utils.cut_image import cut_image_and_table@@ -231,7 +234,9 @@ def _apply_post_ocr(pdf_info_list, lang=None):det_db_box_thresh=0.3,lang=lang)- ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]+ ocr_res_list = run_ocr_rec_inference(+ ocr_model.ocr, img_crop_list, det=False, tqdm_enable=True+ )[0]assert len(ocr_res_list) == len(need_ocr_list), f'ocr_res_list: {len(ocr_res_list)}, need_ocr_list: {len(need_ocr_list)}'for index, span in enumerate(need_ocr_list):