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
Add optional CUDA table sessions and inference stage timings
myhloli9168ac7b1780
diff --git a/mineru/backend/analysis/pdf/pipeline.py b/mineru/backend/analysis/pdf/pipeline.pyindex 0a47aa01..00eca184 100644--- a/mineru/backend/analysis/pdf/pipeline.py+++ b/mineru/backend/analysis/pdf/pipeline.py@@ -10,6 +10,8 @@ from typing import castfrom docvortex.document.pdf import PDFDocumentfrom loguru import logger+from ....utils.timing import stage_timer+from ....config import VlmConfigfrom ....model.runtime.execution import acquire_document, release_documentfrom ....utils.async_utils import run_sync@@ -85,7 +87,8 @@ def analyze_pdf("""使用共享资源生命周期与同步窗口编排生产 PDF 模型结果。"""state = _PDFAnalysis()try:- _prepare_analysis(state, file_bytes, effort, parse_mode, vlm_config)+ with stage_timer("pdf.prepare"):+ _prepare_analysis(state, file_bytes, effort, parse_mode, vlm_config)infer_started_at = time.perf_counter()model_list = process_pdf_windows(file_bytes,@@ -99,7 +102,8 @@ def analyze_pdf()result = _build_pdf_analysis_result(state, model_list, effort, infer_started_at)finally:- _close_analysis(state)+ with stage_timer("pdf.cleanup"):+ _close_analysis(state)return result@@ -143,7 +147,8 @@ def _build_pdf_analysis_result(angles = {id(block): block.get("angle", 0) for page in model_list for block in page}_normalize_pdf_model_list(model_list)elapsed = time.perf_counter() - started_at- geometry, diagnostics = extract_layout_geometry(state.document, None)+ with stage_timer("pdf.geometry"):+ geometry, diagnostics = extract_layout_geometry(state.document, None)rotation_pages = [[{**block, "angle": angles.get(id(block), 0)} for block in page] for page in model_list]attach_layout_image_rotations(geometry, rotation_pages, None)for diagnostic in diagnostics:diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.pyindex 26bfca36..6dd6b774 100644--- a/mineru/backend/analysis/pdf/window.py+++ b/mineru/backend/analysis/pdf/window.py@@ -17,6 +17,8 @@ from docvortex.document.pdf.visuals import attach_visual_block_images as _attachfrom docvortex.document.pdf.visuals import attach_visual_block_images_from_pdffrom loguru import logger+from ....utils.timing import stage_timer+from ....model.runtime.execution import local_model_stagefrom ....utils.async_utils import run_syncfrom ....model.runtime.hybrid import HybridLocalModelContext@@ -161,26 +163,29 @@ def _process_flash_ocr(if np_images is None:np_images = [np.asarray(image_dict["img_pil"]).copy() for image_dict in images_list]empty_formula_list: list[list[dict[str, Any]]] = [[] for _ in model_list]- ocr_res_list = _ocr_det(- local_model_context,- np_images,- model_list,- empty_formula_list,- True,- PIPELINE_DET_TYPE,- )- _apply_ocr_rec_results(local_model_context, ocr_res_list)- model_list = _fill_window_block_content_and_lines(- images_list,- pdf_pages,- model_list,- empty_formula_list,- ocr_res_list,- "ocr",- "flash",- PIPELINE_DET_TYPE,- local_model_context,- )+ with stage_timer("pdf.ocr_detection"):+ ocr_res_list = _ocr_det(+ local_model_context,+ np_images,+ model_list,+ empty_formula_list,+ True,+ PIPELINE_DET_TYPE,+ )+ with stage_timer("pdf.ocr_recognition"):+ _apply_ocr_rec_results(local_model_context, ocr_res_list)+ with stage_timer("pdf.text_fill"):+ model_list = _fill_window_block_content_and_lines(+ images_list,+ pdf_pages,+ model_list,+ empty_formula_list,+ ocr_res_list,+ "ocr",+ "flash",+ PIPELINE_DET_TYPE,+ local_model_context,+ )_fill_flash_ocr_table_contents(images_list,model_list,@@ -237,22 +242,24 @@ def _process_text_and_formulas(# 全部被过滤时保持逐页空结果,不能让原始表内公式重新进入正文 sidecar。images_formula_list = [[] for _ in mfd_res]if any(mfr_inputs):- images_formula_list = local_model_context.mfr_model.batch_predict(- mfr_inputs,- np_images,- batch_size=BATCH_RATIO * MFR_BASE_BATCH_SIZE,- interline_enable=interline_enable,- )+ with stage_timer("pdf.formulas"):+ images_formula_list = local_model_context.mfr_model.batch_predict(+ mfr_inputs,+ np_images,+ batch_size=BATCH_RATIO * MFR_BASE_BATCH_SIZE,+ interline_enable=interline_enable,+ )inline_formula_list, display_formula_list = _split_formula_results(images_formula_list)if effort == "medium":# 表格解析必须早于正文行填充,确保表内图片和行内公式只由表格模型消费一次。- _apply_medium_table_recognition(- local_model_context,- model_list,- inline_formula_list,- np_images,- )+ with stage_timer("pdf.table_recognition"):+ _apply_medium_table_recognition(+ local_model_context,+ model_list,+ inline_formula_list,+ np_images,+ )# 将行间公式span回填入block_apply_medium_display_formula_results(model_list,@@ -260,11 +267,12 @@ def _process_text_and_formulas(images_pil_list,)# 使用ocr识别行间公式标号- _apply_medium_formula_number_ocr(- local_model_context,- model_list,- np_images,- )+ with stage_timer("pdf.formula_numbers"):+ _apply_medium_formula_number_ocr(+ local_model_context,+ model_list,+ np_images,+ )# 行间公式标号回填到blockfor page_model_list in model_list:@@ -272,32 +280,35 @@ def _process_text_and_formulas(need_rec_img = parse_mode == "ocr" and effort == "medium"# vlm没有执行ocr,需要ocr_det- ocr_res_list = _ocr_det(- local_model_context,- np_images,- model_list,- mfd_res,- need_rec_img,- ocr_det_type,- )+ with stage_timer("pdf.ocr_detection"):+ ocr_res_list = _ocr_det(+ local_model_context,+ np_images,+ model_list,+ mfd_res,+ need_rec_img,+ ocr_det_type,+ )# 如果有rec_img则做ocr_recif need_rec_img:- _apply_ocr_rec_results(local_model_context, ocr_res_list)+ with stage_timer("pdf.ocr_recognition"):+ _apply_ocr_rec_results(local_model_context, ocr_res_list)- return _fill_window_block_content_and_lines(- images_list,- pdf_pages,- model_list,- inline_formula_list,- ocr_res_list,- parse_mode,- effort,- ocr_det_type,- local_model_context,- page_text_geometries,- page_vector_geometries=page_vector_geometries,- )+ with stage_timer("pdf.text_fill"):+ return _fill_window_block_content_and_lines(+ images_list,+ pdf_pages,+ model_list,+ inline_formula_list,+ ocr_res_list,+ parse_mode,+ effort,+ ocr_det_type,+ local_model_context,+ page_text_geometries,+ page_vector_geometries=page_vector_geometries,+ )@dataclass@@ -350,12 +361,13 @@ def _prepare_pdf_window(page_vector_geometries: list[PDFPageVectorGeometry | None] | None = Nonetry:window_pages = _get_window_pdf_pages(document, window)- images_list = load_images_from_pdf_bytes_range(- pdf_bytes=file_bytes,- start_page_id=window.start,- end_page_id=window.end,- image_type="pil_img",- )+ with stage_timer("pdf.render"):+ images_list = load_images_from_pdf_bytes_range(+ pdf_bytes=file_bytes,+ start_page_id=window.start,+ end_page_id=window.end,+ image_type="pil_img",+ )if len(window_pages) != len(images_list):raise ValueError("Hybrid processing window PDF page count does not match image count")images_pil_list = [image_dict["img_pil"] for image_dict in images_list]@@ -369,35 +381,38 @@ def _prepare_pdf_window(if local_model_context is None:raise ValueError("Hybrid local model context is required outside Flash TXT mode")np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]- images_layout_res = local_model_context.layout_model.batch_predict(- images_pil_list, batch_size=min(8, BATCH_RATIO * LAYOUT_BASE_BATCH_SIZE)- )+ with stage_timer("pdf.layout"):+ images_layout_res = local_model_context.layout_model.batch_predict(+ images_pil_list, batch_size=min(8, BATCH_RATIO * LAYOUT_BASE_BATCH_SIZE)+ )# 使用小模型layout时对layout的表格做旋转检测if effort in ["flash", "medium", "high"]:table_items = _collect_table_items(images_layout_res, np_images)if table_items:- _apply_table_orientations(- table_items,- parse_mode,- window_pages,- images_list,- local_model_context,- page_text_geometries,- )+ with stage_timer("pdf.table_orientation"):+ _apply_table_orientations(+ table_items,+ parse_mode,+ window_pages,+ images_list,+ local_model_context,+ page_text_geometries,+ )vl_style_layout_blocks = _build_vl_style_layout_blocks(images_layout_res, images_pil_list)if parse_mode == "txt" and effort in {"medium", "high"}:- native_table_summary = _apply_native_txt_table_priority(- vl_style_layout_blocks,- images_layout_res,- window_pages,- images_list,- effort=effort,- page_text_geometries=page_text_geometries,- page_vector_geometries=page_vector_geometries,- )+ with stage_timer("pdf.native_tables"):+ native_table_summary = _apply_native_txt_table_priority(+ vl_style_layout_blocks,+ images_layout_res,+ window_pages,+ images_list,+ effort=effort,+ page_text_geometries=page_text_geometries,+ page_vector_geometries=page_vector_geometries,+ )if native_table_summary.total:native_table_stats = {"effort": effort,@@ -512,18 +527,20 @@ def _finish_pdf_window()if effort in {"medium", "high"}:- _apply_seal_ocr(local_model_context, window_model_list, np_images)+ with stage_timer("pdf.seals"):+ _apply_seal_ocr(local_model_context, window_model_list, np_images)elif effort == "xhigh":_supplement_missing_image_block_containers(window_model_list,vl_style_layout_blocks,)- _attach_visual_block_images(- window_model_list,- images_list,- page_start_index=window.start,- )+ with stage_timer("pdf.image_assets"):+ _attach_visual_block_images(+ window_model_list,+ images_list,+ page_start_index=window.start,+ )return window_model_listdiff --git a/mineru/model/runtime/hybrid.py b/mineru/model/runtime/hybrid.pyindex ddb3d424..c7f7bdae 100644--- a/mineru/model/runtime/hybrid.py+++ b/mineru/model/runtime/hybrid.py@@ -11,6 +11,8 @@ from typing import TYPE_CHECKING, Anyfrom loguru import logger+from ...utils.timing import stage_timer+from ..ocr.language import normalize_ocr_model_langfrom ..ocr.resources import PPOCRV6_DICT_PATHfrom ..registry import MINERU_4_MODELS_ONNX, small_model_repo@@ -225,6 +227,7 @@ class AtomModelSingleton:return self._models[key]+@stage_timer("model.initialize")def atom_model_init(model_name: str, **kwargs: Any) -> Any:"""将原子模型名称分派到具体初始化函数,并校验初始化结果。"""small_backend = resolve_small_model_backend(kwargs.get("small_backend"))diff --git a/mineru/model/runtime/onnx.py b/mineru/model/runtime/onnx.pyindex 20819223..419d5d23 100644--- a/mineru/model/runtime/onnx.py+++ b/mineru/model/runtime/onnx.py@@ -1,9 +1,12 @@# Copyright (c) Opendatalab. All rights reserved.-"""ONNX Runtime CPU 会话与线程配置。"""+"""ONNX Runtime CPU 会话与可选的表格 CUDA 会话。"""import os+import time+from pathlib import Pathimport onnxruntime as ort+from loguru import loggerdef get_op_num_threads(env_name: str) -> int:@@ -37,4 +40,63 @@ def ort_session(model_path: str, device: str | None = None, intra_op_num_threadsreturn ort.InferenceSession(model_path, sess_options=opts, providers=ort_providers(device))-__all__ = ["get_op_num_threads", "ort_providers", "ort_session"]+def table_ort_session(model_path: str, *, sess_options: ort.SessionOptions | None = None) -> ort.InferenceSession:+ """表格独立选择 CPU/CUDA;创建失败或 provider 静默降级时明确记录并保留 CPU 回退。"""+ device = os.getenv("MINERU_TABLE_DEVICE", "cpu").strip().lower()+ if device not in {"cpu", "cuda"}:+ raise ValueError("MINERU_TABLE_DEVICE must be 'cpu' or 'cuda'")+ opts = sess_options if sess_options is not None else ort.SessionOptions()+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL+ opts.log_severity_level = 3+ for attr, env_name in (+ ("intra_op_num_threads", "MINERU_INTRA_OP_NUM_THREADS"),+ ("inter_op_num_threads", "MINERU_INTER_OP_NUM_THREADS"),+ ):+ threads = get_op_num_threads(env_name)+ if threads > 0:+ setattr(opts, attr, threads)+ profile_dir = os.getenv("MINERU_ONNX_PROFILE_DIR")+ if profile_dir:+ Path(profile_dir).mkdir(parents=True, exist_ok=True)+ opts.enable_profiling = True+ opts.profile_file_prefix = str(Path(profile_dir) / f"{Path(model_path).stem}-{os.getpid()}")+ providers = ort_providers()+ if device == "cuda":+ if "CUDAExecutionProvider" in ort.get_available_providers():+ providers = [+ (+ "CUDAExecutionProvider",+ {+ "device_id": 0,+ "cudnn_conv_algo_search": "HEURISTIC",+ "do_copy_in_default_stream": True,+ "arena_extend_strategy": "kSameAsRequested",+ },+ ),+ *providers,+ ]+ else:+ logger.warning("Table CUDA unavailable; falling back to CPU: {}", model_path)+ started = time.perf_counter()+ try:+ session = ort.InferenceSession(model_path, sess_options=opts, providers=providers)+ except Exception as exc:+ if device != "cuda" or providers == ort_providers():+ raise+ logger.warning("Table CUDA initialization failed; falling back to CPU: {}: {}", model_path, exc)+ session = ort.InferenceSession(model_path, sess_options=opts, providers=ort_providers())+ actual = session.get_providers()+ if device == "cuda" and "CUDAExecutionProvider" not in actual:+ logger.warning("Table requested CUDA but actual providers are {}: {}", actual, model_path)+ logger.info(+ "Table ONNX ready: model={}, requested={}, providers={}, init_s={:.3f}, pid={}",+ Path(model_path).name,+ device,+ actual,+ time.perf_counter() - started,+ os.getpid(),+ )+ return session+++__all__ = ["get_op_num_threads", "ort_providers", "ort_session", "table_ort_session"]diff --git a/mineru/model/table/cls/paddle_table_cls.py b/mineru/model/table/cls/paddle_table_cls.pyindex 17e337ad..07e412cf 100644--- a/mineru/model/table/cls/paddle_table_cls.py+++ b/mineru/model/table/cls/paddle_table_cls.py@@ -5,15 +5,15 @@ from PIL import Imagefrom tqdm import tqdmfrom ...registry import small_model_repo-from ...runtime.onnx import ort_session+from ...runtime.onnx import table_ort_sessionclass PaddleTableClsModel:def __init__(self, *, model_path: str | None = None) -> None:- """加载所选模型栈的表格分类文件,始终通过 CPU 推理。"""+ """加载所选模型栈的表格分类文件,使用表格专用设备策略。"""from ...runtime.contracts import AtomicModelName- self.sess = ort_session(model_path or str(small_model_repo().paddle_table_cls.ensure()))+ self.sess = table_ort_session(model_path or str(small_model_repo().paddle_table_cls.ensure()))self.less_length = 256self.cw, self.ch = 224, 224self.std = [0.229, 0.224, 0.225]diff --git a/mineru/model/table/rec/slanet_plus/table_structure_utils.py b/mineru/model/table/rec/slanet_plus/table_structure_utils.pyindex c4cda6d2..404956a8 100644--- a/mineru/model/table/rec/slanet_plus/table_structure_utils.py+++ b/mineru/model/table/rec/slanet_plus/table_structure_utils.py@@ -19,22 +19,22 @@ from typing import Any, Dict, List, Tuple, Unionimport cv2import numpy as npfrom loguru import logger-from onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptions+from onnxruntime import GraphOptimizationLevel, SessionOptions-from ....runtime.onnx import ort_providers+from ....runtime.onnx import table_ort_sessionclass OrtInferSession:def __init__(self, config: Dict[str, Any]):+ """保留原有会话选项,并使用统一的表格设备与回退策略。"""self.logger = loggermodel_path = config.get("model_path", None)self._verify_model(model_path)- self.session = InferenceSession(+ self.session = table_ort_session(model_path,sess_options=self._init_sess_opts(config),- providers=ort_providers(),)@staticmethoddiff --git a/mineru/model/table/rec/unet_table/utils.py b/mineru/model/table/rec/unet_table/utils.pyindex eea1cba9..61e25978 100644--- a/mineru/model/table/rec/unet_table/utils.py+++ b/mineru/model/table/rec/unet_table/utils.py@@ -8,22 +8,24 @@ from typing import Any, Dict, List, Optional, Unionimport cv2import loguruimport numpy as np-from onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptions+from onnxruntime import GraphOptimizationLevel, SessionOptionsfrom PIL import Image, UnidentifiedImageError+from ....runtime.onnx import table_ort_session+root_dir = Path(__file__).resolve().parentInputType = Union[str, np.ndarray, bytes, Path]class OrtInferSession:def __init__(self, config: Dict[str, Any]):+ """保留原有会话选项,并使用统一的表格设备与回退策略。"""self.logger = loguru.loggermodel_path = config.get("model_path", None)- self.session = InferenceSession(+ self.session = table_ort_session(model_path,sess_options=self._init_sess_opts(config),- providers=[("CPUExecutionProvider", {"arena_extend_strategy": "kSameAsRequested"})],)@staticmethoddiff --git a/mineru/utils/timing.py b/mineru/utils/timing.pynew file mode 100644index 00000000..a77ac0b4--- /dev/null+++ b/mineru/utils/timing.py@@ -0,0 +1,25 @@+"""按需记录阶段墙钟耗时,不同步 CUDA,也不改变推理结果。"""++from __future__ import annotations++import os+import time+from collections.abc import Iterator+from contextlib import contextmanager++from loguru import logger+++@contextmanager+def stage_timer(stage: str) -> Iterator[None]:+ """仅在诊断开关开启时记录完整阶段耗时,包含惰性初始化与 CPU 准备工作。"""+ enabled = os.getenv("MINERU_PROFILE_STAGES", "").lower() in {"1", "true", "yes"}+ started = time.perf_counter() if enabled else 0.0+ try:+ yield+ finally:+ if enabled:+ logger.info("MinerU stage: name={}, elapsed_s={:.6f}, pid={}", stage, time.perf_counter() - started, os.getpid())+++__all__ = ["stage_timer"]diff --git a/tests/unittest/test_table_onnx_runtime.py b/tests/unittest/test_table_onnx_runtime.pynew file mode 100644index 00000000..d7c8e30e--- /dev/null+++ b/tests/unittest/test_table_onnx_runtime.py@@ -0,0 +1,86 @@+"""表格 CUDA provider 的显式选择、回退与 CPU 模型边界。"""++from types import SimpleNamespace+from unittest.mock import Mock+from pathlib import Path++import pytest++from mineru.model.runtime import onnx+++def test_table_default_is_cpu(monkeypatch: pytest.MonkeyPatch) -> None:+ """Torch 使用 CUDA 不应隐式改变表格模型设备。"""+ monkeypatch.delenv("MINERU_TABLE_DEVICE", raising=False)+ monkeypatch.setenv("MINERU_DEVICE_MODE", "cuda")+ session = SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"])+ factory = Mock(return_value=session)+ monkeypatch.setattr(onnx.ort, "InferenceSession", factory)+ assert onnx.table_ort_session("model.onnx") is session+ assert factory.call_args.kwargs["providers"] == onnx.ort_providers()+++def test_cuda_is_explicit_and_other_onnx_models_stay_cpu(monkeypatch: pytest.MonkeyPatch) -> None:+ """表格 CUDA 使用低冷启动开销选项,OCR/Layout ONNX 仍保留 CPU 策略。"""+ monkeypatch.setenv("MINERU_TABLE_DEVICE", "cuda")+ monkeypatch.setenv("MINERU_INTRA_OP_NUM_THREADS", "4")+ monkeypatch.setenv("MINERU_INTER_OP_NUM_THREADS", "1")+ monkeypatch.setattr(onnx.ort, "get_available_providers", lambda: ["CUDAExecutionProvider", "CPUExecutionProvider"])+ factory = Mock(return_value=SimpleNamespace(get_providers=lambda: ["CUDAExecutionProvider", "CPUExecutionProvider"]))+ monkeypatch.setattr(onnx.ort, "InferenceSession", factory)+ onnx.table_ort_session("model.onnx")+ call = factory.call_args.kwargs+ assert call["providers"][0][0] == "CUDAExecutionProvider"+ assert call["providers"][0][1]["cudnn_conv_algo_search"] == "HEURISTIC"+ assert call["sess_options"].intra_op_num_threads == 4+ assert call["sess_options"].inter_op_num_threads == 1+ onnx.ort_session("ocr.onnx", device="cuda")+ assert factory.call_args.kwargs["providers"] == onnx.ort_providers()++[email protected]("mode", ["unavailable", "exception", "silent"])+def test_cuda_failure_is_reported_and_cpu_remains_available(monkeypatch: pytest.MonkeyPatch, mode: str) -> None:+ """覆盖未安装 CUDA、动态库失败以及 ORT 自动降级,不能把回退误报为 GPU。"""+ monkeypatch.setenv("MINERU_TABLE_DEVICE", "cuda")+ monkeypatch.setattr(+ onnx.ort,+ "get_available_providers",+ lambda: ["CPUExecutionProvider"] if mode == "unavailable" else ["CUDAExecutionProvider"],+ )+ cpu = SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"])+ factory = Mock(side_effect=[RuntimeError("missing CUDA library"), cpu] if mode == "exception" else None, return_value=cpu)+ warning = Mock()+ monkeypatch.setattr(onnx.ort, "InferenceSession", factory)+ monkeypatch.setattr(onnx.logger, "warning", warning)+ assert onnx.table_ort_session("table.onnx") is cpu+ assert warning.called+ if mode in {"unavailable", "exception"}:+ assert factory.call_args.kwargs["providers"] == onnx.ort_providers()+++def test_invalid_device_fails_before_session_creation(monkeypatch: pytest.MonkeyPatch) -> None:+ """设备拼写错误不能静默退化成 CPU。"""+ monkeypatch.setenv("MINERU_TABLE_DEVICE", "cdua")+ factory = Mock()+ monkeypatch.setattr(onnx.ort, "InferenceSession", factory)+ with pytest.raises(ValueError, match="MINERU_TABLE_DEVICE"):+ onnx.table_ort_session("model.onnx")+ factory.assert_not_called()+++def test_all_table_wrappers_use_shared_factory(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """分类、有线和无线表格三个实际入口都必须经过同一个 provider 决策。"""+ from mineru.model.table.cls import paddle_table_cls+ from mineru.model.table.rec.slanet_plus import table_structure_utils+ from mineru.model.table.rec.unet_table import utils++ path = tmp_path / "table.onnx"+ path.touch()+ factory = Mock()+ for module in (paddle_table_cls, table_structure_utils, utils):+ monkeypatch.setattr(module, "table_ort_session", factory)+ paddle_table_cls.PaddleTableClsModel(model_path=str(path))+ table_structure_utils.OrtInferSession({"model_path": str(path)})+ utils.OrtInferSession({"model_path": str(path)})+ assert factory.call_count == 3+ assert all(call.args == (str(path),) for call in factory.call_args_list)