Skip to content

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

feat: small fixes

jinzhenj4bc4f09ed655
diff --git a/mineru/cli/commands/forget.py b/mineru/cli/commands/forget.py
index e6945cf7..8601ea36 100644
--- a/mineru/cli/commands/forget.py
+++ b/mineru/cli/commands/forget.py
@@ -2,12 +2,11 @@
from __future__ import annotations
-import typer
-
from ...doclib.client import DoclibClient
from ...doclib.types import ForgetPathRequest
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
+from ..path_utils import normalize_cli_path
def forget_cmd(
@@ -21,8 +20,9 @@ def forget_cmd(
except Exception as exc:
exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot connect to mineru server. Run 'mineru server start' first.")
+ file_path = normalize_cli_path(path)
try:
- result = client.forget_path(ForgetPathRequest(path=path, dry_run=dry_run))
+ result = client.forget_path(ForgetPathRequest(path=file_path, dry_run=dry_run))
except Exception as exc:
exit_with_error(exc, json_mode=json_mode)
diff --git a/mineru/cli/commands/invalidate.py b/mineru/cli/commands/invalidate.py
index 475dd1e7..4ed819df 100644
--- a/mineru/cli/commands/invalidate.py
+++ b/mineru/cli/commands/invalidate.py
@@ -10,6 +10,7 @@ from ...doclib.client import DoclibClient
from ...doclib.types import InvalidateRequest
from ...types import Tier
from ..output import print_error, print_success
+from ..path_utils import normalize_cli_path
def invalidate_cmd(
@@ -17,7 +18,7 @@ def invalidate_cmd(
tier: Tier | None = typer.Option(None, "--tier", help="Parse tier to invalidate (omit = all tiers)"),
) -> None:
"""Mark done parse results as superseded."""
- file_path = str(Path(path).resolve())
+ file_path = normalize_cli_path(path)
if not Path(file_path).exists():
print_error(f"File not found: {file_path}")
diff --git a/mineru/cli/commands/parse.py b/mineru/cli/commands/parse.py
index b7d3b746..15eaeba0 100644
--- a/mineru/cli/commands/parse.py
+++ b/mineru/cli/commands/parse.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-import os
+import shlex
import shutil
import time
from pathlib import Path
@@ -25,12 +25,13 @@ 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 ..path_utils import normalize_cli_path
def _normalize_output_path(output: str | None) -> str | None:
if output is None or output == "-":
return output
- return os.path.abspath(os.path.expanduser(output))
+ return normalize_cli_path(output)
def _ensure_output_parent(output: str | None) -> str | None:
@@ -82,7 +83,7 @@ def parse_cmd(
verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose output"),
) -> None:
"""Parse a document file."""
- file_path = str(Path(os.path.expanduser(path)).resolve())
+ file_path = normalize_cli_path(path)
if not Path(file_path).exists():
exit_with_error(MineruError("file_not_found", f"File not found: {file_path}", "path"), json_mode=json_mode)
@@ -357,11 +358,12 @@ def output_doc_content_response(
Path(output_path).write_text(content.content, encoding="utf-8")
print_success(f"Written to {output_path}")
return
- print(content.content)
if content.next_request and not no_marker:
marker = _read_next_marker(content.next_request) if read_mode else _parse_next_marker(source_path, content.next_request)
if marker:
- print(marker)
+ print(_append_next_marker(content.content, marker))
+ return
+ print(content.content)
def _next_request_dict(next_request: ContentNextRequest | None) -> dict[str, str] | None:
@@ -377,6 +379,12 @@ def _next_request_dict(next_request: ContentNextRequest | None) -> dict[str, str
return result
+def _append_next_marker(content: str, marker: str) -> str:
+ newline_count = len(content) - len(content.rstrip("\n"))
+ separator = "\n" * max(2 - newline_count, 0)
+ return f"{content}{separator}{marker}"
+
+
def _parse_next_marker(path: str | None, next_request: ContentNextRequest) -> str | None:
if not path:
return None
@@ -385,7 +393,7 @@ def _parse_next_marker(path: str | None, next_request: ContentNextRequest) -> st
parts.extend(["--pages", next_request.page_range])
if next_request.after:
parts.extend(["--after", next_request.after])
- return f"<!-- Next: {' '.join(parts)} -->"
+ return f"<!-- Next: {shlex.join(parts)} -->"
def _read_next_marker(next_request: ContentNextRequest) -> str | None:
diff --git a/mineru/cli/commands/scan.py b/mineru/cli/commands/scan.py
index 5aa2f75c..3fa7f54e 100644
--- a/mineru/cli/commands/scan.py
+++ b/mineru/cli/commands/scan.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import os
from pathlib import Path
import time
@@ -11,6 +10,7 @@ from ...doclib.client import DoclibClient
from ...doclib.types import ScanRequest
from ..json_errors import exit_with_error
from ..output import print_error, print_info, print_json, print_success
+from ..path_utils import normalize_cli_path
def scan_cmd(
@@ -27,7 +27,7 @@ def scan_cmd(
def _scan_path(path: str, *, wait: int, no_wait: bool, json_mode: bool) -> None:
- scan_path = os.path.abspath(os.path.expanduser(path))
+ scan_path = normalize_cli_path(path)
if not Path(scan_path).exists():
raise MineruError("file_not_found", f"File or directory not found: {scan_path}", "path")
client = _client()
diff --git a/mineru/cli/commands/show.py b/mineru/cli/commands/show.py
index b654047c..50c4e625 100644
--- a/mineru/cli/commands/show.py
+++ b/mineru/cli/commands/show.py
@@ -2,13 +2,12 @@
from __future__ import annotations
-from pathlib import Path
-
import typer
from ...doclib.client import DoclibClient
from ..json_errors import exit_with_error
-from ..output import format_info, print_error, print_json
+from ..output import format_info, print_json
+from ..path_utils import normalize_cli_path
from .scan import _print_scan
app = typer.Typer(help="Show doclib resource details", no_args_is_help=True)
@@ -57,7 +56,7 @@ def show_file(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Show file, doc, and parse state for a local path."""
- file_path = str(Path(path).resolve())
+ file_path = normalize_cli_path(path)
try:
result = _client().get_file_by_path(file_path)
except Exception as exc:
diff --git a/mineru/cli/commands/watch.py b/mineru/cli/commands/watch.py
index d6a66100..878f9fb0 100644
--- a/mineru/cli/commands/watch.py
+++ b/mineru/cli/commands/watch.py
@@ -2,14 +2,13 @@
from __future__ import annotations
-import os
-
import typer
from ...doclib.client import DoclibClient
from ...doclib.types import ScanRequest, WatchInfo, WatchRequest
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
+from ..path_utils import normalize_cli_path
from .scan import _print_scan, _wait_for_scan
app = typer.Typer(help="Watch target management", no_args_is_help=True)
@@ -23,8 +22,9 @@ def watch_add(
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
"""Add a directory to watch."""
+ watch_path = normalize_cli_path(path)
try:
- data = _client().add_watch(WatchRequest(path=path, removable=removable, label=label))
+ data = _client().add_watch(WatchRequest(path=watch_path, removable=removable, label=label))
except Exception as exc:
exit_with_error(exc, json_mode=json_mode, fallback_message="Cannot add watch target.")
@@ -107,8 +107,8 @@ def _resolve_watch(client: DoclibClient, target: str) -> WatchInfo:
return watch
raise ValueError(f"watch_not_found: watch id {watch_id} not found")
- normalized = os.path.abspath(os.path.expanduser(target))
+ normalized = normalize_cli_path(target)
for watch in watches:
- if os.path.abspath(os.path.expanduser(watch.path)) == normalized:
+ if normalize_cli_path(watch.path) == normalized:
return watch
raise ValueError(f"watch_not_found: watch path {normalized} not found")
diff --git a/mineru/cli/path_utils.py b/mineru/cli/path_utils.py
new file mode 100644
index 00000000..e3a2d510
--- /dev/null
+++ b/mineru/cli/path_utils.py
@@ -0,0 +1,10 @@
+"""Path normalization helpers for CLI user input."""
+
+from __future__ import annotations
+
+import os
+
+
+def normalize_cli_path(path: str) -> str:
+ """Normalize a local filesystem path provided to the CLI."""
+ return os.path.normpath(os.path.abspath(os.path.expanduser(path)))
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index 7c333a29..d5dba129 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -1227,12 +1227,24 @@ def _resolve_default_tier(remote: bool = False) -> Tier:
for candidate in ("pro", "standard"):
if candidate in supported:
return candidate
+ actions = ["start a local parse-server"]
+ if not remote and health.remote_healthy and any(tier in health.remote_supported_tiers for tier in ("pro", "standard")):
+ actions.append("use --remote")
+ actions.append("explicitly pass --tier flash for text-only preview")
raise ParseFailure(
"quality_tier_unavailable",
- "No standard or pro engine available. Start a parse-server or use --tier flash for text-only preview.",
+ f"No standard or pro engine available. You can {_format_action_list(actions)}.",
)
+def _format_action_list(actions: list[str]) -> str:
+ if len(actions) == 1:
+ return actions[0]
+ if len(actions) == 2:
+ return f"{actions[0]} or {actions[1]}"
+ return f"{', '.join(actions[:-1])}, or {actions[-1]}"
+
+
def _json_file_exists_by_batch(data_dir: str, sha256: str, tier: Tier, batch: ParseRow) -> bool:
"""Check that the JSON result file for a parses batch row actually exists on disk."""
json_path = parse_batch_json_path(data_dir, sha256, tier, batch["page_range"], batch["done_at"])
diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.py
index bd740543..b5c7b479 100644
--- a/tests/unittest/test_cli_next_command_design.py
+++ b/tests/unittest/test_cli_next_command_design.py
@@ -2,13 +2,14 @@ from __future__ import annotations
import json
import os
+import shlex
from pathlib import Path
from typing import Any
import pytest
from typer.testing import CliRunner
-from mineru.cli.commands import config, list_resources, parse, read, server, show, telemetry
+from mineru.cli.commands import config, invalidate, list_resources, parse, read, server, show, telemetry
from mineru.cli.commands import cleanup as cleanup_cmd
from mineru.cli.commands import search as search_mod
from mineru.cli.commands import watch as watch_cmd
@@ -23,11 +24,13 @@ from mineru.doclib.types import (
DocContentResponse,
FileInfo,
FileInfoResponse,
+ InvalidateResponse,
ListParsesResponse,
ParseInfo,
ParseResponse,
TelemetryActionResponse,
TelemetryStatusResponse,
+ WatchInfo,
)
@@ -225,6 +228,24 @@ def test_parse_wait_ignores_failed_rows_outside_wait_ids(monkeypatch: Any, tmp_p
assert payload["content"]["content"] == "parsed"
+def test_parse_next_marker_quotes_windows_path() -> None:
+ path = r"C:\Users\jinzhenj\Downloads\2606.20787v1.pdf"
+ marker = parse._parse_next_marker(path, ContentNextRequest(page_range="7~10"))
+
+ assert marker is not None
+ command = marker.removeprefix("<!-- Next: ").removesuffix(" -->")
+ assert shlex.split(command) == ["mineru", "parse", path, "--pages", "7~10"]
+
+
+def test_parse_next_marker_escapes_double_quotes_in_path() -> None:
+ path = r'C:\Users\jinzhenj\Downloads\bad"name.pdf'
+ marker = parse._parse_next_marker(path, ContentNextRequest(page_range="7~10"))
+
+ assert marker is not None
+ command = marker.removeprefix("<!-- Next: ").removesuffix(" -->")
+ assert shlex.split(command) == ["mineru", "parse", path, "--pages", "7~10"]
+
+
def test_parse_json_no_wait_wraps_parse_and_null_content(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
source.write_bytes(b"%PDF-1.7\n")
@@ -285,6 +306,29 @@ def test_parse_expands_user_home_in_input_path(monkeypatch: Any, tmp_path: Path)
assert seen_paths == [str(source.resolve())]
+def test_watch_add_normalizes_user_path_before_request(monkeypatch: Any, tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ watched = home / "Documents"
+ watched.mkdir(parents=True)
+ seen_paths: list[str] = []
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def add_watch(self, request: Any) -> WatchInfo:
+ seen_paths.append(request.path)
+ return WatchInfo(id=1, path=request.path, status="active")
+
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setattr(watch_cmd, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["watch", "add", "~/Documents/../Documents", "--json"])
+
+ assert result.exit_code == 0
+ assert seen_paths == [os.path.normpath(os.path.abspath(os.path.expanduser("~/Documents/../Documents")))]
+
+
def test_parse_json_output_writes_file_and_returns_output_object(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
source.write_bytes(b"%PDF-1.7\n")
@@ -469,6 +513,65 @@ def test_show_file_uses_get_file_by_path(monkeypatch: Any, tmp_path: Path) -> No
assert calls == [str(source.resolve())]
+def test_show_file_normalizes_user_path_before_request(monkeypatch: Any, tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ source = home / "docs" / "demo.pdf"
+ source.parent.mkdir(parents=True)
+ source.write_bytes(b"%PDF-1.7\n")
+ calls: list[str] = []
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 30
+
+ def get_file_by_path(self, path: str) -> FileInfoResponse:
+ calls.append(path)
+ return FileInfoResponse(
+ file=FileInfo(
+ filename="demo.pdf",
+ path=path,
+ ext="pdf",
+ size_bytes=7,
+ mtime_ms=1,
+ status="active",
+ first_seen_at=1,
+ updated_at=1,
+ )
+ )
+
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setattr(show, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["show", "file", "~/docs/../docs/demo.pdf", "--json"])
+
+ assert result.exit_code == 0
+ assert calls == [os.path.normpath(os.path.abspath(os.path.expanduser("~/docs/../docs/demo.pdf")))]
+
+
+def test_invalidate_normalizes_user_path_before_request(monkeypatch: Any, tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ source = home / "docs" / "demo.pdf"
+ source.parent.mkdir(parents=True)
+ source.write_bytes(b"%PDF-1.7\n")
+ calls: list[str] = []
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 10
+
+ def invalidate(self, request: Any) -> InvalidateResponse:
+ calls.append(request.path)
+ return InvalidateResponse(target="parses", sha256="a" * 64, tier=request.tier, invalidated_count=1)
+
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setattr(invalidate, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["invalidate", "~/docs/../docs/demo.pdf", "--tier", "standard"])
+
+ assert result.exit_code == 0
+ assert calls == [os.path.normpath(os.path.abspath(os.path.expanduser("~/docs/../docs/demo.pdf")))]
+
+
def test_show_doc_expands_files(monkeypatch: Any) -> None:
calls: list[tuple[str, bool]] = []
@@ -641,6 +744,30 @@ def test_read_json_output_preserves_locator_next_request(monkeypatch: Any) -> No
assert payload["next_request"]["locator"] == "doc:ab12cd3/tier:standard/page:5"
+def test_read_markdown_output_separates_next_marker_with_blank_line(monkeypatch: Any) -> None:
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 60
+
+ def read_content(self, locator: str, **kwargs: Any) -> DocContentResponse:
+ return DocContentResponse(
+ sha256="a" * 64,
+ short_id="ab12cd3",
+ tier="standard",
+ format="markdown",
+ content="hello",
+ request_scope=ContentRequestScope(locator=locator, context=0, limit=30000),
+ next_request=ContentNextRequest(locator="doc:ab12cd3/tier:standard/page:5"),
+ )
+
+ monkeypatch.setattr(read, "DoclibClient", _Client)
+
+ result = runner.invoke(app, ["read", "doc:ab12cd3/tier:standard/page:4"])
+
+ assert result.exit_code == 0
+ assert "hello\n\n<!-- Next: mineru read doc:ab12cd3/tier:standard/page:5 -->" in result.output
+
+
def test_read_json_error_output_is_machine_readable(monkeypatch: Any) -> None:
class _Client:
def __init__(self, *, timeout: int) -> None:
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index 90022a15..0c9567d8 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -13,7 +13,7 @@ import pytest
from mineru.doclib.background.compaction import Compaction
from mineru.doclib.background.device_monitor import DeviceMonitor
from mineru.doclib.background.ingest import IngestWorkerPool
-from mineru.doclib.background.parse_server_health import ParseServerHealthCheck, api_server_args_for_tier
+from mineru.doclib.background.parse_server_health import ParseServerHealth, ParseServerHealthCheck, api_server_args_for_tier
from mineru.doclib.background.watch import WatchLoop
from mineru.doclib.core.db import DatabaseManager
from mineru.doclib.core.file_io import FileStat, get_file_stat
@@ -24,7 +24,9 @@ from mineru.doclib.services.cleanup_svc import CleanupService
from mineru.doclib.services.config_svc import ConfigService
from mineru.doclib.services import parse_svc as parse_svc_module
from mineru.doclib.services.parse_svc import (
+ ParseFailure,
ParseService,
+ _resolve_default_tier,
filter_pages_by_user_range,
load_pages_from_done_batches,
parse_batch_json_path,
@@ -248,6 +250,42 @@ def test_managed_api_server_args_use_tier_for_process_start() -> None:
assert api_server_args_for_tier("pro") == ["--tier", "pro", "--port", "15981"]
+def test_default_tier_error_mentions_remote_when_remote_is_healthy(monkeypatch: pytest.MonkeyPatch) -> None:
+ health = ParseServerHealth(
+ local_healthy=False,
+ local_supported_tiers=["flash"],
+ remote_healthy=True,
+ remote_supported_tiers=["standard", "pro"],
+ )
+ monkeypatch.setattr("mineru.doclib.background.parse_server_health.get_health", lambda: health)
+
+ with pytest.raises(ParseFailure) as exc_info:
+ _resolve_default_tier(remote=False)
+
+ assert exc_info.value.code == "quality_tier_unavailable"
+ assert "--remote" in exc_info.value.message
+ assert "local parse-server" in exc_info.value.message
+ assert "--tier flash" in exc_info.value.message
+
+
+def test_default_tier_error_omits_remote_when_remote_is_unhealthy(monkeypatch: pytest.MonkeyPatch) -> None:
+ health = ParseServerHealth(
+ local_healthy=False,
+ local_supported_tiers=["flash"],
+ remote_healthy=False,
+ remote_supported_tiers=[],
+ )
+ monkeypatch.setattr("mineru.doclib.background.parse_server_health.get_health", lambda: health)
+
+ with pytest.raises(ParseFailure) as exc_info:
+ _resolve_default_tier(remote=False)
+
+ assert exc_info.value.code == "quality_tier_unavailable"
+ assert "--remote" not in exc_info.value.message
+ assert "local parse-server" in exc_info.value.message
+ assert "--tier flash" in exc_info.value.message
+
+
def test_parse_server_health_probe_disables_env_proxy_for_local_urls(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[bool] = []