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
feat(hardware): enhance hardware info collection with parallel probes and structured output
myhlolic9cec90c681c
diff --git a/docs/next/cli/mineru-kit-hardware.md b/docs/next/cli/mineru-kit-hardware.mdindex 870d656d..3c732efe 100644--- a/docs/next/cli/mineru-kit-hardware.md+++ b/docs/next/cli/mineru-kit-hardware.md@@ -11,7 +11,7 @@ mineru-kit hardware infomineru-kit hardware info --json > hardware-info.json```-`hardware` 不带子命令时显示帮助。没有 `--quiet` 或 `auto-tier` 别名。配置沿用 `MINERU_CONFIG`、`MINERU_HOME` 和现有后端/设备环境变量。+`hardware` 不带子命令时显示帮助。根帮助及各级硬件帮助按需加载命令描述,不读取用户配置或启动硬件探测。没有 `--quiet` 或 `auto-tier` 别名。配置沿用 `MINERU_CONFIG`、`MINERU_HOME` 和现有后端/设备环境变量。## 自动推荐@@ -40,21 +40,27 @@ JSON 报告保持 `schema_version=1`,包含 `ceiling`、`pdf_image_tiers`、`d## 环境报告-`info` 不调用自动推荐或 OCR 校准,不下载、加载模型权重或写配置。运行时导入和原生 GPU 探测使用独立子进程,每项最多等待 15 秒。某项失败时继续报告其他信息,并区分未安装、导入失败和超时。+`info` 不调用自动推荐或 OCR 校准,不下载、加载模型权重或写配置。运行时导入和原生 GPU 探测使用独立子进程,最多并发 4 项,并与系统信息采集重叠进行;每项子进程启动后最多等待 15 秒。某项失败时继续报告其他信息,并区分未安装、导入失败和超时。-- 系统、Python 版本与解释器路径,MinerU 版本与实际模块路径。-- CPU 型号、物理/逻辑/进程可用核数,基础/当前/最大频率(MHz);内存总量及可用量(bytes)。+默认文本先输出系统、Python 和 MinerU 版本,再依次输出 CPU/内存、已安装软件、完成合并的显卡库存、运行时探测、有效配置及设备选择与校准信息。每节完成后立即刷新,重定向到管道时也无需等到整份报告完成。`--json` 仍一次输出完整对象,原有字段和结果顺序保持稳定,`schema_version=1`;ONNX 运行时结果补充 `selected_device`,记录只读选型及原因。++- 系统、Python 和 MinerU 版本;JSON 额外保留解释器与实际模块路径。+- CPU 型号、物理/逻辑/进程可用核数,基础/当前/最大频率(MHz);内存总量及可用量。文本容量统一按 `1024³` 换算为三位小数的 GiB,JSON 保留原始字节数。- 系统可探测到的全部独显、集显和虚拟 GPU,以及当前进程运行时可用设备。保留名称、身份、驱动及可获得的显存/共享内存信息。- GPU 的 `kind` 与选型共用同一套分类;`kind_source` 标识分类来源,`source` 保留硬件资料的采集来源,`unified_memory` 单独记录已知的统一内存属性。-- 已安装的软件包版本与位置:MinerU、DocVortex、mineru-llama-cpp、mineru-vl-utils、torch、transformers、ONNX Runtime及EP、vLLM、LMDeploy、mlx-vlm、pypdfium2。未安装的包不列入软件版本列表。+- 已安装的软件包版本:MinerU、DocVortex、mineru-llama-cpp、mineru-vl-utils、torch、transformers、ONNX Runtime及EP、vLLM、LMDeploy、mlx-vlm、pypdfium2。JSON 额外保留安装位置,未安装的包不列入软件版本列表。- Torch 导入、编译使用的 CUDA/ROCm 版本和后端可用性;ORT provider 与相关引擎的探测结果。- 后端、设备、线程及可见设备限制的有效配置与来源;OCR 校准记录的存在状态、环境匹配、稳定性、耗时和阈值。+“设备选择与校准”展示当前小模型后端、设备及选择依据。Torch 直接使用运行时的设备检查结果,并说明不适用 ONNX OCR 校准;ONNX 复用实际选型的候选规则,解释显式 CPU/GPU、独显免校准、不可用或待校准的情况。只读检查不会初始化 GPU 推理会话;需要测速时,设备显示“待校准”(JSON `selected_device.device` 为 `null`),不预先声称 CPU 或 GPU 胜出。++存在有效校准记录时展开详细信息;没有详细记录时仅展示设备选择与原因,不列出空的测速字段。损坏或不可读的记录保留路径及错误。当前为 Torch 时,已有 ONNX 记录明确标注为不参与当前选择。JSON 的原始 `calibration` 对象仍保留全部字段。+未知值为 JSON `null`,文本显示“未知”。例如 Apple Silicon 通常不报告可可靠读取的 CPU 主频,统一内存也不作为独立显存。系统或容器限制导致库存不完整时保留错误说明;不从型号名称猜测设备类型或频率。独立显存采集能力和 Windows PCI 身份修复继续保留,其结果不参与自动 tier。Windows 原生查询不依赖 Torch:DXGI 库存通过 `D3DKMTOpenAdapterFromLuid` / `D3DKMTQueryAdapterInfo(KMTQAITYPE_ADAPTERADDRESS)` 补充物理 PCI 位置,内存仍由对应适配器的 DXGI 接口读取。身份匹配优先使用 LUID 和已知 PCI 坐标,不猜测缺失字段;查询失败或多个同等匹配保留未知。读取预算成功不代表模型推理已验证。-配置报告使用明确白名单,不输出认证信息、完整远程服务地址或整个环境变量集合。诊断报告中的本地路径用于确认解释器和实际加载位置。+配置报告使用明确白名单,不输出认证信息、完整远程服务地址或整个环境变量集合。文本隐藏解释器、模块和软件安装路径,保留配置文件及校准记录路径;JSON 中的完整本地路径仍可用于确认解释器和实际加载位置。## 退出码diff --git a/mineru/cli/version_command.py b/mineru/cli/version_command.pyindex ee26becf..9a9f8802 100644--- a/mineru/cli/version_command.py+++ b/mineru/cli/version_command.py@@ -9,7 +9,6 @@ import typerfrom ..utils.i18n import tfrom .contracts import CliContext-from .runtime import run_cli__all__ = ["VersionInfo", "render_version", "show_version", "version_cmd", "version_info"]@@ -44,5 +43,7 @@ def show_version(ctx: typer.Context, value: bool) -> None:def version_cmd(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:"""Print MinerU and Python versions."""+ from .runtime import run_cli+ctx = CliContext(json_mode=json_mode)run_cli(ctx, version_info, render=render_version)diff --git a/mineru/kit/commands/__init__.py b/mineru/kit/commands/__init__.pyindex e9ab8261..14d6f7a3 100644--- a/mineru/kit/commands/__init__.py+++ b/mineru/kit/commands/__init__.py@@ -1,5 +1,3 @@"""mineru-kit command modules."""-from . import api_server, file_parse_server, hardware, models, parse, router, vlm_server, webui-__all__ = ["api_server", "file_parse_server", "hardware", "models", "parse", "router", "vlm_server", "webui"]diff --git a/mineru/kit/commands/_base.py b/mineru/kit/commands/_base.pynew file mode 100644index 00000000..9f86d1f1--- /dev/null+++ b/mineru/kit/commands/_base.py@@ -0,0 +1,32 @@+"""Kit 命令的运行阶段初始化,不影响帮助参数解析。"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from typer import Context+from typer.core import TyperCommand+++@dataclass(frozen=True)+class KitContext:+ """由控制台入口显式启用进程日志初始化,嵌入应用时保留宿主日志配置。"""++ configure_logging: bool = False+++class RuntimeCommand(TyperCommand):+ """仅在叶子命令真正执行时初始化日志,帮助无需读取用户配置。"""++ def invoke(self, ctx: Context) -> Any:+ """参数与帮助处理完成后配置日志,然后调用原始命令。"""+ options = ctx.find_object(KitContext)+ if options is not None and options.configure_logging:+ from ...utils.logger import configure_global_log_level++ configure_global_log_level()+ return super().invoke(ctx)+++__all__ = ["KitContext", "RuntimeCommand"]diff --git a/mineru/kit/commands/hardware.py b/mineru/kit/commands/hardware.pyindex 40eb1032..f3712dc9 100644--- a/mineru/kit/commands/hardware.py+++ b/mineru/kit/commands/hardware.py@@ -3,15 +3,24 @@from __future__ import annotationsfrom dataclasses import asdict-from typing import Any+from functools import partial+import sys+from typing import TYPE_CHECKING, Anyimport typerfrom ...cli.contracts import CliContext-from ...cli.runtime import run_clifrom ...utils.i18n import t+from ._base import RuntimeCommand-app = typer.Typer(help=t("Detect recommended tiers or inspect hardware and runtime information."), no_args_is_help=True)+if TYPE_CHECKING:+ from ...model.runtime.hardware_types import HardwareInfoSection++app = typer.Typer(+ help=t("Detect recommended tiers or inspect hardware and runtime information."),+ no_args_is_help=True,+ add_completion=False,+)def _value(value: Any) -> str:@@ -41,55 +50,169 @@ def render_detection(data: dict[str, Any]) -> str:return "\n".join(lines)-def render_info(data: dict[str, Any]) -> str:- """使用与 JSON 相同的字段生成可复制的问题反馈文本。"""- cpu, memory = data["cpu"], data["memory"]- lines = [- f"系统:{data['system']['name']} {data['system']['release']} ({data['system']['architecture']})",- f"系统版本:{_value(data['system'].get('os_version'))}",- f"发行版:{_value(data['system']['distribution'])}",- f"Python:{data['python']['version']} ({data['python']['executable']})",- f"MinerU:{data['mineru']['version']} ({data['mineru']['module_path']})",- f"CPU:{_value(cpu['model'])}",- f"CPU 核数:物理 {_value(cpu['physical_cores'])},逻辑 {_value(cpu['logical_cores'])},"- f"进程可用 {_value(cpu['available_cores'])}",- f"CPU 频率 (MHz):基础 {_value(cpu['base_mhz'])},当前 {_value(cpu['current_mhz'])},最大 {_value(cpu['max_mhz'])}",- f"内存 (bytes):总量 {_value(memory['total_bytes'])},可用 {_value(memory['available_bytes'])}",- "系统显卡:",- ]- if not data["gpus"]:- lines.append(" 未发现;如有探测错误,请参见提示")- for gpu in data["gpus"]:+def _memory(value: int | None) -> str:+ """将已知字节容量转换为三位小数的 GiB,未知值不附加伪造单位。"""+ return "未知" if value is None else f"{value / 1024**3:.3f} GiB"+++def _runtime_value(value: Any) -> str:+ """递归隐藏运行时模块路径并格式化容量,不修改原始探测数据。"""+ if isinstance(value, dict):+ fields = []+ for key, item in value.items():+ if key == "module_path":+ continue+ label = key.removesuffix("_bytes")+ rendered = _memory(item) if key.endswith("_bytes") else _runtime_value(item)+ fields.append(f"{label}: {rendered}")+ return "{" + ", ".join(fields) + "}"+ if isinstance(value, (list, tuple)):+ return "[" + ", ".join(_runtime_value(item) for item in value) + "]"+ return _value(value)+++def _render_device_selection(data: dict[str, Any]) -> list[str]:+ """展示当前后端的只读设备选择;仅在存在校准证据时展开详细记录。"""+ backend = (data["effective_config"].get("resolved") or {}).get("small_backend")+ probe = next((probe for probe in data["runtimes"] if probe["name"] == backend), None)+ selection = probe["data"].get("selected_device") if probe and probe["status"] == "ok" else None+ lines = ["设备选择与校准:", f" 小模型后端:{_value(backend)}"]+ reason = selection.get("reason") if selection else None+ reasons = {+ "torch_accelerator": "Torch 加速设备可用",+ "torch_cpu": "未发现可用的 Torch 加速设备,使用 CPU",+ "torch_device_unavailable": "指定的 Torch 设备不可用,回退 CPU",+ "torch_device_error": "Torch 设备检查失败,回退 CPU",+ "configured_cpu": "配置指定使用 CPU",+ "configured_gpu": "配置指定使用 GPU,跳过自动测速",+ "discrete_gpu": "已确认的候选独显满足免校准规则",+ "unsupported_platform": "当前平台不支持 ONNX GPU 路径,使用 CPU",+ "directml_unavailable": "DirectML provider 不可用,使用 CPU",+ "no_hardware_gpu": "未发现可用的 ONNX GPU,使用 CPU",+ "webgpu_architecture_policy": "没有通过 WebGPU 架构与可见性检查的 GPU,使用 CPU",+ "calibration_required": "候选 GPU 需要 OCR 校准后才能确定最终设备",+ "calibration_pending": "当前后端尚未配置可用的校准阈值",+ "selection_unavailable": "设备探测失败,无法确定选择结果",+ }+ if selection:+ device = selection.get("device")+ if reason in {"calibration_required", "calibration_pending"}:+ device = "待校准"+ elif backend == "onnx" and device == "gpu":+ device = f"{selection['backend']}:gpu"+ lines.append(f" 选择设备:{_value(device)}")+ lines.append(f" 选择依据:{reasons.get(reason, _value(reason))} ({_value(reason)})")+ if selection.get("warning"):+ lines.append(f" 设备提示:{selection['warning']}")+ if backend == "onnx" and selection.get("device") == "gpu":+ lines.append(" 验证范围:只读选型,尚未验证 GPU 推理会话")+ else:+ lines.append(" 选择设备:未知")+ detail = f"{probe['status']},{_value(probe['error'])}" if probe else "未取得对应运行时的设备选择结果"+ lines.append(f" 选择依据:{detail}")++ if backend == "torch":+ lines.append(" 校准:不适用(Torch 后端无需 ONNX OCR 校准)")+ elif reason in {"discrete_gpu", "configured_gpu"}:+ lines.append(" 校准:免校准")+ elif reason in {"calibration_required", "calibration_pending"}:+ lines.append(" 校准:待完成(info 只读检查不会执行测速)")+ elif selection and selection.get("device") == "cpu":+ lines.append(" 校准:未执行(当前选择 CPU)")++ calibration = data["calibration"]+ if calibration["status"] == "present":+ label = "ONNX 校准记录(不参与当前 Torch 设备选择)" if backend == "torch" else "ONNX 校准记录"+ lines.append(f" {label}:")+ lines.extend(f" {key}: {_value(value)}" for key, value in calibration.items() if value is not None)+ elif calibration["status"] == "invalid":lines.extend([- f" {_value(gpu['name'])} [{gpu['kind']}],厂商 {_value(gpu['vendor'])},标识 {_value(gpu['device_id'])}",- f" 来源 {gpu['source']},驱动 {_value(gpu['driver'])},总线 {_value(gpu['bus_id'])}",- f" 独立显存 {_value(gpu['dedicated_memory_bytes'])} bytes,"- f"共享内存 {_value(gpu['shared_memory_bytes'])} bytes,统一内存 {_value(gpu['unified_memory'])}",+ " 校准记录:不可用",+ f" path: {calibration['path']}",+ f" error: {_value(calibration['error'])}",])- lines.append("已安装软件:")- lines.extend(f" {package['name']} {package['version']} ({package['location']})" for package in data["packages"])- lines.append("当前进程运行时探测:")- for probe in data["runtimes"]:- lines.append(f" {probe['name']}: {probe['status']}")- if probe["error"]:- lines.append(f" {probe['error']}")- for key, value in probe["data"].items():- lines.append(f" {key}: {_value(value)}")- lines.append("有效配置:")+ elif backend != "torch" and reason not in {"discrete_gpu", "configured_gpu"}:+ lines.append(" 校准记录:无详细记录")+ return lines+++def _render_info_section(section: HardwareInfoSection, data: dict[str, Any]) -> str:+ """用统一分节渲染实现完整报告与逐段输出,保持文本字段和顺序一致。"""+ if section == "environment":+ return "\n".join(+ [+ f"系统:{data['system']['name']} {data['system']['release']} ({data['system']['architecture']})",+ f"系统版本:{_value(data['system'].get('os_version'))}",+ f"发行版:{_value(data['system']['distribution'])}",+ f"Python:{data['python']['version']}",+ f"MinerU:{data['mineru']['version']}",+ ]+ )+ if section == "cpu_memory":+ cpu, memory = data["cpu"], data["memory"]+ return "\n".join(+ [+ f"CPU:{_value(cpu['model'])}",+ f"CPU 核数:物理 {_value(cpu['physical_cores'])},逻辑 {_value(cpu['logical_cores'])},"+ f"进程可用 {_value(cpu['available_cores'])}",+ f"CPU 频率 (MHz):基础 {_value(cpu['base_mhz'])},当前 {_value(cpu['current_mhz'])},"+ f"最大 {_value(cpu['max_mhz'])}",+ f"内存:总量 {_memory(memory['total_bytes'])},可用 {_memory(memory['available_bytes'])}",+ ]+ )+ if section == "packages":+ return "\n".join(["已安装软件:", *(f" {package['name']} {package['version']}" for package in data["packages"])])+ if section == "gpus":+ lines = ["系统显卡:"]+ if not data["gpus"]:+ lines.append(" 未发现;如有探测错误,请参见提示")+ for gpu in data["gpus"]:+ lines.extend(+ [+ f" {_value(gpu['name'])} [{gpu['kind']}],厂商 {_value(gpu['vendor'])},标识 {_value(gpu['device_id'])}",+ f" 来源 {gpu['source']},驱动 {_value(gpu['driver'])},总线 {_value(gpu['bus_id'])}",+ f" 独立显存 {_memory(gpu['dedicated_memory_bytes'])},"+ f"共享内存 {_memory(gpu['shared_memory_bytes'])},统一内存 {_value(gpu['unified_memory'])}",+ ]+ )+ return "\n".join(lines)+ if section == "runtimes":+ lines = ["当前进程运行时探测:"] if data.get("runtime_header", True) else []+ for probe in data["runtimes"]:+ lines.append(f" {probe['name']}: {probe['status']}")+ if probe["error"]:+ lines.append(f" {probe['error']}")+ for key, value in probe["data"].items():+ if key != "module_path":+ rendered = _memory(value) if key.endswith("_bytes") else _runtime_value(value)+ lines.append(f" {key.removesuffix('_bytes')}: {rendered}")+ return "\n".join(lines)+ lines = ["有效配置:"]lines.extend(f" {key}: {_value(value)}" for key, value in data["effective_config"].items())- lines.append("OCR 校准记录:")- lines.extend(f" {key}: {_value(value)}" for key, value in data["calibration"].items())+ lines.extend(_render_device_selection(data))lines.extend(f"提示:{warning}" for warning in data["warnings"])return "\n".join(lines)-def _info_data() -> dict[str, Any]:- """仅在执行 info 时惰性导入采集层,帮助入口保持无探测副作用。"""+def render_info(data: dict[str, Any]) -> str:+ """使用与 JSON 相同的原始数据生成精简路径和容量的完整文本报告。"""+ sections: tuple[HardwareInfoSection, ...] = ("environment", "cpu_memory", "packages", "gpus", "runtimes", "configuration")+ return "\n".join(_render_info_section(section, data) for section in sections)+++def _emit_info_section(section: HardwareInfoSection, data: dict[str, Any]) -> None:+ """每节完成后立即刷新 stdout,管道重定向时也能读取到早期结果。"""+ print(_render_info_section(section, data), file=sys.stdout, flush=True)+++def _info_data(*, stream: bool = False) -> dict[str, Any] | None:+ """文本逐节展示,JSON 仍返回完整报告;帮助入口不导入采集层。"""from ...model.runtime.hardware import collect_hardware_info- return asdict(collect_hardware_info())+ report = collect_hardware_info(on_section=_emit_info_section if stream else None)+ return None if stream else asdict(report)def _detect_data() -> dict[str, Any]:@@ -99,16 +222,24 @@ def _detect_data() -> dict[str, Any]:return run_detection()[email protected]("detect", help=t("Recommend the API tier ceiling using hardware and applicable OCR calibration."))+ "detect", cls=RuntimeCommand, help=t("Recommend the API tier ceiling using hardware and applicable OCR calibration.")+)def detect_cmd(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:"""执行与 API 自动启动一致的后端感知推荐。"""+ from ...cli.runtime import run_cli+run_cli(CliContext(json_mode=json_mode), _detect_data, render=render_detection)[email protected]("info", help=t("Read hardware, installed versions and runtime diagnostics without calibration."))+ "info", cls=RuntimeCommand, help=t("Read hardware, installed versions and runtime diagnostics without calibration.")+)def info_cmd(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:"""只读输出可用于问题反馈的环境报告。"""- run_cli(CliContext(json_mode=json_mode), _info_data, render=render_info)+ from ...cli.runtime import run_cli++ run_cli(CliContext(json_mode=json_mode), partial(_info_data, stream=not json_mode))__all__ = ["app", "detect_cmd", "info_cmd", "render_detection", "render_info"]diff --git a/mineru/kit/commands/models.py b/mineru/kit/commands/models.pyindex b5e1fcc9..c5d3d012 100644--- a/mineru/kit/commands/models.py+++ b/mineru/kit/commands/models.py@@ -27,8 +27,9 @@ from ...utils.logger import configure_global_log_levelfrom ...utils.stdio import configure_standard_streamsfrom ..errors import exit_with_messagefrom ..output import print_info, print_success+from ._base import RuntimeCommand-app = typer.Typer(help=t("Download, inspect, and verify local MinerU models."), no_args_is_help=True)+app = typer.Typer(help=t("Download, inspect, and verify local MinerU models."), no_args_is_help=True, add_completion=False)def _validate_download_source(source: str | None) -> str | None:@@ -82,7 +83,11 @@ def _format_repo_status(repo: ModelRepo) -> str:return f"{repo.name}: {status} ({repo.local_dir()})"[email protected]("download", help=t("Download an explicit repo or the tier resources required by the current backend combination."))+ "download",+ cls=RuntimeCommand,+ help=t("Download an explicit repo or the tier resources required by the current backend combination."),+)def download_cmd(repo: str | None = typer.Argument(None, help=t("Model repo: MinerU-4_models_torch, MinerU-4_models_onnx, or a VLM repo")),tier: str | None = typer.Option(None, "--tier", help=t("Model tier to prepare: basic or standard")),@@ -115,7 +120,7 @@ def download_cmd(print_success(t("Downloaded models for {label}.", label=label))[email protected]("show", help=t("Show configuration sources, effective backends, and tier resources."))[email protected]("show", cls=RuntimeCommand, help=t("Show configuration sources, effective backends, and tier resources."))def show_cmd(small_backend: str | None = typer.Option(None,@@ -169,7 +174,9 @@ def show_cmd(print_info(f" {tier}: {names}")[email protected]("verify", help=t("Verify local resources for an explicit repo or the current backend combination."))+ "verify", cls=RuntimeCommand, help=t("Verify local resources for an explicit repo or the current backend combination.")+)def verify_cmd(repo: str | None = typer.Argument(None, help=t("Optional model repo name")),tier: str | None = typer.Option(None, "--tier", help=t("Optional model tier: basic or standard")),diff --git a/mineru/kit/main.py b/mineru/kit/main.pyindex 3ca3dfee..ef65071c 100644--- a/mineru/kit/main.py+++ b/mineru/kit/main.py@@ -2,33 +2,86 @@from __future__ import annotations+from dataclasses import dataclass+from importlib import import_module+import typer-from click.core import Context-from typer.core import TyperGroup+from typer import Context+from typer.core import TyperCommand, TyperGroup+from typer.main import get_command-from ..cli.version_command import show_version, version_cmd+from ..cli.version_command import show_versionfrom ..utils.i18n import t-from ..utils.logger import configure_global_log_levelfrom ..utils.stdio import configure_standard_streams-from .commands import api_server, file_parse_server, hardware, models, parse, router, vlm_server, webui+from .commands._base import KitContext, RuntimeCommand+++@dataclass(frozen=True)+class CommandSpec:+ """显式声明命令入口和帮助文案,展示根帮助时无需导入命令实现。"""++ module: str+ attribute: str+ help: str+ group: bool = False+ context_settings_attribute: str | None = None-TOP_LEVEL_COMMAND_ORDER = [- "parse",- "webui",- "api-server",- "file-parse-server",- "vlm-server",- "router",- "models",- "hardware",- "version",-]++COMMANDS: dict[str, CommandSpec] = {+ "parse": CommandSpec(+ ".commands.parse", "parse_cmd", "Parse files or directories into markdown, middle JSON, or zip outputs."+ ),+ "webui": CommandSpec(+ ".commands.webui", "webui_cmd", "Start the Gradio document parsing web UI backed by the MinerU V1 API."+ ),+ "api-server": CommandSpec(".commands.api_server", "api_server_cmd", "Start the self-hosted MinerU parsing API service."),+ "file-parse-server": CommandSpec(+ ".commands.file_parse_server", "file_parse_server_cmd", "Start the synchronous single-file Tasks wrapper service."+ ),+ "vlm-server": CommandSpec(+ ".commands.vlm_server",+ "vlm_server_cmd",+ "Start the local VLM server with OpenAI-compatible chat completions.",+ context_settings_attribute="FORWARD_CONTEXT_SETTINGS",+ ),+ "router": CommandSpec(+ ".commands.router", "router_cmd", "Start a standalone Router service exposing only the MinerU V1 API."+ ),+ "models": CommandSpec(".commands.models", "app", "Download, inspect, and verify local MinerU models.", group=True),+ "hardware": CommandSpec(+ ".commands.hardware", "app", "Detect recommended tiers or inspect hardware and runtime information.", group=True+ ),+ "version": CommandSpec("..cli.version_command", "version_cmd", "Print MinerU and Python versions."),+}+TOP_LEVEL_COMMAND_ORDER = list(COMMANDS)class OrderedRootGroup(TyperGroup):+ """根帮助使用轻量命令描述,仅在解析选中的命令时加载完整参数定义。"""+def list_commands(self, ctx: Context) -> list[str]:- ordered = [name for name in TOP_LEVEL_COMMAND_ORDER if name in self.commands]- return ordered + [name for name in self.commands if name not in TOP_LEVEL_COMMAND_ORDER]+ """按产品顺序返回命令名称,不触发服务或模型模块导入。"""+ return list(TOP_LEVEL_COMMAND_ORDER)++ def get_command(self, ctx: Context, cmd_name: str) -> TyperCommand | None:+ """为帮助、补全和命令名称校验提供轻量描述。"""+ spec = COMMANDS.get(cmd_name)+ return TyperCommand(cmd_name, help=t(spec.help)) if spec is not None else None++ def resolve_command(self, ctx: Context, args: list[str]) -> tuple[str | None, TyperCommand | TyperGroup | None, list[str]]:+ """仅加载实际选中的入口,保留原始函数签名和转发参数设置。"""+ name, command, remaining = super().resolve_command(ctx, args)+ if name is None or command is None:+ return name, command, remaining+ spec = COMMANDS[name]+ module = import_module(spec.module, package=__package__)+ target = getattr(module, spec.attribute)+ if spec.group:+ return name, get_command(target), remaining+ selected = typer.Typer(add_completion=False)+ settings = getattr(module, spec.context_settings_attribute) if spec.context_settings_attribute else None+ selected.command(name, help=t(spec.help), cls=RuntimeCommand, context_settings=settings)(target)+ return name, get_command(selected), remainingapp = typer.Typer(@@ -50,31 +103,16 @@ def root(help=t("Show the version and exit."),),) -> None:- pass---app.add_typer(models.app, name="models")-app.add_typer(hardware.app, name="hardware")-app.command("parse", help=t("Parse files or directories into markdown, middle JSON, or zip outputs."))(parse.parse_cmd)-app.command("webui", help=t("Start the Gradio document parsing web UI backed by the MinerU V1 API."))(webui.webui_cmd)-app.command("api-server", help=t("Start the self-hosted MinerU parsing API service."))(api_server.api_server_cmd)-app.command(- "vlm-server",- context_settings=vlm_server.FORWARD_CONTEXT_SETTINGS,- help=t("Start the local VLM server with OpenAI-compatible chat completions."),-)(vlm_server.vlm_server_cmd)-app.command("router", help=t("Start a standalone Router service exposing only the MinerU V1 API."))(router.router_cmd)-app.command("file-parse-server", help=t("Start the synchronous single-file Tasks wrapper service."))(- file_parse_server.file_parse_server_cmd-)-app.command("version", help=t("Print MinerU and Python versions."))(version_cmd)+ """只声明根参数,帮助和版本查询不初始化运行环境。"""def main() -> None:+ """先配置输出编码,再由实际执行的叶子命令初始化日志。"""configure_standard_streams()- configure_global_log_level()- app()+ app(obj=KitContext(configure_logging=True))++__all__ = ["app", "main"]if __name__ == "__main__":main()diff --git a/mineru/model/runtime/hardware.py b/mineru/model/runtime/hardware.pyindex 15a3f2ae..3880e6c0 100644--- a/mineru/model/runtime/hardware.py+++ b/mineru/model/runtime/hardware.py@@ -3,6 +3,9 @@from __future__ import annotations+from collections.abc import Callable+from concurrent.futures import ThreadPoolExecutor+from dataclasses import asdictfrom importlib import metadataimport osfrom pathlib import Path@@ -12,7 +15,7 @@ from typing import TYPE_CHECKING, Anyfrom .hardware_probe import run_probefrom .hardware_system import collect_system_hardware-from .hardware_types import GpuInfo, HardwareInfo, PackageInfo, RuntimeProbe+from .hardware_types import GpuInfo, HardwareInfo, HardwareInfoSection, PackageInfo, RuntimeProbefrom .onnx_calibration_cache import inspect_calibration_recordfrom .gpu import GPU_KIND_ORDER, GpuIdentity, gpu_identities_match, match_gpu_identities@@ -147,11 +150,33 @@ def _calibration_adapters(probes: list[RuntimeProbe]) -> tuple[GpuAdapter | WebGreturn tuple(WebGPUDevice(**row) for row in rows)-def collect_hardware_info() -> HardwareInfo:- """汇总静态信息及有界运行时探测,单项失败保留其余诊断内容。"""+def collect_hardware_info(*, on_section: Callable[[HardwareInfoSection, dict[str, Any]], None] | None = None) -> HardwareInfo:+ """并行采集隔离探测,并按固定顺序通知已完成分节,仍返回完整原始报告。"""from ...version import __version__- native = collect_system_hardware()+ distribution = ""+ if sys.platform == "linux":+ try:+ distribution = platform.freedesktop_os_release().get("PRETTY_NAME", "")+ except OSError:+ pass+ system = {+ "name": platform.system(),+ "release": platform.release(),+ "version": platform.version(),+ "os_version": platform.mac_ver()[0]+ if sys.platform == "darwin"+ else platform.win32_ver()[1]+ if sys.platform == "win32"+ else platform.release(),+ "distribution": distribution,+ "architecture": platform.machine(),+ }+ python = {"version": platform.python_version(), "executable": sys.executable}+ mineru = {"version": __version__, "module_path": str(Path(__file__).resolve().parents[2] / "__init__.py")}+ if on_section:+ on_section("environment", {"system": system, "python": python, "mineru": mineru})+packages = installed_packages()names = {package.name for package in packages}runtime_names = ["selection", "torch", "onnx"]@@ -160,39 +185,47 @@ def collect_hardware_info() -> HardwareInfo:runtime_names.extend(name for name in ("vllm", "lmdeploy", "mlx-vlm") if name in names)if sys.platform in {"win32", "linux"}:runtime_names.append("dxgi" if sys.platform == "win32" else "vulkan")- probes = [run_probe(name) for name in runtime_names]- for probe in probes:- if probe.name in {"vulkan", "dxgi"}:- merge_gpu_inventory(native.gpus, probe)- if probe.status in {"error", "timeout"}:- native.warnings.append(f"{probe.name}: {probe.error}")- if probe.data.get("adapter_error"):- native.warnings.append(f"ONNX adapter inventory is incomplete: {probe.data['adapter_error']}")+ # 线程只调度隔离子进程;推理库与驱动仍不在报告进程内加载。+ with ThreadPoolExecutor(max_workers=4, thread_name_prefix="hardware-probe") as executor:+ futures = {name: executor.submit(run_probe, name) for name in runtime_names}+ native = collect_system_hardware()+ if on_section:+ on_section("cpu_memory", {"cpu": asdict(native.cpu), "memory": asdict(native.memory)})+ on_section("packages", {"packages": [asdict(package) for package in packages]})+ for name in ("vulkan", "dxgi"):+ if name in futures:+ merge_gpu_inventory(native.gpus, futures[name].result())+ if on_section:+ on_section("gpus", {"gpus": [asdict(gpu) for gpu in native.gpus]})++ probes = []+ for index, name in enumerate(runtime_names):+ probe = futures[name].result()+ probes.append(probe)+ if probe.status in {"error", "timeout"}:+ native.warnings.append(f"{probe.name}: {probe.error}")+ if probe.data.get("adapter_error"):+ native.warnings.append(f"ONNX adapter inventory is incomplete: {probe.data['adapter_error']}")+ if on_section:+ on_section("runtimes", {"runtimes": [asdict(probe)], "runtime_header": index == 0})config = config_summary()selection = next(probe for probe in probes if probe.name == "selection")config["resolved"] = selection.data if selection.status == "ok" else Nonecalibration = inspect_calibration_record(_calibration_adapters(probes))- distribution = ""- if sys.platform == "linux":- try:- distribution = platform.freedesktop_os_release().get("PRETTY_NAME", "")- except OSError:- pass+ if on_section:+ on_section(+ "configuration",+ {+ "effective_config": config,+ "calibration": asdict(calibration),+ "runtimes": [asdict(probe) for probe in probes],+ "warnings": native.warnings,+ },+ )return HardwareInfo(- system={- "name": platform.system(),- "release": platform.release(),- "version": platform.version(),- "os_version": platform.mac_ver()[0]- if sys.platform == "darwin"- else platform.win32_ver()[1]- if sys.platform == "win32"- else platform.release(),- "distribution": distribution,- "architecture": platform.machine(),- },- python={"version": platform.python_version(), "executable": sys.executable},- mineru={"version": __version__, "module_path": str(Path(__file__).resolve().parents[2] / "__init__.py")},+ system=system,+ python=python,+ mineru=mineru,cpu=native.cpu,memory=native.memory,gpus=native.gpus,diff --git a/mineru/model/runtime/hardware_probe.py b/mineru/model/runtime/hardware_probe.pyindex 8fa9d451..b9999a25 100644--- a/mineru/model/runtime/hardware_probe.py+++ b/mineru/model/runtime/hardware_probe.py@@ -10,7 +10,7 @@ import importlib.utilimport jsonimport subprocessimport sys-from typing import Any+from typing import Any, Literalfrom .hardware_types import RuntimeProbe@@ -68,6 +68,13 @@ def _onnx_probe() -> dict[str, Any]:"""检查 ORT provider 和适配器库存,不调用会触发校准的设备选择。"""import onnxruntime as ort+ from ...config import get_config+ from .onnx_device import inspect_onnx_candidate++ requested = get_config().model.onnx_device+ backend: Literal["dml", "webgpu"] | None = None+ selected = None+ has_devices = Falseresult: dict[str, Any] = {"version": ort.__version__,"module_path": ort.__file__,@@ -76,7 +83,9 @@ def _onnx_probe() -> dict[str, Any]:if sys.platform == "win32":from .windows_gpu import discover_gpus, preferred_gpu- adapters = discover_gpus()+ backend = "dml"+ # 显式 GPU 沿用运行时性能排序;CPU 模式仍保留分类库存以核对历史校准证据。+ adapters = discover_gpus(classify=requested != "gpu")selected = preferred_gpu(adapters)result["backend"] = "dml"result["adapters"] = [asdict(adapter) for adapter in adapters]@@ -84,13 +93,33 @@ def _onnx_probe() -> dict[str, Any]:elif sys.platform == "linux":from .webgpu import discover_webgpu_devices, select_webgpu_device+ backend = "webgpu"try:adapters = discover_webgpu_devices()+ has_devices = bool(adapters)selected = select_webgpu_device(adapters)result.update(backend="webgpu", adapters=[asdict(adapter) for adapter in adapters])result["selected_adapter"] = asdict(selected) if selected is not None else Noneexcept Exception as error:result["adapter_error"] = str(error)+ if result.get("adapter_error") and requested != "cpu":+ result["selected_device"] = {+ "device": None,+ "reason": "selection_unavailable",+ "warning": result["adapter_error"],+ }+ else:+ choice = inspect_onnx_candidate(+ requested,+ backend=backend,+ adapter=selected,+ provider_available="DmlExecutionProvider" in result["providers"],+ has_devices=has_devices,+ )+ result["selected_device"] = asdict(choice)+ if choice.reason in {"calibration_required", "calibration_pending"}:+ # 只读报告没有执行测速,不能把临时 CPU 占位值当作最终选择。+ result["selected_device"]["device"] = Nonereturn resultdiff --git a/mineru/model/runtime/hardware_types.py b/mineru/model/runtime/hardware_types.pyindex 6168144e..cde7431a 100644--- a/mineru/model/runtime/hardware_types.py+++ b/mineru/model/runtime/hardware_types.py@@ -4,11 +4,13 @@from __future__ import annotationsfrom dataclasses import dataclass, field-from typing import Any+from typing import Any, Literalfrom .onnx_calibration_cache import CalibrationInfofrom .gpu import GpuIdentity, GpuKind+HardwareInfoSection = Literal["environment", "cpu_memory", "packages", "gpus", "runtimes", "configuration"]+@dataclassclass CpuInfo:@@ -107,4 +109,13 @@ class HardwareInfo:schema_version: int = 1-__all__ = ["CpuInfo", "GpuInfo", "HardwareInfo", "MemoryInfo", "PackageInfo", "RuntimeProbe", "SystemHardware"]+__all__ = [+ "CpuInfo",+ "GpuInfo",+ "HardwareInfo",+ "HardwareInfoSection",+ "MemoryInfo",+ "PackageInfo",+ "RuntimeProbe",+ "SystemHardware",+]diff --git a/mineru/model/runtime/onnx_device.py b/mineru/model/runtime/onnx_device.pyindex aa2e0c7a..c0eba154 100644--- a/mineru/model/runtime/onnx_device.py+++ b/mineru/model/runtime/onnx_device.py@@ -72,42 +72,70 @@ def choose_gpu(cpu_elapsed: float, gpu_elapsed: float, threshold: float) -> boolreturn gpu_elapsed / cpu_elapsed <= threshold+def inspect_onnx_candidate(+ requested: str,+ *,+ backend: Literal["dml", "webgpu"] | None,+ adapter: GpuAdapter | WebGPUDevice | None = None,+ provider_available: bool = True,+ has_devices: bool = False,+) -> OnnxSelection:+ """按已采集的库存解释免校准路径;需测速时只报告待校准,不探测、下载或写配置。"""+ if requested == "cpu":+ return OnnxSelection(reason="configured_cpu")+ if backend is None:+ return OnnxSelection(reason="unsupported_platform")+ if backend == "dml" and not provider_available:+ return OnnxSelection(reason="directml_unavailable")+ if backend == "webgpu" and has_devices and adapter is None:+ return OnnxSelection(reason="webgpu_architecture_policy", backend=backend)+ if adapter is None:+ return OnnxSelection(reason="no_hardware_gpu")+ # Linux 只有唯一确认的 Vulkan 独显且会话带物理约束,才与 DML 独显一样免校准。+ discrete = is_discrete_gpu(adapter) and (+ not isinstance(adapter, WebGPUDevice) or adapter.vulkan_device == (adapter.vendor_id, adapter.device_id)+ )+ if requested == "gpu" or discrete:+ return OnnxSelection("gpu", adapter, "configured_gpu" if requested == "gpu" else "discrete_gpu", backend)+ if ONNX_GPU_TIME_RATIO_THRESHOLDS[backend] is None:+ return OnnxSelection(reason="calibration_pending")+ return OnnxSelection(reason="calibration_required", backend=backend)++def _select(requested: str, intra_op_num_threads: int, inter_op_num_threads: int, *, allow_download: bool = True) -> tuple[OnnxSelection, bool]:- if requested == "cpu":- return OnnxSelection(reason="configured_cpu"), False- if sys.platform not in {"win32", "linux"}:+ """复用只读候选规则,只有需要测速时才进入模型准备和校准流程。"""+ backend: Literal["dml", "webgpu"] | None = (+ "webgpu" if sys.platform == "linux" else "dml" if sys.platform == "win32" else None+ )+ if requested == "cpu" or backend is None:if requested == "gpu":logger.warning("ONNX GPU selection requires Windows DirectML or Linux WebGPU; using CPU")- return OnnxSelection(reason="unsupported_platform"), False- backend: Literal["dml", "webgpu"] = "webgpu" if sys.platform == "linux" else "dml"+ return inspect_onnx_candidate(requested, backend=backend), False+ has_devices = Falseif backend == "webgpu":devices = discover_webgpu_devices()+ has_devices = bool(devices)adapter = select_webgpu_device(devices)if devices and adapter is None:logger.info("Linux WebGPU device policy selected CPU; no eligible visible GPU")- return OnnxSelection(reason="webgpu_architecture_policy", backend=backend), Falseelse:import onnxruntime as ortif "DmlExecutionProvider" not in ort.get_available_providers():logger.warning("DirectML provider unavailable; using CPU without saving a performance decision")- return OnnxSelection(reason="directml_unavailable"), False+ return inspect_onnx_candidate(requested, backend=backend, provider_available=False), Falseadapter = preferred_gpu(discover_gpus(classify=requested == "auto"))- if adapter is None:- # A plugin can expose no devices after a driver discovery failure. Do not persist that as a CPU win.- return OnnxSelection(reason="no_hardware_gpu"), requested == "auto" and backend == "dml"- # Linux 只有唯一确认的 Vulkan 独显且会话带物理约束,才与 DML 独显一样免校准。- discrete = is_discrete_gpu(adapter) and (- not isinstance(adapter, WebGPUDevice) or adapter.vulkan_device == (adapter.vendor_id, adapter.device_id)- )- if requested == "gpu" or discrete:- return OnnxSelection("gpu", adapter, "configured_gpu" if requested == "gpu" else "discrete_gpu", backend), False+ selection = inspect_onnx_candidate(requested, backend=backend, adapter=adapter, has_devices=has_devices)+ if selection.reason != "calibration_required":+ if selection.reason == "calibration_pending":+ logger.warning("ONNX {} threshold has not completed calibration; using CPU without saving", backend)+ # 驱动发现失败不能作为 CPU 性能胜出的证据,保留原有 DML 空库存持久化规则。+ return selection, selection.reason == "no_hardware_gpu" and requested == "auto" and backend == "dml"+ assert adapter is not Nonethreshold = ONNX_GPU_TIME_RATIO_THRESHOLDS[backend]- if threshold is None:- logger.warning("ONNX {} threshold has not completed calibration; using CPU without saving", backend)- return OnnxSelection(reason="calibration_pending"), False+ assert threshold is not Nonefrom ..registry import MINERU_4_MODELS_ONNXfrom .onnx_calibration import run_calibration@@ -206,6 +234,7 @@ __all__ = ["choose_gpu","cached_onnx_device","confirm_gpu_session",+ "inspect_onnx_candidate","metacommands_enabled","resolve_onnx_device",]diff --git a/tests/unittest/test_hardware_info.py b/tests/unittest/test_hardware_info.pyindex 3ec91c5f..d19c9ac3 100644--- a/tests/unittest/test_hardware_info.py+++ b/tests/unittest/test_hardware_info.py@@ -2,12 +2,16 @@from __future__ import annotations+from collections.abc import Callable+from concurrent.futures import ThreadPoolExecutorfrom dataclasses import asdictfrom importlib import metadataimport jsonfrom pathlib import Pathimport subprocessimport sys+from threading import Event, Lock+from typing import Anyfrom types import SimpleNamespacefrom unittest.mock import Mock@@ -22,6 +26,7 @@ from mineru.model.runtime.hardware_types import (CpuInfo,GpuInfo,HardwareInfo,+ HardwareInfoSection,MemoryInfo,PackageInfo,RuntimeProbe,@@ -50,7 +55,15 @@ def _report() -> HardwareInfo:def test_info_command_output(monkeypatch: pytest.MonkeyPatch, json_mode: bool) -> None:"""文本与 JSON 均包含诊断信息,局部失败保留可用报告并返回成功。"""report = asdict(_report())- monkeypatch.setattr(command, "_info_data", lambda: report)++ def collect(*, on_section: Callable[[HardwareInfoSection, dict[str, Any]], None] | None = None) -> HardwareInfo:+ """模拟采集通知,分别验证文本流输出和完整 JSON 输出。"""+ if on_section:+ for section in ("environment", "cpu_memory", "packages", "gpus", "runtimes", "configuration"):+ on_section(section, report)+ return _report()++ monkeypatch.setattr(hardware, "collect_hardware_info", collect)result = CliRunner().invoke(app, ["hardware", "info", *(["--json"] if json_mode else [])])assert result.exit_code == 0, result.outputif json_mode:@@ -58,6 +71,8 @@ def test_info_command_output(monkeypatch: pytest.MonkeyPatch, json_mode: bool) -else:assert "test CPU" in result.stdout and "未知" in result.stdoutassert "driver unavailable" in result.stdout+ assert result.stdout.rstrip() == command.render_info(report)+ assert "/env" not in result.stdout and "/source" not in result.stdoutassert "vllm" not in result.stdout@@ -319,12 +334,338 @@ def test_info_partial_failure_is_read_only(tmp_path: Path, monkeypatch: pytest.Mforbidden.assert_not_called()-def test_help_imports_no_heavy_runtime() -> None:- """在新进程验证帮助不会提前导入 Torch、ORT 或原生 llama 运行时。"""+ "arguments",+ [+ [],+ ["--help"],+ ["--version"],+ ["hardware"],+ ["hardware", "--help"],+ ["hardware", "info", "--help"],+ ["hardware", "detect", "--help"],+ ],+)+def test_help_imports_no_heavy_runtime(arguments: list[str]) -> None:+ """真实入口在新进程中展示帮助或版本时不加载服务、模型、采集层或用户配置。"""script = (- "import sys; from typer.testing import CliRunner; from mineru.kit.main import app; "- "r=CliRunner().invoke(app,['hardware','--help']); assert r.exit_code == 0; "- "assert not {'torch','onnxruntime','mineru_llama_cpp'}.intersection(sys.modules)"+ "import sys\nfrom mineru.kit.main import main\n"+ f"sys.argv = ['mineru-kit', *{arguments!r}]\n"+ "try:\n main()\n"+ "except SystemExit as error:\n assert error.code in (0, 2)\n"+ "forbidden = {'torch', 'onnxruntime', 'mineru_llama_cpp', 'mineru.config', "+ "'mineru.parser', 'mineru.kit.router', 'mineru.model.download', 'fastapi', 'httpx', "+ "'mineru.model.runtime.hardware', 'mineru.model.runtime.hardware_probe'}\n"+ "assert not forbidden.intersection(sys.modules), forbidden.intersection(sys.modules)\n")result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=15)assert result.returncode == 0, result.stderr++[email protected]("amount, expected", [(None, "未知"), (0, "0.000 GiB"), (16 * 1024**3, "16.000 GiB")])+def test_info_memory_and_runtime_paths(amount: int | None, expected: str) -> None:+ """系统与嵌套运行时容量使用相同单位,文本隐藏路径且原始 JSON 不受影响。"""+ data = asdict(_report())+ data["memory"]["total_bytes"] = amount+ data["gpus"][0]["shared_memory_bytes"] = amount+ data["runtimes"] = [+ {+ "name": "torch",+ "status": "ok",+ "error": None,+ "data": {+ "module_path": "/runtime/torch.py",+ "backends": {"cuda": {"devices": [{"total_memory_bytes": amount, "module_path": "/nested/path"}]}},+ },+ }+ ]+ before = json.dumps(data)+ rendered = command.render_info(data)+ assert f"总量 {expected}" in rendered+ assert f"共享内存 {expected}" in rendered+ assert f"total_memory: {expected}" in rendered+ assert "独立显存 未知," in rendered and "未知 bytes" not in rendered+ assert "module_path" not in rendered and "/runtime" not in rendered and "/nested" not in rendered+ assert "/env" not in rendered and "/source" not in rendered+ assert "/tmp/config.yaml.onnx-calibration.json" not in rendered+ assert json.dumps(data) == before+++def test_info_parallel_probes_stream_in_order(monkeypatch: pytest.MonkeyPatch) -> None:+ """用阻塞探测验证并发上限、提前分节、最终显卡合并与稳定的报告顺序。"""+ release, first_batch, basic_ready, inventory_ready = Event(), Event(), Event(), Event()+ lock = Lock()+ active = 0+ peak = 0+ calls: list[str] = []+ sections: list[tuple[HardwareInfoSection, dict[str, Any]]] = []+ native = SystemHardware(gpus=[GpuInfo(name="NVIDIA GPU", vendor="NVIDIA", device_id="0x10de:0x2489")])+ monkeypatch.setattr(hardware.sys, "platform", "linux")+ monkeypatch.setattr(+ hardware,+ "installed_packages",+ lambda: [PackageInfo(name, "1", "/env") for name in ("mineru-llama-cpp", "vllm", "lmdeploy", "mlx-vlm")],+ )+ monkeypatch.setattr(hardware, "config_summary", lambda: {})+ monkeypatch.setattr(hardware, "inspect_calibration_record", lambda _: _report().calibration)++ def system() -> SystemHardware:+ """确保运行时探测已启动后再返回系统库存,验证两种采集重叠运行。"""+ assert first_batch.wait(5)+ return native++ def probe(name: str) -> RuntimeProbe:+ """前四项阻塞至测试放行,后续项故意产生超时、错误和显卡补充数据。"""+ nonlocal active, peak+ with lock:+ active += 1+ peak = max(peak, active)+ calls.append(name)+ if active == 4:+ first_batch.set()+ try:+ assert release.wait(5)+ if name == "vulkan":+ assert inventory_ready.wait(5)+ return RuntimeProbe(+ name,+ "ok",+ {+ "devices": [+ {+ "vendor_id": 0x10DE,+ "device_id": 0x2489,+ "kind": "discrete",+ "dedicated_memory_bytes": 8 * 1024**3,+ }+ ]+ },+ )+ if name == "vllm":+ return RuntimeProbe(name, "timeout", error="probe timed out")+ if name == "lmdeploy":+ return RuntimeProbe(name, "error", error="probe failed")+ return RuntimeProbe(name, "ok")+ finally:+ with lock:+ active -= 1++ def section_ready(section: HardwareInfoSection, data: dict[str, Any]) -> None:+ """记录采集层分节;软件信息已经可见时允许测试检查未完成的探测。"""+ sections.append((section, data))+ if section == "packages":+ basic_ready.set()++ monkeypatch.setattr(hardware, "collect_system_hardware", system)+ monkeypatch.setattr(hardware, "run_probe", probe)+ with ThreadPoolExecutor(max_workers=1) as runner:+ future = runner.submit(hardware.collect_hardware_info, on_section=section_ready)+ try:+ assert basic_ready.wait(5)+ assert not future.done()+ assert [section for section, _ in sections] == ["environment", "cpu_memory", "packages"]+ assert len(calls) == 4 and peak == 4+ release.set()+ assert not any(section == "gpus" for section, _ in sections)+ finally:+ release.set()+ inventory_ready.set()+ report = future.result(timeout=10)+ names = ["selection", "torch", "onnx", "llama-cpp", "vllm", "lmdeploy", "mlx-vlm", "vulkan"]+ assert [probe.name for probe in report.runtimes] == names+ assert len(calls) == len(names) and peak == 4+ assert report.runtimes[4].status == "timeout" and report.runtimes[5].status == "error"+ assert len(report.warnings) == 2+ gpu_section = next(data for section, data in sections if section == "gpus")+ assert gpu_section["gpus"][0]["kind"] == "discrete"+ assert gpu_section["gpus"][0]["dedicated_memory_bytes"] == 8 * 1024**3+ streamed = "\n".join(command._render_info_section(section, data) for section, data in sections)+ assert streamed == command.render_info(asdict(report))+++def test_text_sections_flush_before_probe_completion(monkeypatch: pytest.MonkeyPatch) -> None:+ """采集未完成时文本已写出并刷新,JSON 模式则只交付一个完整对象。"""+ import io++ class Output(io.StringIO):+ """记录显式刷新次数,验证非 TTY 管道也能及时接收基础信息。"""++ def __init__(self) -> None:+ """初始化文本缓冲与刷新计数。"""+ super().__init__()+ self.flushes = 0++ def flush(self) -> None:+ """累加刷新次数并保留原始缓冲行为。"""+ self.flushes += 1+ super().flush()++ output = Output()+ monkeypatch.setattr(command.sys, "stdout", output)++ def collect(*, on_section: Callable[[HardwareInfoSection, dict[str, Any]], None] | None = None) -> HardwareInfo:+ """在返回完整报告之前检查分节通知是否已经写入可读内容。"""+ if on_section:+ on_section("environment", asdict(_report()))+ assert "Python:3.12" in output.getvalue()+ assert output.flushes == 1+ else:+ assert not output.getvalue()+ return _report()++ monkeypatch.setattr(hardware, "collect_hardware_info", collect)+ assert command._info_data(stream=True) is None+ output.seek(0)+ output.truncate()+ assert command._info_data(stream=False) == asdict(_report())+ assert not output.getvalue()+++ "backend, device, reason, expected",+ [+ ("torch", "mps", "torch_accelerator", "Torch 加速设备可用"),+ ("torch", "cpu", "configured_cpu", "配置指定使用 CPU"),+ ("onnx", "gpu", "discrete_gpu", "候选独显满足免校准规则"),+ ("onnx", "gpu", "configured_gpu", "配置指定使用 GPU"),+ ("onnx", None, "calibration_required", "需要 OCR 校准后才能确定最终设备"),+ ],+)+def test_info_without_calibration_explains_device(backend: str, device: str | None, reason: str, expected: str) -> None:+ """没有详细记录时显示当前后端设备及原因,待校准不会伪装成 CPU 或 GPU 胜出。"""+ data = asdict(_report())+ data["effective_config"]["resolved"] = {"small_backend": backend}+ data["runtimes"] = [+ asdict(+ RuntimeProbe(+ backend,+ "ok",+ {+ "selected_device": {"device": device, "reason": reason, "backend": "dml"},+ },+ )+ )+ ]+ before = json.dumps(data)+ rendered = "\n".join(command._render_device_selection(data))+ assert "设备选择与校准:" in rendered and expected in rendered+ assert all(key not in rendered for key in ("path:", "cpu_elapsed:", "matches_environment:", "未知"))+ if backend == "torch":+ assert f"选择设备:{device}" in rendered and "不适用" in rendered+ elif device == "gpu":+ assert "选择设备:dml:gpu" in rendered and "校准:免校准" in rendered+ else:+ assert "选择设备:待校准" in rendered and "不会执行测速" in rendered+ assert json.dumps(data) == before++[email protected]("backend", ["torch", "onnx"])[email protected]("matches", [True, False])+def test_info_calibration_details_are_preserved(backend: str, matches: bool) -> None:+ """真实记录保留匹配状态和测量详情,Torch 下明确其不参与当前选择。"""+ data = asdict(_report())+ data["effective_config"]["resolved"] = {"small_backend": backend}+ data["calibration"] = asdict(+ onnx_calibration_cache.CalibrationInfo(+ "/record.json",+ "present",+ matches_environment=matches,+ decision_valid=True,+ outputs_match=True,+ cpu_elapsed=2.0,+ gpu_elapsed=1.0,+ ratio=0.5,+ threshold=0.8,+ model_sha256="test-hash",+ )+ )+ rendered = "\n".join(command._render_device_selection(data))+ assert f"matches_environment: {matches}" in rendered+ assert "cpu_elapsed: 2.0" in rendered and "gpu_elapsed: 1.0" in rendered+ assert "ratio: 0.5" in rendered and "threshold: 0.8" in rendered+ assert "path: /record.json" in rendered and "model_sha256: test-hash" in rendered+ assert "error: 未知" not in rendered+ assert ("不参与当前 Torch 设备选择" in rendered) == (backend == "torch")+++def test_info_invalid_record_and_probe_failure_remain_visible() -> None:+ """损坏记录和探测失败保留错误,不伪造设备或输出空的测速字段。"""+ data = asdict(_report())+ data["calibration"] = asdict(onnx_calibration_cache.CalibrationInfo("/bad.json", "invalid", error="invalid record"))+ rendered = "\n".join(command._render_device_selection(data))+ assert "选择设备:未知" in rendered and "driver unavailable" in rendered+ assert "校准记录:不可用" in rendered and "invalid record" in rendered+ assert "path: /bad.json" in rendered and "cpu_elapsed" not in rendered+++ "requested, kind, provider, expected_device, expected_reason",+ [+ ("auto", "discrete", True, "gpu", "discrete_gpu"),+ ("gpu", "integrated", True, "gpu", "configured_gpu"),+ ("cpu", "discrete", True, "cpu", "configured_cpu"),+ ("auto", "integrated", True, None, "calibration_required"),+ ("auto", "discrete", False, "cpu", "directml_unavailable"),+ ],+)+def test_onnx_info_probe_reuses_policy_without_calibrating(+ monkeypatch: pytest.MonkeyPatch,+ requested: str,+ kind: str,+ provider: bool,+ expected_device: str | None,+ expected_reason: str,+) -> None:+ """ONNX 诊断复用选型规则和一次库存读取,不调用下载、校准或配置写入。"""+ from mineru import config+ from mineru.model import registry+ from mineru.model.runtime import onnx_calibration, windows_gpu++ monkeypatch.setattr(get_config().model, "onnx_device", requested)+ monkeypatch.setattr(hardware_probe, "sys", SimpleNamespace(platform="win32"))+ monkeypatch.setitem(+ sys.modules,+ "onnxruntime",+ SimpleNamespace(+ __version__="test",+ __file__="/ort.py",+ get_available_providers=lambda: ["DmlExecutionProvider"] if provider else ["CPUExecutionProvider"],+ ),+ )+ gpu = windows_gpu.GpuAdapter(0, "luid-0", "test", 0x10DE, 1, 0, kind=kind)+ discovery = Mock(return_value=(gpu,))+ monkeypatch.setattr(windows_gpu, "discover_gpus", discovery)+ forbidden = Mock(side_effect=AssertionError("info cannot calibrate, download or save"))+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", forbidden)+ monkeypatch.setattr(onnx_calibration, "run_calibration", forbidden)+ monkeypatch.setattr(config, "update_config_file", forbidden)+ monkeypatch.setattr(registry, "MINERU_4_MODELS_ONNX", SimpleNamespace(ocr_rec=SimpleNamespace(ensure=forbidden)))+ result = hardware_probe._onnx_probe()+ assert result["selected_device"]["device"] == expected_device+ assert result["selected_device"]["reason"] == expected_reason+ assert result["selected_adapter"] is not None+ discovery.assert_called_once_with(classify=requested != "gpu")+ forbidden.assert_not_called()++[email protected]("requested", ["auto", "cpu"])+def test_onnx_info_probe_discovery_failure_is_not_a_gpu_choice(monkeypatch: pytest.MonkeyPatch, requested: str) -> None:+ """WebGPU 库存错误保持未知,显式 CPU 选择仍可独立解释。"""+ from mineru.model.runtime import webgpu++ monkeypatch.setattr(get_config().model, "onnx_device", requested)+ monkeypatch.setattr(hardware_probe, "sys", SimpleNamespace(platform="linux"))+ monkeypatch.setitem(+ sys.modules,+ "onnxruntime",+ SimpleNamespace(+ __version__="test",+ __file__="/ort.py",+ get_available_providers=lambda: ["CPUExecutionProvider"],+ ),+ )+ monkeypatch.setattr(webgpu, "discover_webgpu_devices", Mock(side_effect=RuntimeError("driver unavailable")))+ result = hardware_probe._onnx_probe()+ assert result["adapter_error"] == "driver unavailable"+ assert result["selected_device"]["device"] == ("cpu" if requested == "cpu" else None)+ assert result["selected_device"]["reason"] == ("configured_cpu" if requested == "cpu" else "selection_unavailable")diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex 10d6d698..9e7fa97c 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import inspectimport jsonimport sysimport tomllib@@ -32,9 +33,16 @@ _REMOVED_DISABLE_FORMULA_OPTION = "--disable-" + "formula"def test_kit_main_configures_standard_streams_before_running_app(monkeypatch: pytest.MonkeyPatch) -> None:+ """控制台入口先设置编码,再把日志初始化标记交给实际命令。"""calls: list[str] = []++ def run_app(*, obj: kit_main.KitContext) -> None:+ """检查仅控制台入口启用进程日志初始化。"""+ assert obj.configure_logging+ calls.append("app")+monkeypatch.setattr(kit_main, "configure_standard_streams", lambda: calls.append("configure"))- monkeypatch.setattr(kit_main, "app", lambda: calls.append("app"))+ monkeypatch.setattr(kit_main, "app", run_app)kit_main.main()@@ -153,7 +161,8 @@ def test_standalone_vlm_main_configures_streams_and_forwards_extra_args(monkeypamonkeypatch.setattr(vlm_server, "configure_standard_streams", lambda: calls.append("configure"))monkeypatch.setattr(vlm_server, "vlm_server_cmd", _record_command)code = _invoke_standalone_command(monkeypatch, vlm_server.main, "mineru-openai-server", ["--port", "30000"])- kit_command = next(command for command in app.registered_commands if command.name == "vlm-server")+ root_command = get_command(app)+ _, kit_command, _ = root_command.resolve_command(typer.Context(root_command), ["vlm-server"])assert code == 0assert calls == ["configure", ["--port", "30000"]]@@ -352,15 +361,21 @@ def test_kit_root_and_models_help() -> None:assert "version" in result.output-def test_top_level_commands_register_implementation_callbacks_directly() -> None:- callbacks = {command.name: command.callback for command in app.registered_commands}-- assert callbacks["parse"] is parse.parse_cmd- assert callbacks["webui"] is webui.webui_cmd- assert callbacks["api-server"] is api_server.api_server_cmd- assert callbacks["vlm-server"] is vlm_server.vlm_server_cmd- assert callbacks["router"] is router.router_cmd- assert callbacks["version"] is version_cmd+def test_selected_commands_use_original_implementation_callbacks() -> None:+ """惰性加载后仍直接使用原始函数签名和回调,不以通用参数透传替代。"""+ root_command = get_command(app)+ callbacks = {+ "parse": parse.parse_cmd,+ "webui": webui.webui_cmd,+ "api-server": api_server.api_server_cmd,+ "vlm-server": vlm_server.vlm_server_cmd,+ "router": router.router_cmd,+ "version": version_cmd,+ }+ for name, callback in callbacks.items():+ _, selected, remaining = root_command.resolve_command(typer.Context(root_command), [name])+ assert remaining == []+ assert inspect.unwrap(selected.callback) is callback@pytest.mark.parametrize(@@ -1310,3 +1325,34 @@ def test_models_verify_rejects_invalid_small_backend() -> None:assert result.exit_code == 1assert "Unsupported small backend 'invalid'" in " ".join(result.output.split())+++ "arguments, expected_calls",+ [+ (["--help"], 0),+ (["hardware", "--help"], 0),+ (["hardware", "info", "--help"], 0),+ (["hardware", "detect", "--help"], 0),+ (["models", "--help"], 0),+ (["version"], 1),+ (["hardware", "info"], 1),+ ],+)+def test_kit_logging_only_initializes_for_execution(+ monkeypatch: pytest.MonkeyPatch, arguments: list[str], expected_calls: int+) -> None:+ """控制台上下文的日志初始化只发生在叶子执行阶段,帮助和嵌入调用没有副作用。"""+ from mineru.kit.commands import hardware+ from mineru.utils import logger++ calls: list[str] = []+ monkeypatch.setattr(logger, "configure_global_log_level", lambda: calls.append("logging"))+ monkeypatch.setattr(hardware, "_info_data", lambda **kwargs: None)+ result = runner.invoke(app, arguments, obj=kit_main.KitContext(configure_logging=True))+ assert result.exit_code == 0, result.output+ assert len(calls) == expected_calls+ calls.clear()+ embedded = runner.invoke(app, arguments)+ assert embedded.exit_code == 0+ assert calls == []diff --git a/tests/unittest/test_onnx_device_selection.py b/tests/unittest/test_onnx_device_selection.pyindex 8cd2c45e..7bf9f8ec 100644--- a/tests/unittest/test_onnx_device_selection.py+++ b/tests/unittest/test_onnx_device_selection.py@@ -523,3 +523,27 @@ def test_unstable_calibration_keeps_auto(config_file: Path, monkeypatch: pytest.assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "auto"assert policy.resolve_onnx_device() == selectedmeasure.assert_called_once()++[email protected]("binding", [None, (0x8086, 1), (0x8086, 2)])+def test_readonly_discrete_policy_requires_matching_webgpu_binding(binding: tuple[int, int] | None) -> None:+ """只读诊断与运行时共享独显判断,缺少或错误物理绑定时仍需要校准。"""+ descriptor = with_gpu_classification(WebGPUDevice(0x8086, 1, vulkan_device=binding), classify_vulkan_gpu(2))+ selection = policy.inspect_onnx_candidate("auto", backend="webgpu", adapter=descriptor, has_devices=True)+ assert selection.reason == ("discrete_gpu" if binding == (0x8086, 1) else "calibration_required")+ assert selection.device == ("gpu" if binding == (0x8086, 1) else "cpu")+++ "backend, has_devices, reason",+ [+ (None, False, "unsupported_platform"),+ ("dml", False, "no_hardware_gpu"),+ ("webgpu", False, "no_hardware_gpu"),+ ("webgpu", True, "webgpu_architecture_policy"),+ ],+)+def test_readonly_policy_explains_missing_candidate(backend: str | None, has_devices: bool, reason: str) -> None:+ """平台不支持、无设备和有库存但无合格候选保持不同原因。"""+ selection = policy.inspect_onnx_candidate("auto", backend=backend, has_devices=has_devices)+ assert selection.device == "cpu" and selection.reason == reason