Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Keep JSON CLI output machine readable

jinzhenj42084789f90f
diff --git a/mineru/cli/commands/cleanup.py b/mineru/cli/commands/cleanup.py
index e01da2e0..87ad7e1a 100644
--- a/mineru/cli/commands/cleanup.py
+++ b/mineru/cli/commands/cleanup.py
@@ -7,7 +7,7 @@ import typer
from ...doclib.client import DoclibClient
from ...doclib.types import CleanupDeletedRequest, CleanupOrphansRequest, CleanupTempRequest
from ..json_errors import exit_with_error
-from ..output import print_error, print_info, print_json, print_success
+from ..output import print_info, print_json, print_success
app = typer.Typer(
name="cleanup",
@@ -22,7 +22,10 @@ def cleanup_deleted_files(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Remove all file rows already marked as deleted."""
- client = _client()
+ try:
+ client = _client()
+ except Exception as exc:
+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
try:
data = client.cleanup_deleted_files(CleanupDeletedRequest(dry_run=dry_run))
except Exception as exc:
@@ -45,7 +48,10 @@ def cleanup_orphan_docs(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Remove docs that are no longer referenced by any file row."""
- client = _client()
+ try:
+ client = _client()
+ except Exception as exc:
+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
try:
data = client.cleanup_orphan_docs(CleanupOrphansRequest(dry_run=dry_run))
except Exception as exc:
@@ -68,7 +74,10 @@ def cleanup_temp_files(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Remove old process temp files."""
- client = _client()
+ try:
+ client = _client()
+ except Exception as exc:
+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
try:
data = client.cleanup_temp_files(CleanupTempRequest(older_than_days=older_than))
except Exception as exc:
@@ -82,7 +91,4 @@ def cleanup_temp_files(
def _client() -> DoclibClient:
- try:
- return DoclibClient(timeout=30)
- except Exception as exc:
- exit_with_error(exc, json_mode=False, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
+ return DoclibClient(timeout=30)
diff --git a/mineru/cli/commands/config.py b/mineru/cli/commands/config.py
index 54b31707..c26fb46f 100644
--- a/mineru/cli/commands/config.py
+++ b/mineru/cli/commands/config.py
@@ -59,7 +59,7 @@ def config_set(
try:
data = _client().set_config(key, ConfigSetRequest(value=value))
except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
+ exit_with_error(exc, json_mode=False)
print_success(f"{data.key} = {data.value} [{data.source}]")
@@ -70,7 +70,7 @@ def config_unset(key: str = typer.Argument(..., help="Configuration key")) -> No
try:
data = _client().unset_config(key)
except Exception as exc:
- exit_with_error(exc, json_mode=json_mode)
+ exit_with_error(exc, json_mode=False)
action = "removed" if data.removed else "unchanged"
print_success(f"{data.key} = {data.value} [{data.source}] ({action})")
@@ -139,8 +139,7 @@ def parsing_rules_add(
ParsingRuleRequest(pattern=pattern, tier=tier, page_range=pages, remote=remote, name=name)
)
except Exception as exc:
- print_error(str(exc))
- raise typer.Exit(1) from None
+ exit_with_error(exc, json_mode=json_mode)
if json_mode:
print_json(data)
@@ -154,8 +153,7 @@ def parsing_rules_list(json_mode: bool = typer.Option(False, "--json", help="JSO
try:
data = _client().list_parsing_rules()
except Exception as exc:
- print_error(str(exc))
- raise typer.Exit(1) from None
+ exit_with_error(exc, json_mode=json_mode)
if json_mode:
print_json(data)
diff --git a/mineru/cli/commands/parse.py b/mineru/cli/commands/parse.py
index 0d48d83c..e0e9ed8b 100644
--- a/mineru/cli/commands/parse.py
+++ b/mineru/cli/commands/parse.py
@@ -25,7 +25,7 @@ from ...doclib.types import (
)
from ...types import Tier
from ..json_errors import exit_with_error
-from ..output import format_parse_result, print_error, print_info, print_json, print_success
+from ..output import format_parse_result, print_error, print_json, print_notice, print_success
from ..path_utils import normalize_cli_path
@@ -103,9 +103,8 @@ def parse_cmd(
try:
client = DoclibClient(timeout=wait + 30)
- except Exception:
- print_error("Cannot connect to mineru server. Run 'mineru server start' first.")
- raise typer.Exit(1) from None
+ except Exception as exc:
+ exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
# send parse request
try:
@@ -131,7 +130,7 @@ def parse_cmd(
# cached
if status == "done":
if verbose:
- print_info("Cache hit — returning cached result.")
+ print_notice("Cache hit — returning cached result.")
_output_parse_result(
client,
result,
@@ -160,7 +159,7 @@ def parse_cmd(
# poll until done or timeout
if verbose:
- print_info(f"Parse queued (tier={req_tier}). Waiting up to {wait}s...")
+ print_notice(f"Parse queued (tier={req_tier}). Waiting up to {wait}s...")
wait_started_at = time.time()
deadline = time.time() + wait
@@ -178,7 +177,7 @@ def parse_cmd(
statuses = {row.status for row in parse_rows}
st = "done" if parse_rows and statuses == {"done"} else ("failed" if "failed" in statuses else "parsing")
if verbose and not json_mode:
- print_info(f" Parse status: {st}")
+ print_notice(f" Parse status: {st}")
if st == "done":
_record_parse_wait(client, wait_parse_ids, "succeeded", wait_started_at)
@@ -211,7 +210,7 @@ def parse_cmd(
timeout_result = result.model_copy(update={"status": "parsing", "tip": "Re-run the same command to continue waiting."})
_print_parse_json_response(timeout_result, None)
else:
- print_info(f"Parse still in progress (tier={req_tier}). Check status with: mineru show file {file_path}")
+ print_notice(f"Parse still in progress (tier={req_tier}). Check status with: mineru show file {file_path}")
def _record_parse_wait(client: DoclibClient, parse_ids: list[int], status: str, started_at: float) -> None:
diff --git a/mineru/cli/output.py b/mineru/cli/output.py
index fd6ee56f..a7de393d 100644
--- a/mineru/cli/output.py
+++ b/mineru/cli/output.py
@@ -13,6 +13,7 @@ from pydantic_core import to_json
Table: Any
Panel: Any
Text: Any
+stderr_console: Any
try:
from rich.console import Console
@@ -20,15 +21,17 @@ try:
from rich.panel import Panel
from rich.text import Text
console = Console()
+ stderr_console = Console(stderr=True)
except ImportError:
console = None
+ stderr_console = None
def print_error(msg: str) -> None:
- if console:
+ if stderr_console:
text = Text("Error:", style="red")
text.append(f" {msg}")
- console.print(text)
+ stderr_console.print(text)
else:
print(f"Error: {msg}", file=sys.stderr)
@@ -47,6 +50,13 @@ def print_info(msg: str) -> None:
print(msg)
+def print_notice(msg: str) -> None:
+ if stderr_console:
+ stderr_console.print(msg, style="dim")
+ else:
+ print(msg, file=sys.stderr)
+
+
def print_json(data: Any) -> None:
if isinstance(data, BaseModel):
print(to_json(data, indent=2).decode("utf-8"))
diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.py
index 1723414d..b1cadbcd 100644
--- a/tests/unittest/test_cli_next_command_design.py
+++ b/tests/unittest/test_cli_next_command_design.py
@@ -147,7 +147,7 @@ def test_print_error_uses_single_rich_render(monkeypatch: Any) -> None:
def print(self, *args: Any, **kwargs: Any) -> None:
calls.append((args, kwargs))
- monkeypatch.setattr(output_mod, "console", _Console())
+ monkeypatch.setattr(output_mod, "stderr_console", _Console())
output_mod.print_error(
"No standard or pro engine available. You can start a local parse-server, use --remote, or explicitly pass "
@@ -516,6 +516,149 @@ def test_parse_wait_ignores_failed_rows_outside_wait_ids(monkeypatch: Any, tmp_p
assert payload["content"]["content"] == "parsed"
+def test_parse_verbose_json_writes_cache_hit_notice_to_stderr(monkeypatch: Any, tmp_path: Path) -> None:
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(b"%PDF-1.7\n")
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 90
+
+ def ensure_parse(self, request: Any) -> ParseResponse:
+ return ParseResponse(sha256="a" * 64, tier="flash", page_range="1~1", status="done", cache_hit=True)
+
+ def get_doc_content(self, *args: Any, **kwargs: Any) -> DocContentResponse:
+ return DocContentResponse(
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ tier="flash",
+ format="markdown",
+ content="parsed",
+ request_scope=ContentRequestScope(page_range="1~1", limit=30000),
+ )
+
+ monkeypatch.setattr(parse, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["parse", str(source), "--tier", "flash", "--verbose", "--json"])
+
+ assert result.exit_code == 0
+ payload = json.loads(result.stdout)
+ assert payload["parse"]["cache_hit"] is True
+ assert payload["content"]["content"] == "parsed"
+ assert "Cache hit" not in result.stdout
+ assert "Cache hit" in result.stderr
+
+
+def test_parse_verbose_json_writes_queue_notice_to_stderr(monkeypatch: Any, tmp_path: Path) -> None:
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(b"%PDF-1.7\n")
+
+ done = ParseInfo(
+ id=3,
+ sha256="a" * 64,
+ tier="flash",
+ page_range="1~1",
+ status="done",
+ privacy="local",
+ created_at=3,
+ updated_at=4,
+ done_at=4,
+ )
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 31
+
+ def ensure_parse(self, request: Any) -> ParseResponse:
+ return ParseResponse(
+ sha256="a" * 64,
+ tier="flash",
+ page_range="1~1",
+ status="pending",
+ wait_parse_ids=[3],
+ created_parse_ids=[3],
+ )
+
+ def list_parses(self, **kwargs: Any) -> ListParsesResponse:
+ return ListParsesResponse(parses=[done], total=1, limit=50, offset=0)
+
+ def get_doc_content(self, *args: Any, **kwargs: Any) -> DocContentResponse:
+ return DocContentResponse(
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ tier="flash",
+ format="markdown",
+ content="parsed",
+ request_scope=ContentRequestScope(page_range="1~1", limit=30000),
+ )
+
+ monkeypatch.setattr(parse, "DoclibClient", _Client)
+ monkeypatch.setattr(parse.time, "sleep", lambda seconds: None)
+
+ result = runner.invoke(app, ["parse", str(source), "--tier", "flash", "--verbose", "--wait", "1", "--json"])
+
+ assert result.exit_code == 0
+ payload = json.loads(result.stdout)
+ assert payload["parse"]["status"] == "done"
+ assert payload["content"]["content"] == "parsed"
+ assert "Parse queued" not in result.stdout
+ assert "Parse queued" in result.stderr
+
+
+def test_parse_json_connection_error_is_machine_readable(monkeypatch: Any, tmp_path: Path) -> None:
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(b"%PDF-1.7\n")
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ raise RuntimeError("cannot connect")
+
+ monkeypatch.setattr(parse, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["parse", str(source), "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["error"]["code"] == "api_error"
+ assert "Cannot connect to mineru server" in payload["error"]["message"]
+ assert "Error:" not in result.stdout
+
+
+def test_cleanup_json_connection_error_is_machine_readable(monkeypatch: Any) -> None:
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ raise RuntimeError("cannot connect")
+
+ monkeypatch.setattr(cleanup_cmd, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["cleanup", "temp", "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["error"]["code"] == "api_error"
+ assert "Cannot connect to mineru server" in payload["error"]["message"]
+ assert "Error:" not in result.stdout
+
+
+def test_config_parsing_rules_list_json_error_is_machine_readable(monkeypatch: Any) -> None:
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def list_parsing_rules(self) -> Any:
+ raise RuntimeError("('rule_not_found', 'No parsing rules backend.', 'rule_id')")
+
+ monkeypatch.setattr(config, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["config", "parsing-rules", "list", "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.stdout)
+ assert payload["error"]["code"] == "rule_not_found"
+ assert payload["error"]["param"] == "rule_id"
+ assert "Error:" not in result.stdout
+
+
def test_parse_failed_response_exits_nonzero(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.unsupported"
source.write_bytes(b"unsupported")