Skip to content

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

feat: add invalidate, cache validation, done_at filenames, and comprehensive error handling

jinzhenj020426474465
diff --git a/NEXT-CLI.md b/NEXT-CLI.md
index 061b5bbe..da51704b 100644
--- a/NEXT-CLI.md
+++ b/NEXT-CLI.md
@@ -513,6 +513,7 @@ mineru config parsing-rules add/list/rm # 解析规则
mineru config parse-server local.mode <mode> # 本地 parse-server 模式: disabled | managed | self_hosted
mineru config parse-server local.managed-tier <tier> # managed 模式 tier: standard | pro
mineru config parse-server local.self_hosted_url <url> # self_hosted 模式的 parse-server 地址
+mineru config parse-server local.self-hosted-api-key <key> # self_hosted 模式的 API Key(可选)
mineru config parse-server remote.url <url> # 远程 parse-server 地址(默认 mineru.net)
mineru config parse-server remote.api-key <key> # 远程 API Key
```
diff --git a/mineru/cli_next/commands/invalidate.py b/mineru/cli_next/commands/invalidate.py
new file mode 100644
index 00000000..6e02ba2f
--- /dev/null
+++ b/mineru/cli_next/commands/invalidate.py
@@ -0,0 +1,42 @@
+"""mineru invalidate — mark parsed results as superseded."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import typer
+
+from mineru.doclib.client import MineruClient
+from mineru.cli_next.output import print_error, print_success
+
+
+def invalidate_cmd(
+ path: str = typer.Argument(..., help="Path to the document file"),
+ tier: str = 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())
+
+ if not Path(file_path).exists():
+ print_error(f"File not found: {file_path}")
+ raise typer.Exit(1)
+
+ try:
+ client = MineruClient(timeout=10)
+ except Exception:
+ print_error("Cannot connect to mineru server. Run 'mineru server start' first.")
+ raise typer.Exit(1) from None
+
+ try:
+ result = client.invalidate(file_path, tier=tier)
+ except Exception as exc:
+ print_error(str(exc))
+ raise typer.Exit(1) from None
+
+ count = result.get("invalidated", 0)
+ sha256 = result.get("sha256", "")[:12]
+ tier_label = f" (tier={tier})" if tier else ""
+ if count:
+ print_success(f"Invalidated {count} batch(es) for {sha256}...{tier_label}. Use 'mineru parse' to re-parse.")
+ else:
+ print(f"No done batches found for {sha256}...{tier_label}.")
diff --git a/mineru/cli_next/commands/parse.py b/mineru/cli_next/commands/parse.py
index 7e9a8ac1..92861450 100644
--- a/mineru/cli_next/commands/parse.py
+++ b/mineru/cli_next/commands/parse.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import sys
import time
from pathlib import Path
@@ -14,13 +13,17 @@ from mineru.cli_next.output import format_parse_result, print_error, print_succe
def parse_cmd(
path: str = typer.Argument(..., help="Path to the document file"),
- tier: str = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro"),
+ tier: str = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro (default: server decides)"),
pages: str = typer.Option(
None, "-p", "--pages", help="Page range, e.g. '1~5' or 'all'"
),
+ format: str = typer.Option(
+ "markdown", "-f", "--format", help="Output format: markdown, text, json, html"
+ ),
force: bool = typer.Option(False, "--force", help="Force re-parse, ignore cache"),
- remote: bool = typer.Option(False, "--remote", help="Use remote parse-server (default: mineru.net)"),
- remote_url: str = typer.Option(None, "--remote-url", help="Custom remote parse-server URL. Requires --remote"),
+ remote: bool = typer.Option(False, "--remote", help="Use remote parse-server (https://mineru.net/api)"),
+ remote_url: str = typer.Option(None, "--remote-url", help="Custom remote server URL (overrides default)"),
+ api_key: str = typer.Option(None, "--api-key", envvar="MINERU_API_KEY", help="API key for remote parse-server"),
wait: int = typer.Option(
60, "--wait", help="Max seconds to wait for parse to complete"
),
@@ -51,7 +54,9 @@ def parse_cmd(
# send parse request
try:
- result = client.parse(file_path, tier=tier, pages=pages, force=force, remote=remote, remote_url=remote_url)
+ result = client.parse(file_path, tier=tier, pages=pages, format=format,
+ force=force, remote=remote, remote_url=remote_url,
+ api_key=api_key)
except Exception as exc:
print_error(str(exc))
raise typer.Exit(1) from None
diff --git a/mineru/cli_next/main.py b/mineru/cli_next/main.py
index eea36dfb..8fd6fb34 100644
--- a/mineru/cli_next/main.py
+++ b/mineru/cli_next/main.py
@@ -21,14 +21,18 @@ app.add_typer(config.app, name="config")
@app.command()
def parse(
path: str = typer.Argument(..., help="Path to the document file"),
- tier: str = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro"),
+ tier: str = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro (default: server decides)"),
pages: str = typer.Option(
None, "-p", "--pages", help="Page range, e.g. '1~5' or 'all'"
),
- force: bool = typer.Option(False, "--force", help="Force re-parse, ignore cache"),
- wait: int = typer.Option(
- 60, "--wait", help="Max seconds to wait for parse to complete"
+ format: str = typer.Option(
+ "markdown", "-f", "--format", help="Output format: markdown, text, json, html"
),
+ force: bool = typer.Option(False, "--force", help="Force re-parse, ignore cache"),
+ remote: bool = typer.Option(False, "--remote", help="Use remote parse-server (https://mineru.net/api)"),
+ remote_url: str = typer.Option(None, "--remote-url", help="Custom remote server URL (overrides default)"),
+ api_key: str = typer.Option(None, "--api-key", envvar="MINERU_API_KEY", help="API key for remote parse-server"),
+ wait: int = typer.Option(60, "--wait", help="Max seconds to wait for parse to complete"),
no_wait: bool = typer.Option(False, "--no-wait", help="Don't wait — return immediately"),
output: str = typer.Option(None, "-o", "--output", help="Output file path (default: STDOUT)"),
no_marker: bool = typer.Option(
@@ -41,12 +45,24 @@ def parse(
from .commands.parse import parse_cmd
parse_cmd(
- path=path, tier=tier, pages=pages, force=force,
+ path=path, tier=tier, pages=pages, format=format, force=force,
+ remote=remote, remote_url=remote_url, api_key=api_key,
wait=wait, no_wait=no_wait, output=output,
no_marker=no_marker, json_mode=json_mode, verbose=verbose,
)
+def invalidate(
+ path: str = typer.Argument(..., help="Path to the document file"),
+ tier: str = typer.Option(None, "--tier", help="Parse tier to invalidate (omit = all tiers)"),
+) -> None:
+ """Mark done parse results as superseded so the next parse re-runs."""
+ from .commands.invalidate import invalidate_cmd
+
+ invalidate_cmd(path=path, tier=tier)
+
+
@app.command()
def search(
query: str = typer.Argument(..., help="Search query"),
diff --git a/mineru/cli_next/output.py b/mineru/cli_next/output.py
index 9b8b8f0a..1096ad72 100644
--- a/mineru/cli_next/output.py
+++ b/mineru/cli_next/output.py
@@ -131,12 +131,24 @@ def format_server_status(data: dict, json_mode: bool = False) -> None:
ps_table.add_column("Tiers", style="green")
for label, key in [("Local", "local"), ("Remote", "remote")]:
ps = ps_data.get(key, {})
- healthy_str = "yes" if ps.get("healthy") else "no"
+ if ps.get("starting"):
+ healthy_str = "starting"
+ elif ps.get("healthy"):
+ healthy_str = "yes"
+ else:
+ healthy_str = "no"
tiers_str = ", ".join(ps.get("supported_tiers", [])) or "-"
mode = ps.get("mode", "")
label_str = f"{label} ({mode})" if mode else label
ps_table.add_row(label_str, healthy_str, tiers_str)
console.print(ps_table)
+
+ # recent logs
+ logs = data.get("recent_logs", [])
+ if logs:
+ log_text = "".join(logs) # last 100 lines from server
+ panel = Panel(log_text.strip() or "(empty)", title="Recent Logs", border_style="dim")
+ console.print(panel)
else:
print(f"Server running (PID {data.get('pid')}), {data.get('files_total')} files")
diff --git a/mineru/doclib/background/compaction.py b/mineru/doclib/background/compaction.py
index 09ee99fa..e51ea18f 100644
--- a/mineru/doclib/background/compaction.py
+++ b/mineru/doclib/background/compaction.py
@@ -90,6 +90,10 @@ class Compaction:
"DELETE FROM parses WHERE sha256=? AND tier=? AND status='done'",
(sha256, tier),
)
+ await self.db.execute(
+ "DELETE FROM parses WHERE sha256=? AND tier=? AND status='superseded'",
+ (sha256, tier),
+ )
for pages_str in merged_ranges:
await self.db.execute(
"INSERT INTO parses (sha256, tier, pages, status, done_at, priority, "
@@ -97,33 +101,34 @@ class Compaction:
(sha256, tier, pages_str, max_done_at, now, now),
)
- # compact JSON files
- await self._compact_json(sha256, tier, merged_ranges)
+ # compact JSON files (only from done batches, not superseded)
+ await self._compact_json(sha256, tier, merged_ranges, rows, max_done_at)
return len(rows) - len(merged_ranges)
async def _compact_json(
- self, sha256: str, tier: str, merged_ranges: list[str]
+ self, sha256: str, tier: str, merged_ranges: list[str],
+ done_rows: list[dict], max_done_at: int,
) -> None:
- """Merge per-batch middle_*.json files to match compacted parses rows."""
+ """Merge per-batch JSON files to match compacted parses rows.
+ Only reads files belonging to *done_rows* — ignores superseded files."""
data_dir = os.path.expanduser(DATA_DIR)
tier_dir = os.path.join(data_dir, "parsed", sha256[:2], sha256, tier)
if not os.path.isdir(tier_dir):
return
- # collect all pages + markdown from existing files
+ # only read files from done batches (exclude superseded)
+ # process oldest first → newest overwrites (done_rows is sorted by done_at DESC)
pages_by_idx: dict[int, dict] = {}
- md_texts: dict[str, str] = {}
- for fname in os.listdir(tier_dir):
+ for row in reversed(done_rows):
+ key = _safe_filename(row["pages"], row["done_at"])
+ fpath = os.path.join(tier_dir, f"{key}.json")
+ if not os.path.isfile(fpath):
+ continue
try:
- if fname.endswith(".json"):
- with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:
- for p in _json.load(f).get("pdf_info", []):
- pages_by_idx[p["page_idx"]] = p
- elif fname.endswith(".md"):
- stem = fname[:-3] # remove .md
- with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:
- md_texts[stem] = f.read()
+ with open(fpath, encoding="utf-8") as f:
+ for p in _json.load(f).get("pages", []):
+ pages_by_idx[p["page_idx"]] = p
except Exception:
pass
@@ -132,13 +137,13 @@ class Compaction:
# delete old files
for fname in os.listdir(tier_dir):
- if fname.endswith(".json") or fname.endswith(".md"):
+ if fname.endswith(".json"):
try:
os.unlink(os.path.join(tier_dir, fname))
except OSError:
pass
- # write one compacted JSON + MD per merged range
+ # write one compacted JSON per merged range
for pages_str in merged_ranges:
page_set = parse_range_set(pages_str)
json_pages = [
@@ -146,24 +151,16 @@ class Compaction:
]
if not json_pages:
continue
- key = _safe_filename(pages_str)
+ key = _safe_filename(pages_str, max_done_at)
json_path = os.path.join(tier_dir, f"{key}.json")
try:
with open(json_path, "w", encoding="utf-8") as f:
_json.dump(
- {"pdf_info": json_pages}, f, ensure_ascii=False, indent=2
+ {"pages": json_pages}, f, ensure_ascii=False, indent=2
)
except Exception:
pass
- md_path = os.path.join(tier_dir, f"{key}.md")
- try:
- merged_md = "\n".join(md for k, md in sorted(md_texts.items()))
- with open(md_path, "w", encoding="utf-8") as f:
- f.write(merged_md)
- except Exception:
- pass
-
-def _safe_filename(s: str) -> str:
- return s # pages string is already safe: "1~5,43~47"
+def _safe_filename(s: str, done_at: int = 0) -> str:
+ return f"{s}_{done_at}" if done_at else s
diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.py
index 11630c0e..50f7a7bc 100644
--- a/mineru/doclib/background/parse_server_health.py
+++ b/mineru/doclib/background/parse_server_health.py
@@ -19,6 +19,8 @@ MAX_RESTART_ATTEMPTS = 3
@dataclass
class ParseServerHealth:
local_healthy: bool = False
+ local_starting: bool = False
+ local_started_at: float = 0.0
local_supported_tiers: list[str] = field(default_factory=list)
local_mode: str = "disabled"
self_hosted_url: str | None = None
@@ -64,6 +66,8 @@ class ParseServerHealthCheck:
healthy, tiers = await self._probe(url)
health.local_healthy = healthy
health.local_supported_tiers = tiers
+ if healthy:
+ health.local_starting = False
# probe remote
remote_url = (await self.config_svc.get("parse_server.remote.url")) or "https://mineru.net/api"
@@ -71,28 +75,37 @@ class ParseServerHealthCheck:
health.remote_healthy = healthy
health.remote_supported_tiers = tiers
- # managed mode: restart if crashed
+ # managed mode: restart if crashed (skip if still starting — give it 30s)
if health.local_mode == "managed" and not health.local_healthy:
+ if health.local_starting:
+ elapsed = asyncio.get_event_loop().time() - health.local_started_at
+ if elapsed < 30:
+ continue # still loading models, don't restart
+ logger.warning("Managed parse-server is unhealthy, attempting restart")
await self._try_restart_managed(health)
async def _try_restart_managed(self, health: ParseServerHealth) -> None:
if health.restart_count >= MAX_RESTART_ATTEMPTS:
logger.error(
- f"Managed parse-server failed {health.restart_count} restarts, disabling"
+ f"Managed parse-server failed %d restarts, disabling", MAX_RESTART_ATTEMPTS
)
health.local_mode = "disabled"
return
health.restart_count += 1
managed_tier = (await self.config_svc.get("parse_server.local.managed_tier")) or "standard"
- logger.info(f"Restarting managed parse-server (attempt {health.restart_count}/{MAX_RESTART_ATTEMPTS})")
+ tier_to_backend = {"standard": "pipeline", "pro": "vlm"}
+ backend = tier_to_backend.get(managed_tier, "pipeline")
+ cmd = [sys.executable, "-m", "mineru.parser.api_server",
+ "--backend", backend, "--port", "15981"]
+ logger.info("Restarting managed parse-server (attempt %d/%d): %s",
+ health.restart_count, MAX_RESTART_ATTEMPTS, " ".join(cmd))
try:
- proc = subprocess.Popen(
- [sys.executable, "-m", "mineru.parser.api_server", "--backend", managed_tier, "--port", "15981"],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- )
+ proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ logger.info("Managed parse-server restarted (PID %d, backend=%s)", proc.pid, backend)
health.managed_proc = proc
+ health.local_starting = True
+ health.local_started_at = asyncio.get_event_loop().time()
except Exception as exc:
logger.error(f"Failed to restart managed parse-server: {exc}")
diff --git a/mineru/doclib/client.py b/mineru/doclib/client.py
index edfeb963..7601eac1 100644
--- a/mineru/doclib/client.py
+++ b/mineru/doclib/client.py
@@ -50,16 +50,21 @@ class MineruClient:
resp = self._client.post(url_path, json=json_data or {})
else:
resp = self._client.delete(url_path, params=query_params or {})
- resp.raise_for_status()
except httpx.ConnectError:
raise ServerNotRunningError() from None
- data = resp.json()
+ try:
+ data = resp.json()
+ except Exception:
+ resp.raise_for_status()
+ raise MineruError("internal_error", f"Invalid server response: HTTP {resp.status_code}") from None
if not isinstance(data, dict):
+ resp.raise_for_status()
return {}
if "error" in data:
err = data["error"]
if isinstance(err, dict):
raise _error_from_response(err)
+ resp.raise_for_status()
return data
# ── server ─────────────────────────────────────────────────
@@ -78,9 +83,11 @@ class MineruClient:
*,
tier: str | None = None,
pages: str | None = None,
+ format: str = "markdown",
force: bool = False,
remote: bool = False,
remote_url: str | None = None,
+ api_key: str | None = None,
) -> dict:
return self._post(
"/parse",
@@ -88,12 +95,20 @@ class MineruClient:
"path": path,
"tier": tier,
"pages": pages,
+ "format": format,
"force": force,
"remote": remote,
"remote_url": remote_url,
+ "api_key": api_key,
},
)
+ def invalidate(self, path: str, *, tier: str | None = None) -> dict:
+ params = {"path": path}
+ if tier:
+ params["tier"] = tier
+ return self._get("/parse/invalidate", **params)
+
def parse_status(self, sha256: str, tier: str) -> dict:
return self._get("/parse/status", sha256=sha256, tier=tier)
diff --git a/mineru/doclib/core/db.py b/mineru/doclib/core/db.py
index 600fbd6a..02f97b5b 100644
--- a/mineru/doclib/core/db.py
+++ b/mineru/doclib/core/db.py
@@ -2,147 +2,29 @@ from __future__ import annotations
import os
import time
+from pathlib import Path
import aiosqlite
from ..config import SQLiteConfig
-SCHEMA_VERSION = 1
-
-CREATE_TABLES_SQL = [
- # ── files ──────────────────────────────────────────────────────
- """
- CREATE TABLE IF NOT EXISTS files (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- path TEXT NOT NULL UNIQUE,
- filename TEXT NOT NULL,
- ext TEXT NOT NULL,
- size_bytes INTEGER NOT NULL,
- mtime_ms INTEGER NOT NULL,
- birthtime_ms INTEGER,
- sha256 TEXT REFERENCES docs(sha256),
- watch_id INTEGER REFERENCES watch_targets(id),
- scan_status TEXT NOT NULL DEFAULT 'active',
- locked_at INTEGER,
- error_code TEXT,
- error_msg TEXT,
- deleted_at INTEGER,
- first_seen_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
- );
- """,
- "CREATE INDEX IF NOT EXISTS idx_files_sha256 ON files(sha256);",
- "CREATE INDEX IF NOT EXISTS idx_files_watch_id ON files(watch_id);",
- "CREATE INDEX IF NOT EXISTS idx_files_scan_status ON files(scan_status);",
- # ── docs ───────────────────────────────────────────────────────
- """
- CREATE TABLE IF NOT EXISTS docs (
- sha256 TEXT PRIMARY KEY,
- size_bytes INTEGER NOT NULL,
- mime_type TEXT,
- page_count INTEGER,
- lang TEXT,
- title TEXT,
- author TEXT,
- subject TEXT,
- keywords TEXT,
- is_encrypted INTEGER NOT NULL DEFAULT 0,
- is_scanned INTEGER NOT NULL DEFAULT 0,
- meta_tier TEXT,
- first_seen_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
- );
- """,
- # ── parses ─────────────────────────────────────────────────────
- """
- CREATE TABLE IF NOT EXISTS parses (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- sha256 TEXT NOT NULL REFERENCES docs(sha256),
- tier TEXT NOT NULL,
- pages TEXT NOT NULL,
- status TEXT NOT NULL DEFAULT 'pending',
- priority INTEGER NOT NULL DEFAULT 0,
- locked_at INTEGER,
- error_code TEXT,
- error_msg TEXT,
- privacy TEXT NOT NULL DEFAULT 'local',
- remote_url TEXT,
- via TEXT,
- output_path TEXT,
- done_at INTEGER,
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
- );
- """,
- "CREATE INDEX IF NOT EXISTS idx_parses_status ON parses(status, priority DESC, created_at ASC);",
- "CREATE INDEX IF NOT EXISTS idx_parses_doc ON parses(sha256, tier);",
- # ── fts_contents ───────────────────────────────────────────────
- """
- CREATE VIRTUAL TABLE IF NOT EXISTS fts_contents USING fts5(
- sha256 UNINDEXED,
- tier UNINDEXED,
- text,
- title,
- author,
- filename,
- tokenize='unicode61'
- );
- """,
- # ── fts_filenames ──────────────────────────────────────────────
- """
- CREATE VIRTUAL TABLE IF NOT EXISTS fts_filenames USING fts5(
- file_id UNINDEXED,
- filename,
- ext,
- tokenize='unicode61'
- );
- """,
- # ── watch_targets ──────────────────────────────────────────────
- """
- CREATE TABLE IF NOT EXISTS watch_targets (
- id INTEGER PRIMARY KEY,
- path TEXT NOT NULL UNIQUE,
- label TEXT,
- removable INTEGER NOT NULL DEFAULT 0,
- enabled INTEGER NOT NULL DEFAULT 1,
- recursive INTEGER NOT NULL DEFAULT 0,
- watch_status TEXT NOT NULL DEFAULT 'active',
- unreachable_at INTEGER,
- last_scan_at INTEGER,
- last_scan_files INTEGER DEFAULT 0
- );
- """,
- # ── rules ──────────────────────────────────────────────────────
- """
- CREATE TABLE IF NOT EXISTS rules (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT,
- rule_type TEXT NOT NULL,
- pattern TEXT NOT NULL,
- tier TEXT,
- pages TEXT,
- remote INTEGER NOT NULL DEFAULT 0,
- enabled INTEGER NOT NULL DEFAULT 1,
- priority INTEGER NOT NULL DEFAULT 0,
- hit_count INTEGER NOT NULL DEFAULT 0
- );
- """,
- # ── config ─────────────────────────────────────────────────────
- """
- CREATE TABLE IF NOT EXISTS config (
- key TEXT PRIMARY KEY,
- value TEXT NOT NULL
- );
- """,
- # ── _migrations ────────────────────────────────────────────────
- """
- CREATE TABLE IF NOT EXISTS _migrations (
- version INTEGER PRIMARY KEY,
- applied_at INTEGER NOT NULL,
- description TEXT
- );
- """,
-]
+SCHEMA_VERSION = 2
+_MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
+
+_CREATE_TABLES_SQL: list[str] = [] # filled by _load_init_sql()
+
+
+def _load_init_sql() -> list[str]:
+ """Load the initial-schema SQL from the migration file so that
+ ``initialize()`` is self-contained for fresh databases."""
+ init_path = _MIGRATIONS_DIR / "001_init.sql"
+ if not init_path.is_file():
+ return []
+ sql = init_path.read_text(encoding="utf-8")
+ return [s.strip() for s in sql.split(";") if s.strip()]
+
+
+_CREATE_TABLES_SQL = _load_init_sql()
DEFAULT_CONFIG = {
"data_dir": "~/MinerU",
@@ -208,7 +90,7 @@ class DatabaseManager:
await conn.execute("PRAGMA wal_autocheckpoint=1000")
await conn.execute("PRAGMA journal_size_limit=33554432")
- for sql in CREATE_TABLES_SQL:
+ for sql in _CREATE_TABLES_SQL:
await conn.execute(sql)
# ── migrations ──────────────────────────────────────────
@@ -311,6 +193,22 @@ def _now_ms() -> int:
async def _apply_migration(conn: aiosqlite.Connection, version: int) -> None:
- """Apply a single schema migration. Extend here as schema evolves."""
- # version 1: initial schema — already created by CREATE_TABLES_SQL
- pass
+ """Apply a single schema migration from its SQL file."""
+ candidates = sorted(_MIGRATIONS_DIR.glob(f"{version:03d}_*.sql"))
+ if not candidates:
+ raise FileNotFoundError(f"No migration file found for version {version}")
+ for p in candidates:
+ raw = p.read_text(encoding="utf-8")
+ # strip comment lines, then split into statements
+ lines = [l for l in raw.splitlines() if not l.strip().startswith("--")]
+ sql = "\n".join(lines)
+ for stmt in sql.split(";"):
+ stmt = stmt.strip()
+ if not stmt:
+ continue
+ try:
+ await conn.execute(stmt)
+ except Exception as exc:
+ if "duplicate column name" in str(exc):
+ continue
+ raise
diff --git a/mineru/doclib/migrations/001_init.sql b/mineru/doclib/migrations/001_init.sql
new file mode 100644
index 00000000..77e90ea9
--- /dev/null
+++ b/mineru/doclib/migrations/001_init.sql
@@ -0,0 +1,115 @@
+-- v001: Initial schema
+-- Applied to new databases. For existing databases, see 002_add_parse_columns.sql.
+
+CREATE TABLE IF NOT EXISTS files (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ path TEXT NOT NULL UNIQUE,
+ filename TEXT NOT NULL,
+ ext TEXT NOT NULL,
+ size_bytes INTEGER NOT NULL,
+ mtime_ms INTEGER NOT NULL,
+ birthtime_ms INTEGER,
+ sha256 TEXT REFERENCES docs(sha256),
+ watch_id INTEGER REFERENCES watch_targets(id),
+ scan_status TEXT NOT NULL DEFAULT 'active',
+ locked_at INTEGER,
+ error_code TEXT,
+ error_msg TEXT,
+ deleted_at INTEGER,
+ first_seen_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_files_sha256 ON files(sha256);
+CREATE INDEX IF NOT EXISTS idx_files_watch_id ON files(watch_id);
+CREATE INDEX IF NOT EXISTS idx_files_scan_status ON files(scan_status);
+
+CREATE TABLE IF NOT EXISTS docs (
+ sha256 TEXT PRIMARY KEY,
+ size_bytes INTEGER NOT NULL,
+ mime_type TEXT,
+ page_count INTEGER,
+ lang TEXT,
+ title TEXT,
+ author TEXT,
+ subject TEXT,
+ keywords TEXT,
+ is_encrypted INTEGER NOT NULL DEFAULT 0,
+ is_scanned INTEGER NOT NULL DEFAULT 0,
+ meta_tier TEXT,
+ first_seen_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+
+CREATE TABLE IF NOT EXISTS parses (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ sha256 TEXT NOT NULL REFERENCES docs(sha256),
+ tier TEXT NOT NULL,
+ pages TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending',
+ priority INTEGER NOT NULL DEFAULT 0,
+ locked_at INTEGER,
+ error_code TEXT,
+ error_msg TEXT,
+ privacy TEXT NOT NULL DEFAULT 'local',
+ remote_url TEXT,
+ via TEXT,
+ done_at INTEGER,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_parses_status ON parses(status, priority DESC, created_at ASC);
+CREATE INDEX IF NOT EXISTS idx_parses_doc ON parses(sha256, tier);
+
+CREATE VIRTUAL TABLE IF NOT EXISTS fts_contents USING fts5(
+ sha256 UNINDEXED,
+ tier UNINDEXED,
+ text,
+ title,
+ author,
+ filename,
+ tokenize='unicode61'
+);
+
+CREATE VIRTUAL TABLE IF NOT EXISTS fts_filenames USING fts5(
+ file_id UNINDEXED,
+ filename,
+ ext,
+ tokenize='unicode61'
+);
+
+CREATE TABLE IF NOT EXISTS watch_targets (
+ id INTEGER PRIMARY KEY,
+ path TEXT NOT NULL UNIQUE,
+ label TEXT,
+ removable INTEGER NOT NULL DEFAULT 0,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ recursive INTEGER NOT NULL DEFAULT 0,
+ watch_status TEXT NOT NULL DEFAULT 'active',
+ unreachable_at INTEGER,
+ last_scan_at INTEGER,
+ last_scan_files INTEGER DEFAULT 0
+);
+
+CREATE TABLE IF NOT EXISTS rules (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT,
+ rule_type TEXT NOT NULL,
+ pattern TEXT NOT NULL,
+ tier TEXT,
+ pages TEXT,
+ remote INTEGER NOT NULL DEFAULT 0,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ priority INTEGER NOT NULL DEFAULT 0,
+ hit_count INTEGER NOT NULL DEFAULT 0
+);
+
+CREATE TABLE IF NOT EXISTS config (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+);
+
+CREATE TABLE IF NOT EXISTS _migrations (
+ version INTEGER PRIMARY KEY,
+ applied_at INTEGER NOT NULL,
+ description TEXT
+);
diff --git a/mineru/doclib/migrations/002_add_parse_columns.sql b/mineru/doclib/migrations/002_add_parse_columns.sql
new file mode 100644
index 00000000..c616c0f0
--- /dev/null
+++ b/mineru/doclib/migrations/002_add_parse_columns.sql
@@ -0,0 +1,6 @@
+-- v002: Add privacy / remote_url / via / output_path columns to parses;
+
+ALTER TABLE parses ADD COLUMN privacy TEXT DEFAULT 'local';
+ALTER TABLE parses ADD COLUMN remote_url TEXT;
+ALTER TABLE parses ADD COLUMN via TEXT;
+ALTER TABLE parses ADD COLUMN output_path TEXT;
diff --git a/mineru/doclib/routes/parse.py b/mineru/doclib/routes/parse.py
index c94ccded..7cb6dad1 100644
--- a/mineru/doclib/routes/parse.py
+++ b/mineru/doclib/routes/parse.py
@@ -38,46 +38,75 @@ async def parse_status(
return result
[email protected]("/parse/invalidate")
+async def parse_invalidate(
+ request: Request,
+ path: str = Query(..., description="File path"),
+ tier: str | None = Query(None, description="Parse tier to invalidate (omit = all tiers)"),
+) -> dict:
+ """Mark done parse results as superseded."""
+ state = request.state.app
+ sha256 = await _resolve_sha256(state, path)
+ if sha256 is None:
+ return {"sha256": "", "tier": tier or "", "invalidated": 0, "error": "File not found or not ingested"}
+ count = await state.parse_svc.invalidate(sha256, tier)
+ return {"sha256": sha256, "tier": tier, "invalidated": count}
+
+
+async def _resolve_sha256(state, path: str) -> str | None:
+ row = await state.db.fetchone(
+ "SELECT sha256 FROM files WHERE path=? AND scan_status='active'", (path,)
+ )
+ if row and row["sha256"]:
+ return row["sha256"]
+ return None
+
+
@router.get("/parse/content")
async def parse_content(
request: Request,
sha256: str = Query(...),
tier: str = Query(...),
output: str | None = Query(None),
+ no_marker: bool = Query(False, description="Omit page markers from markdown output"),
) -> dict:
- """Read parsed markdown content from saved .md files."""
+ """Generate markdown on the fly from saved JSON results."""
state = request.state.app
data_dir = getattr(state, "data_dir", os.path.expanduser("~/MinerU"))
tier_dir = os.path.join(data_dir, "parsed", sha256[:2], sha256, tier)
if not os.path.isdir(tier_dir):
- return {
- "sha256": sha256,
- "tier": tier,
- "content": None,
- "error": "Content not found",
- }
-
- # merge all .md files, sorted by filename
- parts: list[str] = []
- for fname in sorted(os.listdir(tier_dir)):
- if not fname.endswith(".md"):
+ return {"sha256": sha256, "tier": tier, "content": None, "error": "Content not found"}
+
+ # read JSON files from done batches (DB-driven, no directory listing)
+ import json as _json
+
+ from mineru.render import render_markdown
+ from mineru.types import PageInfo
+ from mineru.doclib.services.parse_svc import _safe_filename
+
+ done_rows = await state.db.fetchall(
+ "SELECT pages, done_at FROM parses WHERE sha256=? AND tier=? AND status='done' ORDER BY done_at DESC",
+ (sha256, tier),
+ )
+ all_pages: list[PageInfo] = []
+ for row in done_rows:
+ key = _safe_filename(row["pages"], row["done_at"])
+ fpath = os.path.join(tier_dir, f"{key}.json")
+ if not os.path.isfile(fpath):
continue
try:
- with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:
- parts.append(f.read())
+ with open(fpath, encoding="utf-8") as f:
+ data = _json.load(f)
+ for raw in data.get("pages", []):
+ all_pages.append(PageInfo.from_dict(raw))
except Exception:
pass
- if not parts:
- return {
- "sha256": sha256,
- "tier": tier,
- "content": None,
- "error": "Content not found",
- }
+ if not all_pages:
+ return {"sha256": sha256, "tier": tier, "content": None, "error": "Content not found"}
- content = "\n".join(parts)
+ content = render_markdown(all_pages, add_markers=not no_marker)
if output and output != "-":
os.makedirs(os.path.dirname(os.path.abspath(output)), exist_ok=True)
diff --git a/mineru/doclib/routes/server.py b/mineru/doclib/routes/server.py
index 53773aa9..9900d747 100644
--- a/mineru/doclib/routes/server.py
+++ b/mineru/doclib/routes/server.py
@@ -47,9 +47,19 @@ async def server_status(request: Request) -> dict:
}
for w in watches
],
+ "recent_logs": _tail_log(getattr(state, "data_dir", "")),
}
+def _tail_log(data_dir: str, lines: int = 100) -> list[str]:
+ """Return the last *lines* lines of the server log file."""
+ log_path = os.path.join(os.path.expanduser(data_dir or "~/MinerU"), "mineru.log")
+ if not os.path.isfile(log_path):
+ return []
+ with open(log_path, encoding="utf-8", errors="replace") as fh:
+ return fh.readlines()[-lines:]
+
+
@router.post("/shutdown")
async def shutdown(request: Request) -> dict:
"""Gracefully shut down the server."""
@@ -72,6 +82,8 @@ def _build_parse_server_status() -> dict:
"local": {
"mode": health.local_mode,
"healthy": health.local_healthy,
+ "starting": health.local_starting,
+ "started_at": health.local_started_at or None,
"supported_tiers": health.local_supported_tiers,
},
"remote": {
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 917758a9..d3886d05 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -77,16 +77,24 @@ def create_app(cfg: Config | None = None) -> FastAPI:
health.local_mode = local_mode
if local_mode == "managed":
managed_tier = (await state.config_svc.get("parse_server.local.managed_tier")) or "standard"
+ tier_to_backend = {"standard": "pipeline", "pro": "vlm"}
+ backend = tier_to_backend.get(managed_tier, "pipeline")
try:
+ cmd = [sys.executable, "-m", "mineru.parser.api_server",
+ "--backend", backend, "--port", "15981"]
+ logging.info("Starting managed parse-server: %s", " ".join(cmd))
proc = subprocess.Popen(
- [sys.executable, "-m", "mineru.parser.api_server", "--backend", managed_tier, "--port", "15981"],
+ cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
+ logging.info("Managed parse-server started (PID %d, backend=%s)", proc.pid, backend)
state.parse_server_proc = proc
health.managed_proc = proc
- except Exception:
- pass
+ health.local_starting = True
+ health.local_started_at = time.time()
+ except Exception as exc:
+ logging.error("Failed to start managed parse-server: %s", exc)
# background tasks
state.watch = WatchLoop(state.db, state.config_svc, state.parse_svc)
@@ -121,10 +129,16 @@ def create_app(cfg: Config | None = None) -> FastAPI:
# stop managed parse-server
if state.parse_server_proc:
try:
+ pid = state.parse_server_proc.pid
+ logging.info("Stopping managed parse-server (PID %d)", pid)
state.parse_server_proc.terminate()
state.parse_server_proc.wait(timeout=10)
- except Exception:
- pass
+ logging.info("Managed parse-server stopped (PID %d)", pid)
+ except subprocess.TimeoutExpired:
+ logging.warning("Managed parse-server did not stop within 10s, killing")
+ state.parse_server_proc.kill()
+ except Exception as exc:
+ logging.error("Error stopping managed parse-server: %s", exc)
for comp in [
"watch",
@@ -165,6 +179,16 @@ def create_app(cfg: Config | None = None) -> FastAPI:
content=error_response(exc),
)
+ @app.exception_handler(Exception)
+ async def catch_all_handler(_request: Request, exc: Exception) -> JSONResponse:
+ import traceback
+
+ logging.error("Unhandled exception: %s\n%s", exc, traceback.format_exc())
+ return JSONResponse(
+ status_code=500,
+ content=error_response(MineruError("internal_error", str(exc))),
+ )
+
# ── routes ───────────────────────────────────────────────────
from .routes.parse import router as parse_router
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index d53e44be..314b713d 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -8,6 +8,7 @@ import time
from pathlib import Path
from mineru.constants import TIER_ORDER, ParseStatus, Tier
+from mineru.errors import MineruError
from ..core.db import DatabaseManager
from ..core.file_io import compute_sha256, extract_metadata, get_file_stat
@@ -19,11 +20,11 @@ def _now_ms() -> int:
return int(time.time() * 1000)
-class ParseFailure(Exception):
+class ParseFailure(MineruError):
"""Raised when a parse cannot be completed. Carries an error code for the parses row."""
def __init__(self, code: str, message: str) -> None:
- self.code = code
+ super().__init__(code, message)
self.message = message
@@ -288,85 +289,80 @@ class ParseService:
if file_row is None or file_row["sha256"] is None:
file_row = await self.ingest_file(path)
if file_row is None:
- return {
- "sha256": "",
- "tier": tier or "",
- "status": "error",
- "tip": "File could not be ingested.",
- }
+ return {"sha256": "", "tier": tier or "", "status": "error", "tip": "File could not be ingested."}
sha256 = file_row["sha256"]
doc = await self.db.fetchone("SELECT page_count FROM docs WHERE sha256=?", (sha256,))
page_count = doc["page_count"] if doc else 1
+ privacy = "remote" if remote else "local"
- requested_tier = tier or Tier.FLASH
-
- # Office documents: always flash, ignore requested tier
+ # ── resolve tier (before cache check) ──
+ requested_tier = tier or _resolve_default_tier(remote)
ext = file_row["ext"]
if ext in ("docx", "pptx", "xlsx", "doc", "xls", "ppt"):
requested_tier = Tier.FLASH
- # resolve privacy / remote_url
- privacy = "remote" if remote else "local"
-
- # expand pages
+ # ── expand pages ──
default_pages = "1~5,-5~-1" if page_count and page_count > 10 else f"1~{page_count}"
raw_pages = pages or default_pages
- pages_str = expand_pages(raw_pages, page_count or 1)
+ request_pages_str = expand_pages(raw_pages, page_count or 1)
+ needed = parse_range_set(request_pages_str)
- # check cache — (sha256, tier) regardless of privacy
+ # ── step 1: remove pages covered by valid done batches ──
if not force:
done_batches = await self.db.fetchall(
- "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done'",
+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done' ORDER BY done_at DESC",
(sha256, requested_tier),
)
- if done_batches:
- if pages_covered(pages_str, done_batches):
- return {
- "sha256": sha256,
- "tier": requested_tier,
- "pages": pages_str,
- "status": "done",
- "tip": "Cached. Use --force to re-parse.",
- }
- uncovered = pages_uncovered(pages_str, done_batches)
- if not uncovered:
- return {
- "sha256": sha256,
- "tier": requested_tier,
- "pages": pages_str,
- "status": "done",
- "tip": "Cached.",
- }
- pages_str = _pages_set_to_str(uncovered)
-
- # check if there's already a pending/parsing batch with overlapping pages
- active = await self.db.fetchone(
- "SELECT * FROM parses WHERE sha256=? AND tier=? AND status IN ('pending', 'parsing') "
- "ORDER BY created_at DESC LIMIT 1",
+ for batch in done_batches:
+ if not _json_file_exists_by_batch(sha256, requested_tier, batch):
+ continue # JSON gone → cache invalid
+ covered = parse_range_set(batch["pages"])
+ needed -= covered
+
+ if not needed:
+ return _done_response(sha256, requested_tier, request_pages_str)
+
+ # ── step 2: remove pages covered by pending/parsing batches ──
+ active_batches = await self.db.fetchall(
+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status IN ('pending', 'parsing')",
(sha256, requested_tier),
)
- if active:
- return {
- "sha256": sha256,
- "tier": requested_tier,
- "pages": pages_str,
- "status": active["status"],
- "tip": "Parse already in progress. Check status with: mineru info <path>",
- }
-
- # insert new batch
+ if active_batches:
+ active_covered: set[int] = set()
+ for batch in active_batches:
+ active_covered |= parse_range_set(batch["pages"])
+ needed -= active_covered
+
+ if not needed:
+ # all remaining pages covered by in-progress batches → bump priority
+ now = _now_ms()
+ for batch in active_batches:
+ if batch["priority"] < 1:
+ await self.db.execute(
+ "UPDATE parses SET priority=1, updated_at=? WHERE id=?",
+ (now, batch["id"]),
+ )
+ return {
+ "sha256": sha256,
+ "tier": requested_tier,
+ "pages": request_pages_str,
+ "status": ParseStatus.PENDING,
+ "tip": "Pages already queued. Priority bumped.",
+ }
+
+ # ── step 3: enqueue remaining uncovered pages ──
+ uncovered_str = _pages_set_to_str(needed)
now = _now_ms()
await self.db.execute(
"INSERT INTO parses (sha256, tier, pages, status, privacy, remote_url, priority, created_at, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)",
- (sha256, requested_tier, pages_str, ParseStatus.PENDING, privacy, remote_url, now, now),
+ (sha256, requested_tier, uncovered_str, ParseStatus.PENDING, privacy, remote_url, now, now),
)
-
return {
"sha256": sha256,
"tier": requested_tier,
- "pages": pages_str,
+ "pages": uncovered_str,
"status": ParseStatus.PENDING,
}
@@ -432,35 +428,30 @@ class ParseService:
await self._fail_task(task["id"], "parse_failed", str(exc)[:500])
return False
- # save per-batch markdown + JSON
- md_text = ""
- for result in results:
- md = result.markdown() if hasattr(result, "markdown") else ""
- md_text += md + "\n"
-
+ # save per-batch JSON (markdown is generated on read from /parse/content)
+ done_at_ms = _now_ms()
if results:
import json as _json
pages_key = _safe_filename(task["pages"])
- md_path = os.path.join(output_dir, f"{pages_key}.md")
- json_path = os.path.join(output_dir, f"{pages_key}.json")
+ json_path = os.path.join(output_dir, f"{pages_key}_{done_at_ms}.json")
os.makedirs(output_dir, exist_ok=True)
- try:
- with open(md_path, "w", encoding="utf-8") as f:
- f.write(md_text)
- except Exception:
- pass
new_pages: list[dict] = []
for r in results:
if hasattr(r, "to_dict"):
- new_pages.extend(r.to_dict().get("pdf_info", []))
- os.makedirs(output_dir, exist_ok=True)
+ new_pages.extend(r.to_dict().get("pages", []))
try:
with open(json_path, "w", encoding="utf-8") as f:
- _json.dump({"pdf_info": new_pages}, f, ensure_ascii=False, indent=2)
+ _json.dump({"pages": new_pages}, f, ensure_ascii=False, indent=2)
except Exception:
pass
+ # generate markdown for FTS (not persisted, only for search indexing)
+ md_text = ""
+ for result in results:
+ md = result.markdown(add_markers=False) if hasattr(result, "markdown") else ""
+ md_text += md + "\n"
+
# update fts_contents (tier-gated)
await self._maybe_update_fts(sha256, tier, md_text, file_row)
@@ -468,10 +459,9 @@ class ParseService:
await self._maybe_update_docs_meta(sha256, tier)
# mark done
- now = _now_ms()
await self.db.execute(
- "UPDATE parses SET status=?, done_at=?, locked_at=NULL, via=?, output_path=?, updated_at=? WHERE id=?",
- (ParseStatus.DONE, now, via, output_dir, now, task["id"]),
+ "UPDATE parses SET status=?, done_at=?, locked_at=NULL, via=?, updated_at=? WHERE id=?",
+ (ParseStatus.DONE, done_at_ms, via, done_at_ms, task["id"]),
)
return True
@@ -593,7 +583,13 @@ class ParseService:
(sha256, tier),
)
if done:
- return {"sha256": sha256, "tier": tier, "status": "done", "pages": "TBD"}
+ # still have active batches? → not fully done yet
+ active_count = await self.db.fetchone(
+ "SELECT COUNT(*) as cnt FROM parses WHERE sha256=? AND tier=? AND status IN ('pending', 'parsing')",
+ (sha256, tier),
+ )
+ if active_count and active_count["cnt"] == 0:
+ return {"sha256": sha256, "tier": tier, "status": "done", "pages": "TBD"}
active = await self.db.fetchone(
"SELECT * FROM parses WHERE sha256=? AND tier=? AND status IN ('pending', 'parsing') "
@@ -622,6 +618,17 @@ class ParseService:
return None
+ async def invalidate(self, sha256: str, tier: str | None = None) -> int:
+ """Mark done parses as superseded. Returns count of affected rows."""
+ now = _now_ms()
+ sql = "UPDATE parses SET status='superseded', updated_at=? WHERE sha256=? AND status='done'"
+ params = [now, sha256]
+ if tier:
+ sql += " AND tier=?"
+ params.append(tier)
+ cursor = await self.db.execute(sql, tuple(params))
+ return cursor.rowcount
+
# ── internal helpers ────────────────────────────────────────
async def _maybe_update_fts(self, sha256: str, tier: str, text: str, file_row: dict) -> None:
@@ -659,6 +666,28 @@ class ParseService:
# ── tier → backend mapping ─────────────────────────────────────────
+def _resolve_default_tier(remote: bool = False) -> str:
+ """Pick the best available tier from health check. ``pro`` > ``standard`` > ``flash``."""
+ from mineru.doclib.background.parse_server_health import get_health
+
+ health = get_health()
+ supported = health.remote_supported_tiers if remote else health.local_supported_tiers
+ for candidate in (Tier.PRO, Tier.STANDARD):
+ if candidate in supported:
+ return candidate
+ raise ParseFailure(
+ "no_engine", "No standard or pro engine available. Start a parse-server or use --tier flash for text-only preview."
+ )
+
+
+def _json_file_exists_by_batch(sha256: str, tier: str, batch: dict) -> bool:
+ """Check that the JSON result file for a parses batch row actually exists on disk."""
+ data_dir = os.path.expanduser("~/MinerU")
+ key = _safe_filename(batch["pages"], batch["done_at"])
+ json_path = os.path.join(data_dir, "parsed", sha256[:2], sha256, tier, f"{key}.json")
+ return os.path.isfile(json_path)
+
+
def _tier_to_backend(tier: str) -> str:
mapping = {
Tier.FLASH: "flash",
@@ -668,6 +697,16 @@ def _tier_to_backend(tier: str) -> str:
return mapping.get(tier, "pipeline")
+def _done_response(sha256: str, tier: str, pages: str) -> dict:
+ return {
+ "sha256": sha256,
+ "tier": tier,
+ "pages": pages,
+ "status": "done",
+ "tip": "Cached. Use --force to re-parse.",
+ }
+
+
def _local_parse_server_url(mode: str, health: object) -> str | None:
"""Resolve local parse-server URL from mode and health state."""
if mode == "managed":
@@ -677,6 +716,6 @@ def _local_parse_server_url(mode: str, health: object) -> str | None:
return None
-def _safe_filename(s: str) -> str:
- """Convert a pages range string to a safe filename — keep ~ and , as-is."""
- return s # pages string is already safe: "1~5,43~47"
+def _safe_filename(s: str, done_at: int = 0) -> str:
+ """Convert a pages range string + done_at to a filename."""
+ return f"{s}_{done_at}" if done_at else s