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: add short aliases for command-line flags and redact sensitive values in startup banner
myhloli4fff0d375bfe
diff --git a/mineru/kit/vlm_server/llama_cpp_server.py b/mineru/kit/vlm_server/llama_cpp_server.pyindex 889d84c3..cd0e6f4b 100644--- a/mineru/kit/vlm_server/llama_cpp_server.py+++ b/mineru/kit/vlm_server/llama_cpp_server.py@@ -35,6 +35,29 @@ _GGUF_STRING = 8_GGUF_ARRAY = 9_GGUF_UINT32 = 4+# llama-server 同一选项的短别名与等价选择器(清单来自 llama-server --help)。+# 追加默认参数前必须把整组别名视为「用户已显式提供」:llama.cpp 参数解析中+# 后出现的同名项生效,漏认别名会让追加的默认值覆盖用户先传入的值。+GRAMMAR_SELECTOR_FLAGS = ("--grammar", "--grammar-file", "-j", "--json-schema", "-jf", "--json-schema-file")+MODEL_SELECTOR_FLAGS = ("-m", "--model", "-hf", "-hfr", "--hf-repo", "-mu", "--model-url")+PROJECTOR_SELECTOR_FLAGS = (+ "-mm",+ "--mmproj",+ "-mmu",+ "--mmproj-url",+ "-hfv",+ "-hfrv",+ "--hf-repo-v",+ "--mmproj-auto",+ "--no-mmproj",+ "--no-mmproj-auto",+)+PARALLEL_FLAGS = ("-np", "--parallel")+KV_UNIFIED_FLAGS = ("-kvu", "--kv-unified", "-no-kvu", "--no-kv-unified")+SPECIAL_FLAGS = ("-sp", "--special")+# 值为凭据的旗标,启动横幅打印前脱敏;--api-key-file 等是路径不是凭据,不脱敏。+SECRET_VALUE_FLAGS = ("--api-key", "-hft", "--hf-token")+def llama_server_binary() -> Path:"""定位 mineru-llama-cpp 包内分发的 llama-server 可执行文件。"""@@ -59,6 +82,26 @@ def _flag_value(args: list[str], *flags: str) -> str | None:return None+def _redact_secrets(args: list[str]) -> list[str]:+ """启动横幅脱敏:SECRET_VALUE_FLAGS 的值替换为 ***,覆盖 flag value 与 flag=value 两种形式。"""+ redacted: list[str] = []+ redact_next = False+ for arg in args:+ if redact_next:+ redacted.append("***")+ redact_next = False+ continue+ flag = next((name for name in SECRET_VALUE_FLAGS if arg == name or arg.startswith(f"{name}=")), None)+ if flag is None:+ redacted.append(arg)+ elif arg == flag:+ redacted.append(arg)+ redact_next = True+ else:+ redacted.append(f"{flag}=***")+ return redacted++def _skip_gguf_value(f: typing.BinaryIO, value_type: int) -> None:"""按 gguf.h 的类型布局跳过一个 kv 值。"""if value_type == _GGUF_STRING:@@ -83,7 +126,12 @@ def _read_gguf_context_length(model_path: Path) -> int:对齐 EngineCore 的 read_n_ctx_train_from_gguf:server 的 --ctx-size只接受总量,而进程内引擎按单 slot 训练上下文 × n_parallel 配 KV,所以这里必须自己从模型元数据取训练上下文。++ GGUF 不保证 metadata key 顺序,`<arch>.context_length` 可能出现在+ general.architecture 之前:先按前缀收齐全部候选,读完后按 arch 查表。"""+ context_by_architecture: dict[str, int] = {}+ architecture = ""try:with model_path.open("rb") as f:header = f.read(24)@@ -92,7 +140,6 @@ def _read_gguf_context_length(model_path: Path) -> int:version, _tensor_count, kv_count = struct.unpack_from("<IQQ", header, 4)if version < 2:return 0- architecture = ""for _ in range(kv_count):(key_length,) = struct.unpack("<Q", f.read(8))key = f.read(key_length).decode("utf-8", errors="replace")@@ -100,14 +147,14 @@ def _read_gguf_context_length(model_path: Path) -> int:if key == "general.architecture" and value_type == _GGUF_STRING:(value_length,) = struct.unpack("<Q", f.read(8))architecture = f.read(value_length).decode("utf-8", errors="replace")- continue- if architecture and key == f"{architecture}.context_length" and value_type == _GGUF_UINT32:+ elif key.endswith(".context_length") and value_type == _GGUF_UINT32:(value,) = struct.unpack("<I", f.read(4))- return int(value)- _skip_gguf_value(f, value_type)+ context_by_architecture[key.removesuffix(".context_length")] = int(value)+ else:+ _skip_gguf_value(f, value_type)except (OSError, struct.error):return 0- return 0+ return context_by_architecture.get(architecture, 0)def main() -> None:@@ -115,28 +162,29 @@ def main() -> None:if not _has_arg(args, "--port"):args.extend(["--port", DEFAULT_PORT])- if not _has_arg(args, "--grammar"):+ if not _has_arg(args, *GRAMMAR_SELECTOR_FLAGS):args.extend(["--grammar", VALID_UNICODE_GRAMMAR])# params_.special=true:MinerU 输出里的 <|box_start|> 等格式标记注册为# special tokens,server 默认(false)会在输出 detokenize 时吞掉它们,# 解析格式依赖这些标记,必须显式开启。- if not _has_arg(args, "--special"):+ if not _has_arg(args, *SPECIAL_FLAGS):args.append("--special")- # 模型与 mmproj 必须成对来自同一模型;用户自定义任一参数时不再补默认,+ # 模型与 mmproj 必须成对来自同一模型;用户通过任一原生选择器(-m/-hf/+ # --model-url,或 -mm/--mmproj 等投影选择器)自定义时不再补默认,# 避免拼出「自定义主模型 + 官方 mmproj」的不匹配组合。model_path: Path | None = Noneif _has_arg(args, "-m", "--model"):value = _flag_value(args, "-m", "--model")model_path = Path(value) if value else None- elif not _has_arg(args, "--mmproj"):+ elif not _has_arg(args, *MODEL_SELECTOR_FLAGS, *PROJECTOR_SELECTOR_FLAGS):repo = vlm_model_repo("llama-cpp")model_dir = repo.ensure()model_path = model_dir / repo.paths["main"]args.extend(["-m", str(model_path), "--mmproj", str(model_dir / repo.paths["mmproj"])])# ---- 对齐 EngineCore::EngineCore 写死的 common_params(用户显式传入时逐项让位)----- user_defined_parallel = _has_arg(args, "--parallel")+ user_defined_parallel = _has_arg(args, *PARALLEL_FLAGS)user_defined_ctx = _has_arg(args, "-c", "--ctx-size")if not user_defined_parallel:args.extend(["--parallel", str(DEFAULT_N_PARALLEL)])@@ -154,7 +202,7 @@ def main() -> None:# EngineCore 用 kv_unified=false 的硬分区 KV(每 slot 私有 n_ctx_seq,互不侵占,# 见 engine_core.cpp 的注释);llama-server 默认 unified=enabled,需显式关闭,# 并同步关闭 idle-slot RAM 缓存(EngineCore 的 cache_idle_slots=false / cache_ram_mib=0)。- if not _has_arg(args, "--kv-unified", "--no-kv-unified"):+ if not _has_arg(args, *KV_UNIFIED_FLAGS):args.append("--no-kv-unified")if not _has_arg(args, "--cache-ram", "-cram"):args.extend(["--cache-ram", "0"])@@ -172,7 +220,7 @@ def main() -> None:if not binary.is_file():raise FileNotFoundError(f"llama-server binary not found: {binary}")- print(f"start llama.cpp server: {binary} {' '.join(args)}")+ print(f"start llama.cpp server: {binary} {' '.join(_redact_secrets(args))}")os.execv(str(binary), [str(binary), *args])diff --git a/tests/unittest/test_llama_cpp_server.py b/tests/unittest/test_llama_cpp_server.pyindex 5632405e..6afcc436 100644--- a/tests/unittest/test_llama_cpp_server.py+++ b/tests/unittest/test_llama_cpp_server.py@@ -1,8 +1,9 @@from __future__ import annotations+import structimport sys-import typesfrom pathlib import Path+from types import ModuleType, SimpleNamespaceimport pytest@@ -17,7 +18,7 @@ def test_llama_server_binary_matches_platform_executable_name(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, platform: str, expected_name: str) -> None:"""Windows wheel 分发 llama-server.exe,其余平台无后缀。"""- fake_pkg = types.ModuleType("mineru_llama_cpp")+ fake_pkg = ModuleType("mineru_llama_cpp")fake_pkg.__file__ = str(tmp_path / "mineru_llama_cpp" / "__init__.py")monkeypatch.setitem(sys.modules, "mineru_llama_cpp", fake_pkg)monkeypatch.setattr(sys, "platform", platform)@@ -25,3 +26,217 @@ def test_llama_server_binary_matches_platform_executable_name(binary = llama_cpp_server.llama_server_binary()assert binary == tmp_path / "mineru_llama_cpp" / "bin" / expected_name+++def _gguf_string_kv(key: str, value: str) -> bytes:+ key_bytes, value_bytes = key.encode(), value.encode()+ return (+ struct.pack("<Q", len(key_bytes))+ + key_bytes+ + struct.pack("<I", llama_cpp_server._GGUF_STRING)+ + struct.pack("<Q", len(value_bytes))+ + value_bytes+ )+++def _gguf_uint32_kv(key: str, value: int) -> bytes:+ key_bytes = key.encode()+ return (+ struct.pack("<Q", len(key_bytes))+ + key_bytes+ + struct.pack("<I", llama_cpp_server._GGUF_UINT32)+ + struct.pack("<I", value)+ )+++def _write_gguf(path: Path, kv_entries: list[bytes]) -> Path:+ path.write_bytes(+ b"GGUF" + struct.pack("<I", 3) + struct.pack("<Q", 0) + struct.pack("<Q", len(kv_entries)) + b"".join(kv_entries)+ )+ return path+++def test_gguf_context_length_is_key_order_independent(tmp_path: Path) -> None:+ """GGUF 不保证 metadata key 顺序,context_length 在 architecture 前也必须读出。"""+ architecture = _gguf_string_kv("general.architecture", "qwen2vl")+ context = _gguf_uint32_kv("qwen2vl.context_length", 40960)++ assert (+ llama_cpp_server._read_gguf_context_length(_write_gguf(tmp_path / "arch_first.gguf", [architecture, context])) == 40960+ )+ assert (+ llama_cpp_server._read_gguf_context_length(_write_gguf(tmp_path / "ctx_first.gguf", [context, architecture])) == 40960+ )+++def test_gguf_context_length_returns_zero_without_matching_architecture(tmp_path: Path) -> None:+ """没有与 architecture 匹配的 context_length 时返回 0,交给 llama-server 默认。"""+ mismatch = [+ _gguf_string_kv("general.architecture", "llama"),+ _gguf_uint32_kv("qwen2vl.context_length", 40960),+ ]++ assert llama_cpp_server._read_gguf_context_length(_write_gguf(tmp_path / "mismatch.gguf", mismatch)) == 0+++def _run_main(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], user_args: list[str]+) -> tuple[list[str], str, Path]:+ """执行 main() 并捕获转交 llama-server 的 argv 与横幅输出,不真正启动进程。"""+ model_dir = tmp_path / "repo"+ model_dir.mkdir()+ # 故意用 context_length 在前的 GGUF,端到端覆盖 key 顺序无关的读取路径。+ gguf = _write_gguf(+ model_dir / "main.gguf",+ [_gguf_uint32_kv("qwen2vl.context_length", 40960), _gguf_string_kv("general.architecture", "qwen2vl")],+ )+ binary = tmp_path / "llama-server"+ binary.write_bytes(b"")+ executed: list[list[str]] = []+ monkeypatch.setattr(llama_cpp_server, "llama_server_binary", lambda: binary)+ monkeypatch.setattr(+ llama_cpp_server,+ "vlm_model_repo",+ lambda name: SimpleNamespace(ensure=lambda: model_dir, paths={"main": gguf.name, "mmproj": "mmproj.gguf"}),+ )+ monkeypatch.setattr("os.execv", lambda path, argv: executed.append(argv))+ monkeypatch.setattr(sys, "argv", ["llama_cpp_server", *user_args])++ llama_cpp_server.main()++ captured = capsys.readouterr()+ return executed[0], captured.out, model_dir+++def test_main_appends_engine_aligned_defaults(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]+) -> None:+ argv, out, model_dir = _run_main(monkeypatch, tmp_path, capsys, [])++ assert argv[argv.index("--port") + 1] == llama_cpp_server.DEFAULT_PORT+ assert argv[argv.index("--grammar") + 1] == llama_cpp_server.VALID_UNICODE_GRAMMAR+ assert "--special" in argv+ assert argv[argv.index("-m") + 1] == str(model_dir / "main.gguf")+ assert argv[argv.index("--mmproj") + 1] == str(model_dir / "mmproj.gguf")+ assert argv[argv.index("--parallel") + 1] == str(llama_cpp_server.DEFAULT_N_PARALLEL)+ assert argv[argv.index("--n-gpu-layers") + 1] == str(llama_cpp_server.DEFAULT_N_GPU_LAYERS)+ assert "--no-kv-unified" in argv+ assert argv[argv.index("--cache-ram") + 1] == "0"+ # 训练上下文 40960 × 默认并发 4,且来自 key 顺序颠倒的 GGUF。+ assert argv[argv.index("--ctx-size") + 1] == "163840"+ assert "start llama.cpp server:" in out+++ "parallel_args",+ [["-np", "8"], ["--parallel", "6"], ["--parallel=6"]],+ ids=["short-alias", "long-separated", "long-inline"],+)+def test_main_respects_user_parallel_and_skips_ctx_conversion(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], parallel_args: list[str]+) -> None:+ """-np 是 --parallel 的别名:用户给过后不再追加默认值,也不做 ×4 换算。"""+ argv, _, _ = _run_main(monkeypatch, tmp_path, capsys, parallel_args)++ joined = " ".join(argv)+ assert f"--parallel {llama_cpp_server.DEFAULT_N_PARALLEL}" not in joined+ assert "--ctx-size" not in argv+++ "grammar_args",+ [+ ["--grammar-file", "g.gbnf"],+ ["-j", '{"type": "object"}'],+ ["--json-schema", '{"type": "object"}'],+ ["--json-schema={}"],+ ["-jf", "schema.json"],+ ["--json-schema-file", "schema.json"],+ ["--grammar", "root ::= A"],+ ],+ ids=[+ "grammar-file",+ "json-schema-short",+ "json-schema",+ "json-schema-inline",+ "json-schema-file-short",+ "json-schema-file",+ "grammar",+ ],+)+def test_main_skips_default_grammar_when_alternate_selector_supplied(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], grammar_args: list[str]+) -> None:+ """任一 grammar 等价选择器都视为用户已约束生成,不再注入兜底 grammar。"""+ argv, _, _ = _run_main(monkeypatch, tmp_path, capsys, grammar_args)++ assert llama_cpp_server.VALID_UNICODE_GRAMMAR not in argv+ if grammar_args[0] == "--grammar":+ assert argv.count("--grammar") == 1+ else:+ assert "--grammar" not in argv+++ "model_args",+ [+ ["-hf", "org/model:Q8_0"],+ ["-hfr", "org/model"],+ ["--hf-repo", "org/model"],+ ["-mu", "https://example.com/m.gguf"],+ ["--model-url", "https://example.com/m.gguf"],+ ["-mm", "p.gguf"],+ ["--mmproj", "p.gguf"],+ ["-mmu", "https://example.com/p.gguf"],+ ["--mmproj-url", "https://example.com/p.gguf"],+ ],+ ids=[+ "hf",+ "hf-repo-short2",+ "hf-repo",+ "model-url-short",+ "model-url",+ "mmproj-short",+ "mmproj",+ "mmproj-url-short",+ "mmproj-url",+ ],+)+def test_main_skips_default_model_pair_when_native_selector_supplied(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], model_args: list[str]+) -> None:+ """原生模型/投影选择器视为用户已提供模型,不再注入官方 -m + --mmproj 组合。"""+ argv, _, model_dir = _run_main(monkeypatch, tmp_path, capsys, model_args)++ assert str(model_dir / "main.gguf") not in argv+ assert str(model_dir / "mmproj.gguf") not in argv+++ "kv_args",+ [["-kvu"], ["--kv-unified"], ["-no-kvu"], ["--no-kv-unified"]],+ ids=["short", "long", "no-short", "no-long"],+)+def test_main_respects_user_kv_unified_choice(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], kv_args: list[str]+) -> None:+ argv, _, _ = _run_main(monkeypatch, tmp_path, capsys, kv_args)++ assert argv.count("--no-kv-unified") == (1 if "--no-kv-unified" in kv_args else 0)+++def test_main_redacts_secrets_in_startup_banner(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]+) -> None:+ """横幅对 --api-key/-hft/--hf-token 的值脱敏,转交进程的参数保持原值。"""+ argv, out, _ = _run_main(+ monkeypatch, tmp_path, capsys, ["--api-key", "sk-plain-secret", "-hft=tok-inline", "--hf-token", "tok-separated"]+ )++ assert "sk-plain-secret" not in out+ assert "tok-inline" not in out+ assert "tok-separated" not in out+ assert out.count("***") == 3+ assert "sk-plain-secret" in argv+ assert "-hft=tok-inline" in argv+ assert "tok-separated" in argv