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
many features
jinzhenj7437d9efbe30
diff --git a/mineru/cli_next/commands/cleanup.py b/mineru/cli_next/commands/cleanup.pyindex 698b24bb..092d8aa0 100644--- a/mineru/cli_next/commands/cleanup.py+++ b/mineru/cli_next/commands/cleanup.py@@ -4,8 +4,9 @@ from __future__ import annotationsimport typer-from mineru.doclib.client import MineruClient-from mineru.cli_next.output import print_error, print_success, print_info+from ...doclib.client import DoclibClient+from ...doclib.types import CleanupDeletedRequest, CleanupOrphansRequest, CleanupTempRequest+from ..output import print_error, print_info, print_successdef cleanup_cmd(@@ -24,42 +25,42 @@ def cleanup_cmd(mineru cleanup --temp"""try:- client = MineruClient(timeout=30)+ client = DoclibClient(timeout=30)except Exception:print_error("Cannot connect to mineru server. Run 'mineru server start' first.")raise typer.Exit(1) from Noneif orphans:try:- data = client._post("/cleanup/orphans", json_data={"dry_run": dry_run})+ data = client.cleanup_orphan_docs(CleanupOrphansRequest(dry_run=dry_run))except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None- count = data.get("orphan_docs", 0)+ count = data.orphan_docsif dry_run:print_info(f"Would remove {count} orphan doc(s). Use --no-dry-run to proceed.")else:print_success(f"Removed {count} orphan doc(s).")elif deleted:try:- data = client._post("/cleanup/deleted", json_data={- "dry_run": dry_run, "older_than_days": older_than,- })+ data = client.cleanup_deleted_files(+ CleanupDeletedRequest(dry_run=dry_run, older_than_days=older_than)+ )except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None- count = data.get("deleted_files", 0)+ count = data.deleted_filesif dry_run:print_info(f"Would remove {count} deleted file record(s). Use --no-dry-run to proceed.")else:print_success(f"Removed {count} deleted file record(s).")elif temp:try:- data = client._post("/cleanup/temp", json_data={"older_than_days": older_than})+ data = client.cleanup_temp_files(CleanupTempRequest(older_than_days=older_than))except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None- count = data.get("temp_files_removed", 0)+ count = data.temp_files_removedprint_success(f"Removed {count} temp file(s).")else:print_info("Specify --orphans, --deleted, or --temp.")diff --git a/mineru/cli_next/commands/config.py b/mineru/cli_next/commands/config.pyindex ded19a42..14824f4b 100644--- a/mineru/cli_next/commands/config.py+++ b/mineru/cli_next/commands/config.py@@ -4,8 +4,10 @@ from __future__ import annotationsimport typer-from mineru.doclib.client import MineruClient-from mineru.cli_next.output import print_error, print_success, print_info, print_json+from ...doclib.client import DoclibClient+from ...doclib.types import ConfigResponse, ConfigSetRequest, ExcludeRuleRequest, ParsingRuleRequest, WatchRequest+from ...types import Tier+from ..output import print_error, print_success, print_info, print_jsonapp = typer.Typer(help="Configuration management", no_args_is_help=True)@@ -26,8 +28,8 @@ app.add_typer(parsing_rules_app, name="parsing-rules")def show(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:"""Show all configuration."""try:- client = MineruClient(timeout=10)- data = client.config_show()+ client = DoclibClient(timeout=10)+ data = client.get_config()if json_mode:print_json(data)else:@@ -48,9 +50,9 @@ def watch_add() -> None:"""Add a directory to watch."""try:- client = MineruClient(timeout=10)- data = client.config_watch_add(path, removable=removable, label=label)- print_success(f"Watch added: {data.get('path')} (id={data.get('id')})")+ client = DoclibClient(timeout=10)+ data = client.add_watch(WatchRequest(path=path, removable=removable, label=label))+ print_success(f"Watch added: {data.path} (id={data.id})")except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None@@ -60,19 +62,19 @@ def watch_add(def watch_list(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:"""List all watched directories."""try:- client = MineruClient(timeout=10)- data = client.config_watch_list()+ client = DoclibClient(timeout=10)+ data = client.list_watches()if json_mode:print_json(data)else:- watches = data.get("watches", [])+ watches = data.watchesif not watches:print_info("No watches configured.")for w in watches:- status = w.get("watch_status", "?")+ status = w.watch_statusicon = "✓" if status == "active" else "✗"- extra = " [removable]" if w.get("removable") else ""- print(f" {icon} {w['path']}{extra} [{status}]")+ extra = " [removable]" if w.removable else ""+ print(f" {icon} {w.path}{extra} [{status}]")except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None@@ -82,8 +84,8 @@ def watch_list(json_mode: bool = typer.Option(False, "--json", help="JSON outputdef watch_rm(path: str = typer.Argument(..., help="Watch directory path to remove")) -> None:"""Remove a watched directory."""try:- client = MineruClient(timeout=10)- client.config_watch_rm(path)+ client = DoclibClient(timeout=10)+ client.remove_watch(path)print_success(f"Watch removed: {path}")except Exception as exc:print_error(str(exc))@@ -100,9 +102,9 @@ def exclude_add() -> None:"""Add an exclusion pattern."""try:- client = MineruClient(timeout=10)- data = client.config_exclude_add(pattern, priority=priority)- print_success(f"Exclude rule added: id={data.get('id')}")+ client = DoclibClient(timeout=10)+ data = client.add_exclude_rule(ExcludeRuleRequest(pattern=pattern, priority=priority))+ print_success(f"Exclude rule added: id={data.id}")except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None@@ -114,16 +116,16 @@ def exclude_list() -> None:"""List all exclusion rules."""try:- client = MineruClient(timeout=10)- data = client.config_exclude_list()+ client = DoclibClient(timeout=10)+ data = client.list_exclude_rules()if json_mode:print_json(data)else:- rules = data.get("rules", [])+ rules = data.rulesif not rules:print_info("No exclude rules configured.")for r in rules:- print(f" [{r['id']}] {r['pattern']} priority={r.get('priority', 0)}")+ print(f" [{r.id}] {r.pattern} priority={r.priority}")except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None@@ -133,8 +135,8 @@ def exclude_list(def exclude_rm(rule_id: int = typer.Argument(..., help="Rule ID to remove")) -> None:"""Remove an exclusion rule."""try:- client = MineruClient(timeout=10)- client.config_exclude_rm(rule_id)+ client = DoclibClient(timeout=10)+ client.remove_exclude_rule(rule_id)print_success(f"Exclude rule {rule_id} removed.")except Exception as exc:print_error(str(exc))@@ -147,18 +149,18 @@ def exclude_rm(rule_id: int = typer.Argument(..., help="Rule ID to remove")) ->@parsing_rules_app.command("add")def parsing_rules_add(pattern: str = typer.Argument(..., help="Glob pattern to match"),- tier: str = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro"),+ tier: Tier | None = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro"),pages: str = typer.Option(None, "--pages", help="Page range, e.g. 'all' or '1~10'"),remote: bool = typer.Option(False, "--remote", help="Allow remote parsing"),name: str = typer.Option(None, "--name", help="Rule name"),) -> None:"""Add a parsing rule."""try:- client = MineruClient(timeout=10)- data = client.config_parsing_rules_add(- pattern, tier=tier, pages=pages, remote=remote, name=name,+ client = DoclibClient(timeout=10)+ data = client.add_parsing_rule(+ ParsingRuleRequest(pattern=pattern, tier=tier, pages=pages, remote=remote, name=name))- print_success(f"Parsing rule added: id={data.get('id')}")+ print_success(f"Parsing rule added: id={data.id}")except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None@@ -170,23 +172,23 @@ def parsing_rules_list() -> None:"""List all parsing rules."""try:- client = MineruClient(timeout=10)- data = client.config_parsing_rules_list()+ client = DoclibClient(timeout=10)+ data = client.list_parsing_rules()if json_mode:print_json(data)else:- rules = data.get("rules", [])+ rules = data.rulesif not rules:print_info("No parsing rules configured.")for r in rules:flags = []- if r.get("tier"):- flags.append(f"tier={r['tier']}")- if r.get("pages"):- flags.append(f"pages={r['pages']}")- if r.get("remote"):+ if r.tier:+ flags.append(f"tier={r.tier}")+ if r.pages:+ flags.append(f"pages={r.pages}")+ if r.remote:flags.append("remote")- print(f" [{r['id']}] {r['pattern']} {', '.join(flags)}")+ print(f" [{r.id}] {r.pattern} {', '.join(flags)}")except Exception as exc:print_error(str(exc))raise typer.Exit(1) from None@@ -196,8 +198,8 @@ def parsing_rules_list(def parsing_rules_rm(rule_id: int = typer.Argument(..., help="Rule ID to remove")) -> None:"""Remove a parsing rule."""try:- client = MineruClient(timeout=10)- client.config_parsing_rules_rm(rule_id)+ client = DoclibClient(timeout=10)+ client.remove_parsing_rule(rule_id)print_success(f"Parsing rule {rule_id} removed.")except Exception as exc:print_error(str(exc))@@ -221,8 +223,8 @@ def parse_server_local_mode(print_error(f"Invalid mode '{mode}'. Must be one of: {', '.join(sorted(valid))}")raise typer.Exit(1)try:- client = MineruClient(timeout=10)- client._post("/config", {"key": "parse_server.local.mode", "value": mode})+ client = DoclibClient(timeout=10)+ client.set_config(ConfigSetRequest(key="parse_server.local.mode", value=mode))print_success(f"Local parse-server mode set to '{mode}'.")except Exception as exc:print_error(str(exc))@@ -231,15 +233,15 @@ def parse_server_local_mode(@parse_server_app.command("local.managed-tier")def parse_server_managed_tier(- tier: str = typer.Argument(..., help="Tier: standard, pro"),+ tier: Tier = typer.Argument(..., help="Tier: standard, pro"),) -> None:"""Set tier for managed local parse-server."""if tier not in ("standard", "pro"):print_error("Tier must be 'standard' or 'pro'.")raise typer.Exit(1)try:- client = MineruClient(timeout=10)- client._post("/config", {"key": "parse_server.local.managed_tier", "value": tier})+ client = DoclibClient(timeout=10)+ client.set_config(ConfigSetRequest(key="parse_server.local.managed_tier", value=tier))print_success(f"Managed tier set to '{tier}'.")except Exception as exc:print_error(str(exc))@@ -252,8 +254,8 @@ def parse_server_self_hosted_url() -> None:"""Set URL for self-hosted parse-server."""try:- client = MineruClient(timeout=10)- client._post("/config", {"key": "parse_server.local.self_hosted_url", "value": url})+ client = DoclibClient(timeout=10)+ client.set_config(ConfigSetRequest(key="parse_server.local.self_hosted_url", value=url))print_success(f"Self-hosted URL set to '{url}'.")except Exception as exc:print_error(str(exc))@@ -266,8 +268,8 @@ def parse_server_self_hosted_api_key() -> None:"""Set API key for self-hosted parse-server."""try:- client = MineruClient(timeout=10)- client._post("/config", {"key": "parse_server.local.self_hosted_api_key", "value": api_key})+ client = DoclibClient(timeout=10)+ client.set_config(ConfigSetRequest(key="parse_server.local.self_hosted_api_key", value=api_key))print_success("Self-hosted API key set.")except Exception as exc:print_error(str(exc))@@ -280,8 +282,8 @@ def parse_server_remote_url() -> None:"""Set remote parse-server URL."""try:- client = MineruClient(timeout=10)- client._post("/config", {"key": "parse_server.remote.url", "value": url})+ client = DoclibClient(timeout=10)+ client.set_config(ConfigSetRequest(key="parse_server.remote.url", value=url))print_success(f"Remote URL set to '{url}'.")except Exception as exc:print_error(str(exc))@@ -294,8 +296,8 @@ def parse_server_remote_api_key() -> None:"""Set API key for remote parse-server."""try:- client = MineruClient(timeout=10)- client._post("/config", {"key": "parse_server.remote.api_key", "value": api_key})+ client = DoclibClient(timeout=10)+ client.set_config(ConfigSetRequest(key="parse_server.remote.api_key", value=api_key))print_success("Remote API key set.")except Exception as exc:print_error(str(exc))@@ -305,19 +307,9 @@ def parse_server_remote_api_key(# ── helpers ──────────────────────────────────────────────────────-def _print_config(data: dict) -> None:- cfg = data.get("config", {})- watches = data.get("watches", [])- rules = data.get("rules", [])+def _print_config(data: ConfigResponse) -> None:+ cfg = data.configprint("\n[Global Config]")for k, v in cfg.items():print(f" {k} = {v}")-- print(f"\n[Watches] ({len(watches)})")- for w in watches:- print(f" {w['path']} [{w.get('watch_status','?')}]")-- print(f"\n[Rules] ({len(rules)})")- for r in rules:- print(f" [{r['rule_type']}] {r['pattern']}")diff --git a/mineru/cli_next/commands/invalidate.py b/mineru/cli_next/commands/invalidate.pyindex 6e02ba2f..475dd1e7 100644--- a/mineru/cli_next/commands/invalidate.py+++ b/mineru/cli_next/commands/invalidate.py@@ -6,13 +6,15 @@ from pathlib import Pathimport typer-from mineru.doclib.client import MineruClient-from mineru.cli_next.output import print_error, print_success+from ...doclib.client import DoclibClient+from ...doclib.types import InvalidateRequest+from ...types import Tier+from ..output import print_error, print_successdef 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)"),+ 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())@@ -22,19 +24,19 @@ def invalidate_cmd(raise typer.Exit(1)try:- client = MineruClient(timeout=10)+ client = DoclibClient(timeout=10)except Exception:print_error("Cannot connect to mineru server. Run 'mineru server start' first.")raise typer.Exit(1) from Nonetry:- result = client.invalidate(file_path, tier=tier)+ result = client.invalidate(InvalidateRequest(path=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]+ count = result.invalidated_count+ sha256 = result.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.")diff --git a/mineru/cli_next/commands/search.py b/mineru/cli_next/commands/search.pyindex 5e85e621..7ef68a7d 100644--- a/mineru/cli_next/commands/search.py+++ b/mineru/cli_next/commands/search.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport typer-from mineru.doclib.client import MineruClient-from mineru.cli_next.output import format_search_results, format_info, print_error+from ...doclib.client import DoclibClient+from ..output import format_info, format_search_results, print_errordef search_cmd(@@ -17,7 +17,7 @@ def search_cmd() -> None:"""Search parsed document content."""try:- client = MineruClient(timeout=10)+ client = DoclibClient(timeout=10)result = client.search(query, file_type=file_type, limit=limit, offset=offset)format_search_results(result, json_mode=json_mode)except Exception as exc:@@ -32,7 +32,7 @@ def find_cmd() -> None:"""Search filenames only (not document content)."""try:- client = MineruClient(timeout=10)+ client = DoclibClient(timeout=10)result = client.find(query, limit=limit)format_search_results(result, json_mode=json_mode)except Exception as exc:@@ -49,8 +49,8 @@ def info_cmd(file_path = str(Path(path).resolve())try:- client = MineruClient(timeout=10)- result = client.info(file_path)+ client = DoclibClient(timeout=10)+ result = client.get_file_info(file_path)format_info(result, json_mode=json_mode)except Exception as exc:print_error(str(exc))diff --git a/mineru/cli_next/commands/server.py b/mineru/cli_next/commands/server.pyindex 157f1ddb..80c02f6d 100644--- a/mineru/cli_next/commands/server.py+++ b/mineru/cli_next/commands/server.py@@ -9,28 +9,35 @@ import timeimport typer-from mineru.constants import SOCKET_PATH-from mineru.cli_next.output import format_server_status, print_error, print_success, print_info+from ...config import config+from ..output import format_server_status, print_error, print_info, print_successapp = typer.Typer(help="Server lifecycle management", no_args_is_help=True)+def _socket_path() -> str:+ return config.doclib.uds.path++def _server_running() -> bool:- if not os.path.exists(SOCKET_PATH):+ socket_path = _socket_path()+ if not os.path.exists(socket_path):return Falsetry:- from mineru.doclib.client import MineruClient- c = MineruClient(timeout=3)- c.server_status()+ from ...doclib.client import DoclibClient++ c = DoclibClient(timeout=3)+ c.get_server_status()return Trueexcept Exception:return Falsedef _wait_for_sock(timeout: float = 15.0) -> bool:+ socket_path = _socket_path()deadline = time.time() + timeoutwhile time.time() < deadline:- if os.path.exists(SOCKET_PATH):+ if os.path.exists(socket_path):time.sleep(0.3)if _server_running():return True@@ -45,14 +52,15 @@ def start() -> None:print_info("Server is already running.")return+ socket_path = _socket_path()# Clean stale sockettry:- os.unlink(SOCKET_PATH)+ os.unlink(socket_path)except OSError:passproc = subprocess.Popen(- [sys.executable, "-m", "mineru.doclib.server"],+ [sys.executable, "-m", "mineru.doclib.app"],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,)@@ -62,7 +70,7 @@ def start() -> None:print_error("Server failed to start within 15 seconds.")raise typer.Exit(1)- print_success(f"Server started (PID {proc.pid}). Socket: {SOCKET_PATH}")+ print_success(f"Server started (PID {proc.pid}). Socket: {socket_path}")@app.command()@@ -73,15 +81,16 @@ def stop() -> None:returntry:- from mineru.doclib.client import MineruClient- c = MineruClient(timeout=5)- c.shutdown()+ from ...doclib.client import DoclibClient++ c = DoclibClient(timeout=5)+ c.shutdown_server()except Exception:passtime.sleep(0.5)try:- os.unlink(SOCKET_PATH)+ os.unlink(_socket_path())except OSError:pass@@ -105,9 +114,10 @@ def status() -> None:returntry:- from mineru.doclib.client import MineruClient- c = MineruClient(timeout=5)- data = c.server_status()+ from ...doclib.client import DoclibClient++ c = DoclibClient(timeout=5)+ data = c.get_server_status()format_server_status(data)except Exception as exc:print_error(str(exc))diff --git a/mineru/cli_next/output.py b/mineru/cli_next/output.pyindex 1096ad72..fc1e6da2 100644--- a/mineru/cli_next/output.py+++ b/mineru/cli_next/output.py@@ -4,6 +4,10 @@ from __future__ import annotationsimport jsonimport sys+from typing import Any++from pydantic import BaseModel+from pydantic_core import to_jsontry:from rich.console import Console@@ -35,36 +39,44 @@ def print_info(msg: str) -> None:print(msg)-def print_json(data: dict) -> None:+def print_json(data: Any) -> None:+ if isinstance(data, BaseModel):+ print(to_json(data, indent=2).decode("utf-8"))+ returnprint(json.dumps(data, ensure_ascii=False, indent=2))+def _get(data: Any, key: str, default: Any = None) -> Any:+ if isinstance(data, dict):+ return data.get(key, default)+ return getattr(data, key, default)++# ── parse ──────────────────────────────────────────────────────-def format_parse_result(data: dict, json_mode: bool = False) -> None:+def format_parse_result(data: Any, json_mode: bool = False) -> None:if json_mode:print_json(data)return- status = data.get("status", "?")- tip = data.get("tip", "")+ status = _get(data, "status", "?")+ tip = _get(data, "tip", "")if status == "pending" or status == "parsing":print_info(f"Parse {status}... {tip}")elif status == "failed":- err = data.get("error", {})- print_error(f"Parse failed: {err.get('code','?')} — {err.get('message','')}")+ print_error(f"Parse failed: {_get(data, 'error_code', '?')} — {_get(data, 'error_msg', '')}")else:- print_success(f"Parse complete (tier={data.get('tier','?')}) {tip}")+ print_success(f"Parse complete (tier={_get(data, 'tier', '?')}) {tip}")# ── search ─────────────────────────────────────────────────────-def format_search_results(data: dict, json_mode: bool = False) -> None:- results = data.get("results", [])- total = data.get("total", 0)+def format_search_results(data: Any, json_mode: bool = False) -> None:+ results = _get(data, "results", [])+ total = _get(data, "total", 0)if json_mode:print_json(data)@@ -82,28 +94,28 @@ def format_search_results(data: dict, json_mode: bool = False) -> None:for r in results:table.add_row(- r.get("title") or r.get("filename", "?"),- r.get("tier", ""),- (r.get("snippet") or "")[:80],- ", ".join(r.get("paths", [])[:3]),+ _get(r, "title") or _get(r, "filename", "?"),+ _get(r, "tier", ""),+ (_get(r, "snippet", "") or "")[:80],+ ", ".join(_get(r, "paths", [])[:3]),)if console:console.print(table)else:for r in results:- print(f"{r.get('title')} [{r.get('tier')}] — {', '.join(r.get('paths', []))}")+ print(f"{_get(r, 'title')} [{_get(r, 'tier')}] — {', '.join(_get(r, 'paths', []))}")# ── server status ──────────────────────────────────────────────-def format_server_status(data: dict, json_mode: bool = False) -> None:+def format_server_status(data: Any, json_mode: bool = False) -> None:if json_mode:print_json(data)return- if not data.get("running"):+ if not _get(data, "running"):print_info("Server is not running.")return@@ -111,80 +123,82 @@ def format_server_status(data: dict, json_mode: bool = False) -> None:table = Table(title="MinerU Server")table.add_column("Metric", style="cyan")table.add_column("Value", style="green")- table.add_row("PID", str(data.get("pid", "?")))- table.add_row("Uptime", f"{data.get('uptime_seconds', 0):.0f}s")- table.add_row("Socket", data.get("socket_path", ""))- table.add_row("Data dir", data.get("data_dir", ""))- table.add_row("Files tracked", str(data.get("files_total", 0)))- table.add_row("Docs indexed", str(data.get("docs_total", 0)))- table.add_row("Parse queue", str(data.get("parse_queue_length", 0)))- table.add_row("Ingest queue", str(data.get("ingest_queue_length", 0)))- table.add_row("Watches", str(data.get("watch_count", 0)))+ table.add_row("PID", str(_get(data, "pid", "?")))+ table.add_row("Uptime", f"{_get(data, 'uptime_seconds', 0):.0f}s")+ table.add_row("Socket", _get(data, "socket_path", ""))+ table.add_row("Data dir", _get(data, "data_dir", ""))+ table.add_row("Files tracked", str(_get(data, "files_total", 0)))+ table.add_row("Docs indexed", str(_get(data, "docs_total", 0)))+ table.add_row("Parse queue", str(_get(data, "parse_queue_length", 0)))+ table.add_row("Ingest queue", str(_get(data, "ingest_queue_length", 0)))+ table.add_row("Watches", str(_get(data, "watch_count", 0)))console.print(table)# parse-server status- ps_data = data.get("parse_server")+ ps_data = _get(data, "parse_server")if ps_data:ps_table = Table(title="Parse Server")ps_table.add_column("Target", style="cyan")ps_table.add_column("Healthy", style="green")ps_table.add_column("Tiers", style="green")for label, key in [("Local", "local"), ("Remote", "remote")]:- ps = ps_data.get(key, {})- if ps.get("starting"):+ ps = _get(ps_data, key, {})+ if _get(ps, "starting"):healthy_str = "starting"- elif ps.get("healthy"):+ elif _get(ps, "healthy"):healthy_str = "yes"else:healthy_str = "no"- tiers_str = ", ".join(ps.get("supported_tiers", [])) or "-"- mode = ps.get("mode", "")+ tiers_str = ", ".join(_get(ps, "supported_tiers", [])) or "-"+ mode = _get(ps, "mode", "")label_str = f"{label} ({mode})" if mode else labelps_table.add_row(label_str, healthy_str, tiers_str)console.print(ps_table)# recent logs- logs = data.get("recent_logs", [])+ logs = _get(data, "recent_logs", [])if logs:log_text = "".join(logs) # last 100 lines from serverpanel = 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")+ print(f"Server running (PID {_get(data, 'pid')}), {_get(data, 'files_total')} files")# ── info ───────────────────────────────────────────────────────-def format_info(data: dict, json_mode: bool = False) -> None:+def format_info(data: Any, json_mode: bool = False) -> None:if json_mode:print_json(data)return- if not data.get("found"):+ file_data = _get(data, "file")+ if not file_data:print_info("File not found in database.")return+ doc_data = _get(data, "doc")if console:- table = Table(title=f"File Info: {data.get('filename','?')}")+ table = Table(title=f"File Info: {_get(file_data, 'filename', '?')}")table.add_column("Field", style="cyan")table.add_column("Value", style="green")- table.add_row("Path", data.get("path", "?"))- table.add_row("Type", data.get("ext", "?"))- table.add_row("Size", _format_bytes(data.get("size_bytes")))- table.add_row("SHA-256", (data.get("sha256") or "")[:16] + "...")- table.add_row("Page count", str(data.get("page_count", "?")))- table.add_row("Title", data.get("title") or "—")- table.add_row("Author", data.get("author") or "—")-- tiers = data.get("tiers", [])+ table.add_row("Path", _get(file_data, "path", "?"))+ table.add_row("Type", _get(file_data, "ext", "?"))+ table.add_row("Size", _format_bytes(_get(file_data, "size_bytes")))+ table.add_row("SHA-256", (_get(file_data, "sha256") or "")[:16] + "...")+ table.add_row("Page count", str(_get(doc_data, "page_count", "?") if doc_data else "?"))+ table.add_row("Title", (_get(doc_data, "title") if doc_data else None) or "—")+ table.add_row("Author", (_get(doc_data, "author") if doc_data else None) or "—")++ tiers = _get(data, "parsed_tiers", [])if tiers:- tier_str = ", ".join(f"{t['tier']}={t['status']}" for t in tiers)+ tier_str = ", ".join(f"{_get(t, 'tier')}={_get(t, 'status')}" for t in tiers)table.add_row("Tiers", tier_str)console.print(table)else:- print(f"{data.get('filename')} — {data.get('title') or 'No title'}")+ print(f"{_get(file_data, 'filename')} — {(_get(doc_data, 'title') if doc_data else None) or 'No title'}")# ── helpers ────────────────────────────────────────────────────diff --git a/mineru/config.py b/mineru/config.pynew file mode 100644index 00000000..f54b3c78--- /dev/null+++ b/mineru/config.py@@ -0,0 +1,277 @@+"""MinerU startup configuration."""++from __future__ import annotations++import copy+import logging+import os+import platform+import re+import socket+import tempfile+from typing import Any++import yaml+from pydantic import BaseModel, Field+from pydantic_core import to_jsonable_python++_logger = logging.getLogger(__name__)++CONFIG_ENV = "MINERU_CONFIG"+ENV_PREFIX = "MINERU_"+DEFAULT_CONFIG_FILENAME = "mineru.yaml"++_INTERPOLATION_RE = re.compile(r"\$\{(\w+)(?::-([^${}]*))?\}")+++def _uds_available() -> bool:+ try:+ socket.socket(socket.AF_UNIX, socket.SOCK_STREAM).close()+ return True+ except Exception:+ return False+++def _default_uds_path() -> str:+ system = platform.system().lower()+ if system not in ("windows", "darwin", "linux"):+ raise RuntimeError(f"System [{system}] is not supported.")+ if not _uds_available():+ raise RuntimeError("Unix domain socket is not available.")+ temp_dir = tempfile.gettempdir() if system == "windows" else "/tmp"+ return os.path.join(temp_dir, "mineru.sock")+++def _default_data_path() -> str:+ return os.path.join(os.path.expanduser("~"), "MinerU")+++def _default_config_path() -> str:+ return os.path.join(_default_data_path(), DEFAULT_CONFIG_FILENAME)+++def _default_log_path() -> str:+ return os.path.join(_default_data_path(), "mineru.log")+++def _default_db_path() -> str:+ return os.path.join(_default_data_path(), "mineru.db")+++def _strip_quotes(value: str) -> str:+ value = value.strip()+ if len(value) >= 2 and value[0] in ('"', "'") and value[-1] == value[0]:+ return value[1:-1]+ return value+++def _interpolation_replace(match: re.Match[str]) -> str:+ var_name, raw_default = match.group(1), match.group(2)+ value = os.environ.get(var_name)+ if value is not None:+ return value+ if raw_default is not None:+ return _strip_quotes(raw_default)+ raise ValueError(+ f"Environment variable {var_name!r} is referenced in MinerU config but is not set and has no default value."+ )+++def _substitute(value: str, max_depth: int = 20) -> str:+ for _ in range(max_depth):+ substituted = _INTERPOLATION_RE.sub(_interpolation_replace, value)+ if substituted == value:+ return value+ value = substituted+ raise ValueError(f"MinerU config interpolation did not converge after {max_depth} passes.")+++def interpolate_env(value: Any) -> Any:+ """Recursively substitute ${VAR} and ${VAR:-default} placeholders."""+ if isinstance(value, str):+ return _substitute(value)+ if isinstance(value, dict):+ return {key: interpolate_env(item) for key, item in value.items()}+ if isinstance(value, list):+ return [interpolate_env(item) for item in value]+ return value+++def load_config(config_file: str) -> dict[str, Any]:+ with open(config_file, encoding="utf-8") as file:+ raw = yaml.safe_load(file)+ if isinstance(raw, dict):+ return interpolate_env(raw)+ _logger.warning("MinerU config file [%s] is empty or invalid.", config_file)+ return {}+++def _read_config() -> dict[str, Any]:+ config_file = os.getenv(CONFIG_ENV)+ if config_file and not os.path.isfile(config_file):+ raise FileNotFoundError(f"MinerU config file [{config_file}] does not exist.")++ default_config_file = _default_config_path()+ if not config_file and os.path.isfile(default_config_file):+ config_file = default_config_file++ if not config_file:+ _logger.debug(+ "MinerU config file not found. Default path is %s. Use %s to specify a custom path.",+ default_config_file,+ CONFIG_ENV,+ )+ return {}++ return load_config(config_file)+++def get_env(key: str, default: str | None = None) -> str:+ value = os.getenv(key)+ if value not in (None, ""):+ return value+ if default is not None:+ return default+ raise ValueError(f"Environment variable {key} is not set.")+++def _collect_path(remaining: str, model_class: type[BaseModel]) -> list[str] | None:+ """Greedily match an UPPER_CASE env suffix to a pydantic field path."""+ remaining_lower = remaining.lower()+ fields = sorted(model_class.model_fields.keys(), key=len, reverse=True)+ for field_name in fields:+ if remaining_lower == field_name:+ return [field_name]+ if remaining_lower.startswith(field_name + "_"):+ annotation = model_class.model_fields[field_name].annotation+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):+ sub_remaining = remaining[len(field_name) + 1 :]+ sub_path = _collect_path(sub_remaining, annotation)+ if sub_path is not None:+ return [field_name, *sub_path]+ return None+++def _deep_merge(base: dict[str, Any], overrides: dict[str, Any]) -> dict[str, Any]:+ result = copy.deepcopy(base)+ for key, value in overrides.items():+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):+ result[key] = _deep_merge(result[key], value)+ else:+ result[key] = value+ return result+++def apply_env_overrides(cfg: "Config", prefix: str = ENV_PREFIX) -> "Config":+ """Return a new Config with matching environment variables merged in.++ Environment variable names use the prefix plus a greedy field path joined by+ underscores. Values remain strings here and are converted by Pydantic when+ rebuilding Config.++ Examples:+ MINERU_DOCLIB_HTTP_PORT=15981 -> config.doclib.http.port+ MINERU_DOCLIB_SQLITE_MMAP_SIZE=0 -> config.doclib.sqlite.mmap_size+ """+ prefix_upper = prefix.upper()+ overrides: dict[str, Any] = {}++ for key, value in os.environ.items():+ if not key.startswith(prefix_upper):+ continue+ remaining = key[len(prefix_upper) :]+ if not remaining or remaining == "CONFIG":+ continue+ path = _collect_path(remaining, Config)+ if path is None:+ continue++ node = overrides+ for part in path[:-1]:+ node = node.setdefault(part, {})+ node[path[-1]] = value++ if not overrides:+ return cfg++ merged = _deep_merge(to_jsonable_python(cfg), overrides)+ return Config(**merged)+++class UDSConfig(BaseModel):+ path: str = Field(default_factory=_default_uds_path)+ permission: int = 0o600+++class HTTPConfig(BaseModel):+ enabled: bool = False+ host: str = "127.0.0.1"+ port: int = 15980+ strict_port: bool = False+ backlog: int = 128+ timeout: int = 600+++class LogConfig(BaseModel):+ path: str = Field(default_factory=_default_log_path)+ level: str = "info"+++class SQLiteConfig(BaseModel):+ path: str = Field(default_factory=_default_db_path)+ mmap_size: int = 268435456+ cache_size: int = -20000+ wal_autocheckpoint: int = 1000+ journal_size_limit: int = 33_554_432+ temp_store: str = "memory"+ synchronous: str = "NORMAL"+++class DoclibConfig(BaseModel):+ """Doclib startup configuration.++ Only configuration needed before the doclib server starts belongs here.+ Runtime configuration that can be read from SQLite stays in the config+ service.+ """++ uds: UDSConfig = Field(default_factory=UDSConfig)+ http: HTTPConfig = Field(default_factory=HTTPConfig)+ log: LogConfig = Field(default_factory=LogConfig)+ sqlite: SQLiteConfig = Field(default_factory=SQLiteConfig)+ data_dir: str = Field(default_factory=_default_data_path)+ ingest_workers: int = 2+ parse_workers: int = 2+ compaction_interval_sec: int = 3600+++class Config(BaseModel):+ """Top-level MinerU startup configuration."""++ doclib: DoclibConfig = Field(default_factory=DoclibConfig)+++config = apply_env_overrides(Config(**_read_config()))+++def PatchedConfig(**kwargs: Any) -> Config:+ merged = _deep_merge(to_jsonable_python(config), kwargs)+ return Config(**merged)+++__all__ = [+ "CONFIG_ENV",+ "ENV_PREFIX",+ "Config",+ "DoclibConfig",+ "HTTPConfig",+ "LogConfig",+ "PatchedConfig",+ "SQLiteConfig",+ "UDSConfig",+ "apply_env_overrides",+ "config",+ "get_env",+ "interpolate_env",+ "load_config",+]diff --git a/mineru/constants.py b/mineru/constants.pydeleted file mode 100644index 92a0fb27..00000000--- a/mineru/constants.py+++ /dev/null@@ -1,75 +0,0 @@-"""Shared enums, file type whitelists, and constants."""--from __future__ import annotations--from enum import StrEnum--# ── paths ──────────────────────────────────────────────────────────--SOCKET_PATH = "/tmp/mineru.sock"-DATA_DIR = "~/MinerU"--# ── file types ─────────────────────────────────────────────────────--ALLOWED_EXTENSIONS: set[str] = {- "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "csv", "rtf", "odt", "ods",- "epub", "mobi",- "pages", "key", "numbers",- "txt", "md", "markdown", "rst", "tex",- "html", "htm",- "eml", "mbox",-}--DEFAULT_EXCLUDE_PATTERNS: list[str] = [- "*/Library/*",- "*/.git/*",- "*/node_modules/*",- "*/vendor/*",- "*/go/pkg/*",- "*/__pycache__/*",- "*/.venv/*",- "*/miniconda3/*",- "*/.nvm/*",- "*/.docker/*",- "*/target/*",- "*/dist/*",- "*/build/*",-]--# ── enums ──────────────────────────────────────────────────────────---class Tier(StrEnum):- FLASH = "flash"- STANDARD = "standard"- PRO = "pro"---TIER_ORDER: dict[str, int] = {- Tier.FLASH: 0,- Tier.STANDARD: 1,- Tier.PRO: 2,-}---class ScanStatus(StrEnum):- ACTIVE = "active"- DELETED = "deleted"- UNREACHABLE = "unreachable"---class ParseStatus(StrEnum):- PENDING = "pending"- PARSING = "parsing"- DONE = "done"- FAILED = "failed"---class RuleType(StrEnum):- EXCLUDE = "exclude"- PARSING_RULE = "parsing_rule"---class WatchStatus(StrEnum):- ACTIVE = "active"- UNREACHABLE = "unreachable"diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pynew file mode 100644index 00000000..dbd8c6d7--- /dev/null+++ b/mineru/doclib/app.py@@ -0,0 +1,262 @@+"""New doclib app factory and process entrypoint using the interface server."""++from __future__ import annotations++import asyncio+import errno+import logging+import os+import socket+import subprocess+import sys+import time+from collections.abc import Callable+from logging.handlers import RotatingFileHandler+from typing import Any++import uvicorn+from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse++from ..errors import MineruError, error_response+from ..config import Config, LogConfig, config+from .server import DoclibServer+from .types import PARSE_STATUS_FAILED, PARSE_STATUS_PARSING+++def create_app(cfg: Config | None = None) -> FastAPI:+ """Create the new interface-backed FastAPI app."""+ if cfg is None:+ cfg = config+ state = AppState()+ app = DoclibServer(state).app+ app.title = "MinerU DocLib"+ app.version = "1.0.0"++ @app.on_event("startup")+ async def startup() -> None:+ from .background.compaction import Compaction+ from .background.device_monitor import DeviceMonitor+ from .background.ingest import IngestWorkerPool+ from .background.parse_server_health import ParseServerHealthCheck, api_server_args_for_tier, get_health+ from .background.parse_worker import ParseWorkerPool+ from .background.watch import WatchLoop+ from .core.db import DatabaseManager+ from .core.fts import FTSManager+ from .services.cleanup_svc import CleanupService+ from .services.config_svc import ConfigService+ from .services.parse_svc import ParseService+ from .services.search_svc import SearchService++ data_dir = os.path.expanduser(cfg.doclib.data_dir)+ os.makedirs(data_dir, exist_ok=True)++ _setup_logging(cfg.doclib.log)++ db_path = os.path.expanduser(cfg.doclib.sqlite.path)+ os.makedirs(os.path.dirname(db_path), exist_ok=True)+ state.db = DatabaseManager(db_path, cfg.doclib.sqlite)+ await state.db.initialize()++ state.fts = FTSManager(state.db)+ state.config_svc = ConfigService(state.db)+ state.parse_svc = ParseService(state.db, state.fts, state.config_svc, data_dir)+ state.search_svc = SearchService(state.db, state.fts)+ state.cleanup_svc = CleanupService(state.db, data_dir)++ await state.db.execute("UPDATE files SET locked_at = NULL WHERE locked_at IS NOT NULL")+ await state.db.execute(+ "UPDATE parses SET locked_at = NULL, status = ? WHERE status = ?",+ (PARSE_STATUS_FAILED, PARSE_STATUS_PARSING),+ )++ state.parse_server_proc = None+ local_mode = (await state.config_svc.get("parse_server.local.mode")) or "disabled"+ health = get_health()+ health.local_mode = local_mode+ if local_mode == "managed":+ managed_tier = (await state.config_svc.get("parse_server.local.managed_tier")) or "standard"+ try:+ cmd = [sys.executable, "-m", "mineru.parser.api_server", *api_server_args_for_tier(managed_tier)]+ logging.info("Starting managed parse-server: %s", " ".join(cmd))+ proc = subprocess.Popen(+ cmd,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ logging.info("Managed parse-server started (PID %d, tier=%s)", proc.pid, managed_tier)+ state.parse_server_proc = proc+ health.managed_proc = proc+ health.local_starting = True+ health.local_started_at = time.time()+ except Exception as exc:+ logging.error("Failed to start managed parse-server: %s", exc)++ state.watch = WatchLoop(state.db, state.config_svc, state.parse_svc)+ state.ingest_workers = IngestWorkerPool(state.parse_svc, num_workers=cfg.doclib.ingest_workers)+ state.parse_workers = ParseWorkerPool(state.parse_svc, num_workers=cfg.doclib.parse_workers)+ state.device_monitor = DeviceMonitor(state.db, state.config_svc)+ state.compaction = Compaction(state.db, interval_sec=cfg.doclib.compaction_interval_sec, data_dir=data_dir)+ state.health_check = ParseServerHealthCheck(state.config_svc)++ asyncio.create_task(state.watch.run())+ asyncio.create_task(state.ingest_workers.run())+ asyncio.create_task(state.parse_workers.run())+ asyncio.create_task(state.device_monitor.run())+ asyncio.create_task(state.compaction.run())+ asyncio.create_task(state.health_check.run())++ state.start_time = time.time()+ state.pid = os.getpid()+ state.data_dir = data_dir+ state.config = cfg++ @app.on_event("shutdown")+ async def shutdown() -> None:+ 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)+ 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",+ "ingest_workers",+ "parse_workers",+ "device_monitor",+ "compaction",+ "health_check",+ ]:+ c = getattr(state, comp, None)+ if c and hasattr(c, "stop"):+ await c.stop()++ if state.db:+ await state.db.close()++ @app.middleware("http")+ async def attach_state(request: Request, call_next: Callable) -> Any:+ request.state.app = state+ return await call_next(request)++ @app.exception_handler(MineruError)+ async def mineru_error_handler(_request: Request, exc: MineruError) -> JSONResponse:+ status_map = {+ "invalid_request_error": 400,+ "authentication_error": 401,+ "permission_error": 403,+ "rate_limit_error": 429,+ "engine_error": 500,+ "api_error": 500,+ }+ return JSONResponse(+ status_code=status_map.get(exc.type, 500),+ 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))),+ )++ return app+++class AppState:+ pass+++def main() -> None:+ """Entry point: python -m mineru.doclib.app"""+ cfg = config+ uds_path = cfg.doclib.uds.path++ try:+ os.unlink(uds_path)+ except OSError:+ pass++ app = create_app(cfg)+ uv_config = uvicorn.Config(+ app,+ lifespan="on",+ timeout_keep_alive=cfg.doclib.http.timeout,+ )+ server = uvicorn.Server(uv_config)++ uds_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ uds_sock.bind(uds_path)+ os.chmod(uds_path, cfg.doclib.uds.permission)+ uds_sock.listen(cfg.doclib.http.backlog)+ sockets = [uds_sock]++ if cfg.doclib.http.enabled:+ tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ tcp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ tcp_sock.bind((cfg.doclib.http.host, cfg.doclib.http.port))+ except OSError as exc:+ if exc.errno == errno.EADDRINUSE and not cfg.doclib.http.strict_port:+ tcp_sock.bind((cfg.doclib.http.host, 0))+ port = tcp_sock.getsockname()[1]+ print(f"Port {cfg.doclib.http.port} in use, using {port}")+ else:+ raise+ else:+ port = cfg.doclib.http.port+ tcp_sock.listen(cfg.doclib.http.backlog)+ sockets.append(tcp_sock)+ print(f"MinerU server listening on UDS {uds_path} and TCP {cfg.doclib.http.host}:{port}")+ else:+ print(f"MinerU server listening on UDS {uds_path}")++ loop = asyncio.new_event_loop()++ async def serve() -> None:+ await server.serve(sockets=sockets)++ try:+ loop.run_until_complete(serve())+ except KeyboardInterrupt:+ pass+ finally:+ try:+ os.unlink(uds_path)+ except OSError:+ pass+ loop.close()+++def _setup_logging(log_cfg: LogConfig) -> None:+ logger = logging.getLogger("mineru")+ level = getattr(logging, log_cfg.level.upper(), logging.INFO)+ logger.setLevel(level)++ if not logger.handlers:+ ch = logging.StreamHandler()+ ch.setLevel(level)+ ch.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))+ logger.addHandler(ch)++ log_path = os.path.expanduser(log_cfg.path)+ os.makedirs(os.path.dirname(log_path), exist_ok=True)+ fh = RotatingFileHandler(log_path, maxBytes=5 * 1024 * 1024, backupCount=3)+ fh.setLevel(level)+ fh.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))+ logger.addHandler(fh)+++if __name__ == "__main__":+ main()diff --git a/mineru/doclib/background/compaction.py b/mineru/doclib/background/compaction.pyindex e51ea18f..17a035bb 100644--- a/mineru/doclib/background/compaction.py+++ b/mineru/doclib/background/compaction.py@@ -8,17 +8,19 @@ import loggingimport osimport time-from mineru.constants import DATA_DIRfrom ..core.db import DatabaseManager-from ..services.parse_svc import parse_range_set+from ..services.parse_svc import parse_batch_json_path, parse_range_set+from ...types import Tier+from ..types import PARSE_STATUS_DONE, PARSE_STATUS_SUPERSEDEDlogger = logging.getLogger("mineru.compaction")class Compaction:- def __init__(self, db: DatabaseManager, interval_sec: int = 600) -> None:+ def __init__(self, db: DatabaseManager, interval_sec: int, data_dir: str) -> None:self.db = dbself.interval_sec = interval_sec+ self.data_dir = os.path.expanduser(data_dir)self.running = Falseasync def run(self) -> None:@@ -40,8 +42,9 @@ class Compaction:async def _compact(self) -> int:"""Scan all (sha256, tier) pairs with multiple done batches and merge them."""rows = await self.db.fetchall(- "SELECT sha256, tier FROM parses WHERE status='done' "- "GROUP BY sha256, tier HAVING COUNT(*) > 1"+ "SELECT sha256, tier FROM parses WHERE status=? "+ "GROUP BY sha256, tier HAVING COUNT(*) > 1",+ (PARSE_STATUS_DONE,),)total_merged = 0for r in rows:@@ -49,11 +52,11 @@ class Compaction:total_merged += mergedreturn total_merged- async def _compact_doc_tier(self, sha256: str, tier: str) -> int:+ async def _compact_doc_tier(self, sha256: str, tier: Tier) -> int:rows = await self.db.fetchall(- "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done' "+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status=? ""ORDER BY done_at DESC",- (sha256, tier),+ (sha256, tier, PARSE_STATUS_DONE),)if len(rows) <= 1:return 0@@ -87,18 +90,18 @@ class Compaction:# atomic replacenow = int(time.time() * 1000)await self.db.execute(- "DELETE FROM parses WHERE sha256=? AND tier=? AND status='done'",- (sha256, tier),+ "DELETE FROM parses WHERE sha256=? AND tier=? AND status=?",+ (sha256, tier, PARSE_STATUS_DONE),)await self.db.execute(- "DELETE FROM parses WHERE sha256=? AND tier=? AND status='superseded'",- (sha256, tier),+ "DELETE FROM parses WHERE sha256=? AND tier=? AND status=?",+ (sha256, tier, PARSE_STATUS_SUPERSEDED),)for pages_str in merged_ranges:await self.db.execute("INSERT INTO parses (sha256, tier, pages, status, done_at, priority, "- "created_at, updated_at) VALUES (?, ?, ?, 'done', ?, 0, ?, ?)",- (sha256, tier, pages_str, max_done_at, now, now),+ "created_at, updated_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?)",+ (sha256, tier, pages_str, PARSE_STATUS_DONE, max_done_at, now, now),)# compact JSON files (only from done batches, not superseded)@@ -107,13 +110,12 @@ class Compaction:return len(rows) - len(merged_ranges)async def _compact_json(- self, sha256: str, tier: str, merged_ranges: list[str],+ self, sha256: str, tier: Tier, merged_ranges: list[str],done_rows: list[dict], max_done_at: int,) -> None:"""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)+ tier_dir = os.path.join(self.data_dir, "parsed", sha256[:2], sha256, tier)if not os.path.isdir(tier_dir):return@@ -121,8 +123,7 @@ class Compaction:# process oldest first → newest overwrites (done_rows is sorted by done_at DESC)pages_by_idx: dict[int, dict] = {}for row in reversed(done_rows):- key = _safe_filename(row["pages"], row["done_at"])- fpath = os.path.join(tier_dir, f"{key}.json")+ fpath = parse_batch_json_path(self.data_dir, sha256, tier, row["pages"], row["done_at"])if not os.path.isfile(fpath):continuetry:@@ -151,8 +152,7 @@ class Compaction:]if not json_pages:continue- key = _safe_filename(pages_str, max_done_at)- json_path = os.path.join(tier_dir, f"{key}.json")+ json_path = parse_batch_json_path(self.data_dir, sha256, tier, pages_str, max_done_at)try:with open(json_path, "w", encoding="utf-8") as f:_json.dump(@@ -160,7 +160,3 @@ class Compaction:)except Exception:pass---def _safe_filename(s: str, done_at: int = 0) -> str:- return f"{s}_{done_at}" if done_at else sdiff --git a/mineru/doclib/background/device_monitor.py b/mineru/doclib/background/device_monitor.pyindex 886dd4c4..a0609d97 100644--- a/mineru/doclib/background/device_monitor.py+++ b/mineru/doclib/background/device_monitor.py@@ -4,9 +4,11 @@ from __future__ import annotationsimport asyncioimport os+import timefrom ..core.db import DatabaseManagerfrom ..services.config_svc import ConfigService+from ..types import SCAN_STATUS_ACTIVE, SCAN_STATUS_UNREACHABLE, WATCH_STATUS_ACTIVE, WATCH_STATUS_UNREACHABLEclass DeviceMonitor:@@ -18,29 +20,31 @@ class DeviceMonitor:async def run(self) -> None:self.running = Truewhile self.running:- watches = await self.config_svc.get_watches_by_status("active")+ watches = await self.config_svc.get_watches_by_status(WATCH_STATUS_ACTIVE)for w in watches:if not w["removable"]:continuetry:os.stat(w["path"])except (FileNotFoundError, OSError):- await self.config_svc.update_watch_status(w["id"], "unreachable")+ await self.config_svc.update_watch_status(w["id"], WATCH_STATUS_UNREACHABLE)+ now = int(time.time() * 1000)await self.db.execute(- "UPDATE files SET scan_status='unreachable' "- "WHERE watch_id=? AND scan_status='active'",- (w["id"],),+ "UPDATE files SET scan_status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, deleted_at=NULL, updated_at=? "+ "WHERE watch_id=? AND scan_status=?",+ (SCAN_STATUS_UNREACHABLE, now, w["id"], SCAN_STATUS_ACTIVE),)- unreachable = await self.config_svc.get_watches_by_status("unreachable")+ unreachable = await self.config_svc.get_watches_by_status(WATCH_STATUS_UNREACHABLE)for w in unreachable:try:os.stat(w["path"])- await self.config_svc.update_watch_status(w["id"], "active")+ await self.config_svc.update_watch_status(w["id"], WATCH_STATUS_ACTIVE)+ now = int(time.time() * 1000)await self.db.execute(- "UPDATE files SET scan_status='active' "- "WHERE watch_id=? AND scan_status='unreachable'",- (w["id"],),+ "UPDATE files SET scan_status=?, updated_at=? "+ "WHERE watch_id=? AND scan_status=?",+ (SCAN_STATUS_ACTIVE, now, w["id"], SCAN_STATUS_UNREACHABLE),)except (FileNotFoundError, OSError):passdiff --git a/mineru/doclib/background/ingest.py b/mineru/doclib/background/ingest.pyindex 928f0792..2720e04a 100644--- a/mineru/doclib/background/ingest.py+++ b/mineru/doclib/background/ingest.py@@ -7,6 +7,7 @@ import loggingimport timefrom ..services.parse_svc import ParseService+from ..types import SCAN_STATUS_ACTIVElogger = logging.getLogger("mineru.ingest")@@ -35,7 +36,8 @@ class IngestWorkerPool:no_task_count += 1if no_task_count == 1 or no_task_count % 20 == 0:q = await self.parse_svc.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND scan_status='active'"+ "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND scan_status=?",+ (SCAN_STATUS_ACTIVE,),)logger.info(f"Ingest worker {worker_id}: queue={q['cnt'] if q else 0}")await asyncio.sleep(0.5)@@ -72,11 +74,11 @@ class IngestWorkerPool:"UPDATE files SET locked_at=? ""WHERE id = ("" SELECT id FROM files "- " WHERE sha256 IS NULL AND scan_status='active' "+ " WHERE sha256 IS NULL AND scan_status=? "" AND (locked_at IS NULL OR locked_at < ?) "" ORDER BY first_seen_at ASC LIMIT 1"") RETURNING *",- (now, timeout),+ (now, SCAN_STATUS_ACTIVE, timeout),)async def stop(self) -> None:diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.pyindex 50f7a7bc..edb1ff00 100644--- a/mineru/doclib/background/parse_server_health.py+++ b/mineru/doclib/background/parse_server_health.py@@ -7,9 +7,12 @@ import loggingimport subprocessimport sysfrom dataclasses import dataclass, field+from typing import castimport httpx+from ...types import TIERS, Tier+logger = logging.getLogger("mineru.health_check")CHECK_INTERVAL_SEC = 60@@ -21,11 +24,11 @@ class ParseServerHealth:local_healthy: bool = Falselocal_starting: bool = Falselocal_started_at: float = 0.0- local_supported_tiers: list[str] = field(default_factory=list)+ local_supported_tiers: list[Tier] = field(default_factory=list)local_mode: str = "disabled"self_hosted_url: str | None = Noneremote_healthy: bool = False- remote_supported_tiers: list[str] = field(default_factory=list)+ remote_supported_tiers: list[Tier] = field(default_factory=list)restart_count: int = 0managed_proc: subprocess.Popen | None = None@@ -37,6 +40,16 @@ def get_health() -> ParseServerHealth:return _parse_server_health+def api_server_args_for_tier(tier: Tier) -> list[str]:+ """Return managed api-server process args for a doclib tier.++ Managed doclib startup uses ``--tier`` so the api-server resolves its own+ backend. Backend remains an api-server implementation detail and must not+ leak into runtime doclib parse requests.+ """+ return ["--tier", tier, "--port", "15981"]++class ParseServerHealthCheck:"""Periodically probes parse-server health via GET /v1/tiers."""@@ -87,22 +100,19 @@ class ParseServerHealthCheck:async def _try_restart_managed(self, health: ParseServerHealth) -> None:if health.restart_count >= MAX_RESTART_ATTEMPTS:logger.error(- f"Managed parse-server failed %d restarts, disabling", MAX_RESTART_ATTEMPTS+ "Managed parse-server failed %d restarts, disabling", MAX_RESTART_ATTEMPTS)health.local_mode = "disabled"returnhealth.restart_count += 1managed_tier = (await self.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")- cmd = [sys.executable, "-m", "mineru.parser.api_server",- "--backend", backend, "--port", "15981"]+ cmd = [sys.executable, "-m", "mineru.parser.api_server", *api_server_args_for_tier(managed_tier)]logger.info("Restarting managed parse-server (attempt %d/%d): %s",health.restart_count, MAX_RESTART_ATTEMPTS, " ".join(cmd))try:proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)- logger.info("Managed parse-server restarted (PID %d, backend=%s)", proc.pid, backend)+ logger.info("Managed parse-server restarted (PID %d, tier=%s)", proc.pid, managed_tier)health.managed_proc = prochealth.local_starting = Truehealth.local_started_at = asyncio.get_event_loop().time()@@ -110,13 +120,17 @@ class ParseServerHealthCheck:logger.error(f"Failed to restart managed parse-server: {exc}")@staticmethod- async def _probe(base_url: str) -> tuple[bool, list[str]]:+ async def _probe(base_url: str) -> tuple[bool, list[Tier]]:try:async with httpx.AsyncClient(timeout=10) as client:resp = await client.get(f"{base_url}/v1/tiers")if resp.status_code == 200:data = resp.json()- tiers = [t.get("id") for t in data.get("data", [])]+ tiers: list[Tier] = []+ for t in data.get("data", []):+ tier_id = t.get("id")+ if tier_id in TIERS:+ tiers.append(cast(Tier, tier_id))return True, tiersexcept Exception:passdiff --git a/mineru/doclib/background/parse_worker.py b/mineru/doclib/background/parse_worker.pyindex 334be9a6..79c3710b 100644--- a/mineru/doclib/background/parse_worker.py+++ b/mineru/doclib/background/parse_worker.py@@ -7,6 +7,7 @@ import loggingimport timefrom ..services.parse_svc import ParseService+from ..types import PARSE_STATUS_FAILEDlogger = logging.getLogger("mineru.parse_worker")@@ -55,9 +56,9 @@ class ParseWorkerPool:try:now = int(time.time() * 1000)await self.parse_svc.db.execute(- "UPDATE parses SET status='failed', error_code=?, error_msg=?, "+ "UPDATE parses SET status=?, error_code=?, error_msg=?, ""locked_at=NULL, updated_at=? WHERE id=?",- ("parse_failed", str(exc)[:500], now, task["id"]),+ (PARSE_STATUS_FAILED, "parse_failed", str(exc)[:500], now, task["id"]),)except Exception:passdiff --git a/mineru/doclib/background/watch.py b/mineru/doclib/background/watch.pyindex 602b4757..62551b99 100644--- a/mineru/doclib/background/watch.py+++ b/mineru/doclib/background/watch.py@@ -4,16 +4,15 @@ from __future__ import annotationsimport asyncioimport os-import timefrom pathlib import Pathfrom watchfiles import awatch-from mineru.constants import ALLOWED_EXTENSIONS-from ..core.db import DatabaseManager+from ..constants import ALLOWED_EXTENSIONSfrom ..services.config_svc import ConfigServicefrom ..services.parse_svc import ParseService+from ..types import WATCH_STATUS_ACTIVEclass WatchLoop:@@ -33,7 +32,7 @@ class WatchLoop:active_ids: set[int] = set()for w in watches:- if w["watch_status"] != "active":+ if w["watch_status"] != WATCH_STATUS_ACTIVE:continueactive_ids.add(w["id"])@@ -63,7 +62,7 @@ class WatchLoop:continueif await self.config_svc.is_path_excluded(filepath):continue- await self._discover_file(filepath, watch_id)+ await self._refresh_file(filepath, watch_id)file_count += 1await self.config_svc.update_watch_scan_stats(watch_id, file_count)except Exception:@@ -85,23 +84,10 @@ class WatchLoop:returnif await self.config_svc.is_path_excluded(filepath):return- await self._discover_file(filepath, watch_id)-- async def _discover_file(self, filepath: str, watch_id: int) -> None:- now = int(time.time() * 1000)-- await self.db.execute(- "INSERT OR IGNORE INTO files (path, filename, ext, size_bytes, mtime_ms, "- "watch_id, first_seen_at, updated_at) VALUES (?, ?, ?, 0, 0, ?, ?, ?)",- (- filepath,- Path(filepath).name,- Path(filepath).suffix.lstrip(".").lower(),- watch_id,- now,- now,- ),- )+ await self._refresh_file(filepath, watch_id)++ async def _refresh_file(self, filepath: str, watch_id: int) -> None:+ await self.parse_svc.refresh_file(filepath, watch_id=watch_id)async def stop(self) -> None:self.running = Falsediff --git a/mineru/doclib/base.py b/mineru/doclib/base.pynew file mode 100644index 00000000..6bb8dd82--- /dev/null+++ b/mineru/doclib/base.py@@ -0,0 +1,497 @@+"""Synchronous doclib public interface."""++from __future__ import annotations++from abc import ABC, abstractmethod++from ..types import Tier+from .types import (+ CleanupDeletedRequest,+ CleanupDeletedResponse,+ CleanupOrphansRequest,+ CleanupOrphansResponse,+ CleanupTempRequest,+ CleanupTempResponse,+ ConfigResponse,+ ConfigSetRequest,+ ConfigSetResponse,+ DocContentResponse,+ DocInfo,+ ExcludeRuleInfo,+ ExcludeRuleListResponse,+ ExcludeRuleRequest,+ FileInfoResponse,+ FindResponse,+ InvalidateRequest,+ InvalidateResponse,+ ListDocsResponse,+ ListParsesResponse,+ ParseInfo,+ ParseRequest,+ ParseResponse,+ ParsingRuleInfo,+ ParsingRuleListResponse,+ ParsingRuleRequest,+ RemoveExcludeRuleResponse,+ RemoveParsingRuleResponse,+ RemoveWatchResponse,+ SearchResponse,+ ServerStatusResponse,+ ShutdownResponse,+ WatchInfo,+ WatchListResponse,+ WatchRequest,+)+++class DoclibInterface(ABC):+ """Synchronous contract for the doclib SDK client and sync implementations.++ Implementations must raise ``MineruError`` subclasses for contract-level+ failures. HTTP implementations serialize those failures as ``ErrorResponse``+ and SDK clients translate them back to ``MineruError``.+ """++ @abstractmethod+ def get_server_status(self) -> ServerStatusResponse:+ """Return local doclib server status.++ Raises:+ ServerNotRunningError: when an SDK client cannot connect to the local server.+ MineruError: for invalid or non-JSON server responses.+ """+ raise NotImplementedError()++ @abstractmethod+ def shutdown_server(self) -> ShutdownResponse:+ """Request graceful doclib server shutdown.++ Raises:+ ServerNotRunningError: when an SDK client cannot connect to the local server.+ MineruError: for server-side shutdown failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def ensure_parse(self, request: ParseRequest) -> ParseResponse:+ """Ensure parse records exist for a document request.++ Raises:+ InvalidRequestError: for invalid paths, invalid page ranges, unsupported file types, or invalid tier values.+ NotFoundError: when the source file cannot be found.+ PermissionError_: when the source file cannot be read.+ EngineError: when the requested quality tier cannot be served or parsing cannot be queued.+ MineruError: for other server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def list_parses(+ self,+ *,+ ids: list[int] | None = None,+ sha256: str | None = None,+ tier: Tier | None = None,+ status: str | None = None,+ pages: str | None = None,+ include_superseded: bool = False,+ ) -> ListParsesResponse:+ """List parse records and optional coverage information.++ Raises:+ InvalidRequestError: for malformed ids, status filters, page ranges, or tier filters.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def get_parse(self, parse_id: int) -> ParseInfo:+ """Return one parse record.++ Raises:+ NotFoundError: when ``parse_id`` does not exist.+ InvalidRequestError: when ``parse_id`` is invalid.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def invalidate(self, request: InvalidateRequest) -> InvalidateResponse:+ """Invalidate cached doclib artifacts.++ Raises:+ InvalidRequestError: when the target, path, sha256, or tier is invalid.+ NotFoundError: when the target document cannot be resolved.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def list_docs(self, *, path: str | None = None) -> ListDocsResponse:+ """List active docs, optionally filtered by path.++ Raises:+ InvalidRequestError: when ``path`` is malformed.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:+ """Return one doc by content hash.++ Raises:+ NotFoundError: when ``sha256`` does not exist in doclib.+ InvalidRequestError: when ``sha256`` is malformed.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def get_doc_content(+ self,+ sha256: str,+ *,+ tier: Tier,+ pages: str | None = None,+ format: str = "markdown",+ output: str | None = None,+ no_marker: bool = False,+ ) -> DocContentResponse:+ """Render stored doc content from parsed JSON artifacts.++ Raises:+ NotFoundError: when the document or requested parsed content is not cached.+ InvalidRequestError: when tier, pages, format, output, or marker options are invalid.+ MineruError: for render or server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def search(self, query: str, *, file_type: str | None = None, limit: int = 20, offset: int = 0) -> SearchResponse:+ """Search parsed document content.++ Raises:+ InvalidRequestError: when query, file type, limit, or offset is invalid.+ MineruError: for search backend failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def find(self, query: str, *, limit: int = 50) -> FindResponse:+ """Search filenames.++ Raises:+ InvalidRequestError: when query or limit is invalid.+ MineruError: for search backend failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def get_file_info(self, path: str) -> FileInfoResponse:+ """Return file, doc, and parse state for a local path.++ Raises:+ NotFoundError: when the path is unknown to doclib.+ InvalidRequestError: when the path is malformed.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def get_config(self) -> ConfigResponse:+ """Return runtime doclib key-value config.++ Raises:+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def set_config(self, request: ConfigSetRequest) -> ConfigSetResponse:+ """Set one runtime config key.++ Raises:+ InvalidRequestError: when the key is unknown, read-only, or the value is invalid.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def add_watch(self, request: WatchRequest) -> WatchInfo:+ """Add a watch target.++ Raises:+ InvalidRequestError: when the path is not absolute, not normalized, or otherwise invalid.+ NotFoundError: when the path does not exist.+ PermissionError_: when the path cannot be read.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def list_watches(self) -> WatchListResponse:+ """List watch targets.++ Raises:+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def remove_watch(self, path: str) -> RemoveWatchResponse:+ """Remove a watch target.++ Raises:+ NotFoundError: when the watch target does not exist.+ InvalidRequestError: when the path is malformed.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def add_exclude_rule(self, request: ExcludeRuleRequest) -> ExcludeRuleInfo:+ """Add an exclude rule.++ Raises:+ InvalidRequestError: when the pattern, priority, or name is invalid.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def list_exclude_rules(self) -> ExcludeRuleListResponse:+ """List exclude rules.++ Raises:+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def remove_exclude_rule(self, rule_id: int) -> RemoveExcludeRuleResponse:+ """Remove an exclude rule.++ Raises:+ NotFoundError: when the rule does not exist.+ InvalidRequestError: when ``rule_id`` is invalid.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def add_parsing_rule(self, request: ParsingRuleRequest) -> ParsingRuleInfo:+ """Add a parsing rule.++ Raises:+ InvalidRequestError: when the pattern, tier, pages, priority, or name is invalid.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def list_parsing_rules(self) -> ParsingRuleListResponse:+ """List parsing rules.++ Raises:+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def remove_parsing_rule(self, rule_id: int) -> RemoveParsingRuleResponse:+ """Remove a parsing rule.++ Raises:+ NotFoundError: when the rule does not exist.+ InvalidRequestError: when ``rule_id`` is invalid.+ MineruError: for server-side failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def cleanup_deleted_files(self, request: CleanupDeletedRequest) -> CleanupDeletedResponse:+ """Clean DB/file entries for deleted source files.++ Raises:+ InvalidRequestError: when cleanup options are invalid.+ MineruError: for cleanup failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def cleanup_orphan_docs(self, request: CleanupOrphansRequest) -> CleanupOrphansResponse:+ """Clean orphan doc artifacts.++ Raises:+ InvalidRequestError: when cleanup options are invalid.+ MineruError: for cleanup failures.+ """+ raise NotImplementedError()++ @abstractmethod+ def cleanup_temp_files(self, request: CleanupTempRequest) -> CleanupTempResponse:+ """Clean temporary files.++ Raises:+ InvalidRequestError: when cleanup options are invalid.+ MineruError: for cleanup failures.+ """+ raise NotImplementedError()+++class AsyncDoclibInterface(ABC):+ """Asynchronous contract matching ``DoclibInterface`` method-for-method.++ The async interface has the same method names, parameters, return+ annotations, and error contract as ``DoclibInterface``. Implementations must+ raise ``MineruError`` subclasses for contract-level failures.+ """++ @abstractmethod+ async def get_server_status(self) -> ServerStatusResponse:+ """Async version of ``DoclibInterface.get_server_status``."""+ raise NotImplementedError()++ @abstractmethod+ async def shutdown_server(self) -> ShutdownResponse:+ """Async version of ``DoclibInterface.shutdown_server``."""+ raise NotImplementedError()++ @abstractmethod+ async def ensure_parse(self, request: ParseRequest) -> ParseResponse:+ """Async version of ``DoclibInterface.ensure_parse``."""+ raise NotImplementedError()++ @abstractmethod+ async def list_parses(+ self,+ *,+ ids: list[int] | None = None,+ sha256: str | None = None,+ tier: Tier | None = None,+ status: str | None = None,+ pages: str | None = None,+ include_superseded: bool = False,+ ) -> ListParsesResponse:+ """Async version of ``DoclibInterface.list_parses``."""+ raise NotImplementedError()++ @abstractmethod+ async def get_parse(self, parse_id: int) -> ParseInfo:+ """Async version of ``DoclibInterface.get_parse``."""+ raise NotImplementedError()++ @abstractmethod+ async def invalidate(self, request: InvalidateRequest) -> InvalidateResponse:+ """Async version of ``DoclibInterface.invalidate``."""+ raise NotImplementedError()++ @abstractmethod+ async def list_docs(self, *, path: str | None = None) -> ListDocsResponse:+ """Async version of ``DoclibInterface.list_docs``."""+ raise NotImplementedError()++ @abstractmethod+ async def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:+ """Async version of ``DoclibInterface.get_doc``."""+ raise NotImplementedError()++ @abstractmethod+ async def get_doc_content(+ self,+ sha256: str,+ *,+ tier: Tier,+ pages: str | None = None,+ format: str = "markdown",+ output: str | None = None,+ no_marker: bool = False,+ ) -> DocContentResponse:+ """Async version of ``DoclibInterface.get_doc_content``."""+ raise NotImplementedError()++ @abstractmethod+ async def search(self, query: str, *, file_type: str | None = None, limit: int = 20, offset: int = 0) -> SearchResponse:+ """Async version of ``DoclibInterface.search``."""+ raise NotImplementedError()++ @abstractmethod+ async def find(self, query: str, *, limit: int = 50) -> FindResponse:+ """Async version of ``DoclibInterface.find``."""+ raise NotImplementedError()++ @abstractmethod+ async def get_file_info(self, path: str) -> FileInfoResponse:+ """Async version of ``DoclibInterface.get_file_info``."""+ raise NotImplementedError()++ @abstractmethod+ async def get_config(self) -> ConfigResponse:+ """Async version of ``DoclibInterface.get_config``."""+ raise NotImplementedError()++ @abstractmethod+ async def set_config(self, request: ConfigSetRequest) -> ConfigSetResponse:+ """Async version of ``DoclibInterface.set_config``."""+ raise NotImplementedError()++ @abstractmethod+ async def add_watch(self, request: WatchRequest) -> WatchInfo:+ """Async version of ``DoclibInterface.add_watch``."""+ raise NotImplementedError()++ @abstractmethod+ async def list_watches(self) -> WatchListResponse:+ """Async version of ``DoclibInterface.list_watches``."""+ raise NotImplementedError()++ @abstractmethod+ async def remove_watch(self, path: str) -> RemoveWatchResponse:+ """Async version of ``DoclibInterface.remove_watch``."""+ raise NotImplementedError()++ @abstractmethod+ async def add_exclude_rule(self, request: ExcludeRuleRequest) -> ExcludeRuleInfo:+ """Async version of ``DoclibInterface.add_exclude_rule``."""+ raise NotImplementedError()++ @abstractmethod+ async def list_exclude_rules(self) -> ExcludeRuleListResponse:+ """Async version of ``DoclibInterface.list_exclude_rules``."""+ raise NotImplementedError()++ @abstractmethod+ async def remove_exclude_rule(self, rule_id: int) -> RemoveExcludeRuleResponse:+ """Async version of ``DoclibInterface.remove_exclude_rule``."""+ raise NotImplementedError()++ @abstractmethod+ async def add_parsing_rule(self, request: ParsingRuleRequest) -> ParsingRuleInfo:+ """Async version of ``DoclibInterface.add_parsing_rule``."""+ raise NotImplementedError()++ @abstractmethod+ async def list_parsing_rules(self) -> ParsingRuleListResponse:+ """Async version of ``DoclibInterface.list_parsing_rules``."""+ raise NotImplementedError()++ @abstractmethod+ async def remove_parsing_rule(self, rule_id: int) -> RemoveParsingRuleResponse:+ """Async version of ``DoclibInterface.remove_parsing_rule``."""+ raise NotImplementedError()++ @abstractmethod+ async def cleanup_deleted_files(self, request: CleanupDeletedRequest) -> CleanupDeletedResponse:+ """Async version of ``DoclibInterface.cleanup_deleted_files``."""+ raise NotImplementedError()++ @abstractmethod+ async def cleanup_orphan_docs(self, request: CleanupOrphansRequest) -> CleanupOrphansResponse:+ """Async version of ``DoclibInterface.cleanup_orphan_docs``."""+ raise NotImplementedError()++ @abstractmethod+ async def cleanup_temp_files(self, request: CleanupTempRequest) -> CleanupTempResponse:+ """Async version of ``DoclibInterface.cleanup_temp_files``."""+ raise NotImplementedError()diff --git a/mineru/doclib/client.py b/mineru/doclib/client.pyindex 7601eac1..52e411f9 100644--- a/mineru/doclib/client.py+++ b/mineru/doclib/client.py@@ -1,194 +1,285 @@-"""Product SDK — communicates with the local mineru doclib over UDS."""+"""Synchronous HTTP client implementation of the doclib public interface."""from __future__ import annotations-from typing import Any+from typing import Any, Final, TypeVarimport httpx--from mineru.constants import SOCKET_PATH-from mineru.errors import MineruError, ServerNotRunningError---class MineruClient:- """httpx-based client for the local mineru doclib."""-- def __init__(self, socket_path: str = SOCKET_PATH, timeout: int = 60) -> None:- transport = httpx.HTTPTransport(uds=socket_path)- self._client = httpx.Client(- transport=transport, base_url="http://mineru", timeout=timeout- )+from pydantic import BaseModel+from pydantic_core import to_jsonable_python++from ..config import config+from ..errors import MineruError, ServerNotRunningError+from ..types import Tier+from .base import DoclibInterface+from .types import (+ CleanupDeletedRequest,+ CleanupDeletedResponse,+ CleanupOrphansRequest,+ CleanupOrphansResponse,+ CleanupTempRequest,+ CleanupTempResponse,+ ConfigResponse,+ ConfigSetRequest,+ ConfigSetResponse,+ DocContentResponse,+ DocInfo,+ ExcludeRuleInfo,+ ExcludeRuleListResponse,+ ExcludeRuleRequest,+ FileInfoResponse,+ FindResponse,+ InvalidateRequest,+ InvalidateResponse,+ ListDocsResponse,+ ListParsesResponse,+ ParseInfo,+ ParseRequest,+ ParseResponse,+ ParsingRuleInfo,+ ParsingRuleListResponse,+ ParsingRuleRequest,+ RemoveExcludeRuleResponse,+ RemoveParsingRuleResponse,+ RemoveWatchResponse,+ SearchResponse,+ ServerStatusResponse,+ ShutdownResponse,+ WatchInfo,+ WatchListResponse,+ WatchRequest,+)+from .utils.route_utils import get_route_info, route++T = TypeVar("T", bound=BaseModel)+_CONFIG_UDS_PATH: Final = object()+++class DoclibClient(DoclibInterface):+ """httpx-backed synchronous client for the doclib public interface."""++ def __init__(+ self,+ *,+ base_url: str = "http://mineru",+ socket_path: str | None | object = _CONFIG_UDS_PATH,+ timeout: int = 60,+ api_prefix: str = "/api/v1",+ ) -> None:+ if socket_path is _CONFIG_UDS_PATH:+ socket_path = config.doclib.uds.path+ transport = httpx.HTTPTransport(uds=socket_path) if isinstance(socket_path, str) and socket_path else None+ self._client = httpx.Client(transport=transport, base_url=base_url, timeout=timeout)+ self._api_prefix = api_prefix.rstrip("/")def close(self) -> None:self._client.close()- # ── helpers ────────────────────────────────────────────────-- def _get(self, url_path: str, **params: Any) -> dict:- data = self._request("GET", url_path, query_params=params or None)- return data+ @route("GET", "/server/status", tags=("server",))+ def get_server_status(self) -> ServerStatusResponse:+ return self._request_model(ServerStatusResponse)- def _post(self, url_path: str, json_data: dict | None = None) -> dict:- data = self._request("POST", url_path, json_data=json_data)- return data+ @route("POST", "/shutdown", tags=("server",))+ def shutdown_server(self) -> ShutdownResponse:+ return self._request_model(ShutdownResponse)- def _delete(self, url_path: str, **params: Any) -> dict:- data = self._request("DELETE", url_path, query_params=params or None)- return data+ @route("POST", "/parses", tags=("parse",))+ def ensure_parse(self, request: ParseRequest) -> ParseResponse:+ return self._request_model(ParseResponse, body=request)- def _request(+ @route("GET", "/parses", tags=("parse",))+ def list_parses(self,- method: str,- url_path: str,- query_params: dict | None = None,- json_data: dict | None = None,- ) -> dict:- try:- if method == "GET":- resp = self._client.get(url_path, params=query_params or {})- elif method == "POST":- resp = self._client.post(url_path, json=json_data or {})- else:- resp = self._client.delete(url_path, params=query_params or {})- except httpx.ConnectError:- raise ServerNotRunningError() from None- 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+ *,+ ids: list[int] | None = None,+ sha256: str | None = None,+ tier: Tier | None = None,+ status: str | None = None,+ pages: str | None = None,+ include_superseded: bool = False,+ ) -> ListParsesResponse:+ return self._request_model(+ ListParsesResponse,+ params={+ "ids": ids,+ "sha256": sha256,+ "tier": tier,+ "status": status,+ "pages": pages,+ "include_superseded": include_superseded,+ },+ )- # ── server ─────────────────────────────────────────────────+ @route("GET", "/parses/{parse_id}", tags=("parse",))+ def get_parse(self, parse_id: int) -> ParseInfo:+ return self._request_model(ParseInfo, path_params={"parse_id": parse_id})- def server_status(self) -> dict:- return self._get("/server/status")+ @route("POST", "/invalidate", tags=("parse",))+ def invalidate(self, request: InvalidateRequest) -> InvalidateResponse:+ return self._request_model(InvalidateResponse, body=request)- def shutdown(self) -> dict:- return self._post("/shutdown")+ @route("GET", "/docs", tags=("docs",))+ def list_docs(self, *, path: str | None = None) -> ListDocsResponse:+ return self._request_model(ListDocsResponse, params={"path": path})- # ── parse ──────────────────────────────────────────────────+ @route("GET", "/docs/{sha256}", tags=("docs",))+ def get_doc(self, sha256: str, *, expand_files: bool = False) -> DocInfo:+ return self._request_model(DocInfo, path_params={"sha256": sha256}, params={"expand_files": expand_files})- def parse(+ @route("GET", "/docs/{sha256}/content", tags=("docs",))+ def get_doc_content(self,- path: str,+ sha256: str,*,- tier: str | None = None,+ tier: Tier,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",- {- "path": path,+ output: str | None = None,+ no_marker: bool = False,+ ) -> DocContentResponse:+ return self._request_model(+ DocContentResponse,+ path_params={"sha256": sha256},+ params={"tier": tier,"pages": pages,"format": format,- "force": force,- "remote": remote,- "remote_url": remote_url,- "api_key": api_key,+ "output": output,+ "no_marker": no_marker,},)- def invalidate(self, path: str, *, tier: str | None = None) -> dict:- params = {"path": path}- if tier:- params["tier"] = tier- return self._get("/parse/invalidate", **params)+ @route("GET", "/search", tags=("search",))+ def search(self, query: str, *, file_type: str | None = None, limit: int = 20, offset: int = 0) -> SearchResponse:+ return self._request_model(+ SearchResponse,+ params={"query": query, "file_type": file_type, "limit": limit, "offset": offset},+ )- def parse_status(self, sha256: str, tier: str) -> dict:- return self._get("/parse/status", sha256=sha256, tier=tier)+ @route("GET", "/find", tags=("search",))+ def find(self, query: str, *, limit: int = 50) -> FindResponse:+ return self._request_model(FindResponse, params={"query": query, "limit": limit})- def parse_content(self, sha256: str, tier: str, output: str | None = None) -> dict:- params = {"sha256": sha256, "tier": tier}- if output:- params["output"] = output- return self._get("/parse/content", **params)+ @route("GET", "/info", tags=("info",))+ def get_file_info(self, path: str) -> FileInfoResponse:+ return self._request_model(FileInfoResponse, params={"path": path})- # ── search ─────────────────────────────────────────────────+ @route("GET", "/config", tags=("config",))+ def get_config(self) -> ConfigResponse:+ return self._request_model(ConfigResponse)- def search(- self, query: str, file_type: str | None = None, limit: int = 20, offset: int = 0- ) -> dict:- return self._get("/search", q=query, type=file_type, limit=limit, offset=offset)+ @route("POST", "/config", tags=("config",))+ def set_config(self, request: ConfigSetRequest) -> ConfigSetResponse:+ return self._request_model(ConfigSetResponse, body=request)- def find(self, query: str, limit: int = 50) -> dict:- return self._get("/find", q=query, limit=limit)+ @route("POST", "/config/watch", tags=("config",))+ def add_watch(self, request: WatchRequest) -> WatchInfo:+ return self._request_model(WatchInfo, body=request)- # ── info ───────────────────────────────────────────────────+ @route("GET", "/config/watch", tags=("config",))+ def list_watches(self) -> WatchListResponse:+ return self._request_model(WatchListResponse)- def info(self, file_path: str) -> dict:- return self._get("/info", path=file_path)+ @route("DELETE", "/config/watch", tags=("config",))+ def remove_watch(self, path: str) -> RemoveWatchResponse:+ return self._request_model(RemoveWatchResponse, params={"path": path})- # ── config ─────────────────────────────────────────────────+ @route("POST", "/config/exclude", tags=("config",))+ def add_exclude_rule(self, request: ExcludeRuleRequest) -> ExcludeRuleInfo:+ return self._request_model(ExcludeRuleInfo, body=request)- def config_show(self) -> dict:- return self._get("/config")+ @route("GET", "/config/exclude", tags=("config",))+ def list_exclude_rules(self) -> ExcludeRuleListResponse:+ return self._request_model(ExcludeRuleListResponse)- def config_watch_add(- self, path: str, *, removable: bool = False, label: str | None = None- ) -> dict:- return self._post(- "/config/watch", {"path": path, "removable": removable, "label": label}- )+ @route("DELETE", "/config/exclude/{rule_id}", tags=("config",))+ def remove_exclude_rule(self, rule_id: int) -> RemoveExcludeRuleResponse:+ return self._request_model(RemoveExcludeRuleResponse, path_params={"rule_id": rule_id})++ @route("POST", "/config/parsing-rules", tags=("config",))+ def add_parsing_rule(self, request: ParsingRuleRequest) -> ParsingRuleInfo:+ return self._request_model(ParsingRuleInfo, body=request)- def config_watch_list(self) -> dict:- return self._get("/config/watch")+ @route("GET", "/config/parsing-rules", tags=("config",))+ def list_parsing_rules(self) -> ParsingRuleListResponse:+ return self._request_model(ParsingRuleListResponse)- def config_watch_rm(self, path: str) -> dict:- return self._delete("/config/watch", path=path)+ @route("DELETE", "/config/parsing-rules/{rule_id}", tags=("config",))+ def remove_parsing_rule(self, rule_id: int) -> RemoveParsingRuleResponse:+ return self._request_model(RemoveParsingRuleResponse, path_params={"rule_id": rule_id})- def config_exclude_add(self, pattern: str, priority: int = 0) -> dict:- return self._post("/config/exclude", {"pattern": pattern, "priority": priority})+ @route("POST", "/cleanup/deleted", tags=("cleanup",))+ def cleanup_deleted_files(self, request: CleanupDeletedRequest) -> CleanupDeletedResponse:+ return self._request_model(CleanupDeletedResponse, body=request)- def config_exclude_list(self) -> dict:- return self._get("/config/exclude")+ @route("POST", "/cleanup/orphans", tags=("cleanup",))+ def cleanup_orphan_docs(self, request: CleanupOrphansRequest) -> CleanupOrphansResponse:+ return self._request_model(CleanupOrphansResponse, body=request)- def config_exclude_rm(self, rule_id: int) -> dict:- return self._delete(f"/config/exclude/{rule_id}")+ @route("POST", "/cleanup/temp", tags=("cleanup",))+ def cleanup_temp_files(self, request: CleanupTempRequest) -> CleanupTempResponse:+ return self._request_model(CleanupTempResponse, body=request)- def config_parsing_rules_add(+ def _request_model(self,- pattern: str,+ response_model: type[T],*,- tier: str | None = None,- pages: str | None = None,- remote: bool = False,- name: str | None = None,- ) -> dict:- return self._post(- "/config/parsing-rules",- {- "pattern": pattern,- "tier": tier,- "pages": pages,- "remote": remote,- "name": name,- },- )+ path_params: dict[str, object] | None = None,+ params: dict[str, object] | None = None,+ body: BaseModel | None = None,+ ) -> T:+ route_info = get_route_info(self._calling_route_method())+ path = self._api_prefix + _format_path(route_info.path, path_params or {})+ query_params = _compact_params(params or {})+ json_data = to_jsonable_python(body) if body is not None else None++ try:+ if route_info.method == "GET":+ resp = self._client.get(path, params=query_params)+ elif route_info.method == "POST":+ resp = self._client.post(path, params=query_params, json=json_data or {})+ elif route_info.method == "DELETE":+ resp = self._client.delete(path, params=query_params)+ else:+ raise MineruError("internal_error", f"Unsupported client method: {route_info.method}")+ except httpx.ConnectError:+ raise ServerNotRunningError() from None++ data = _decode_response(resp)+ return response_model.model_validate(data)++ def _calling_route_method(self) -> object:+ import inspect- def config_parsing_rules_list(self) -> dict:- return self._get("/config/parsing-rules")+ frame = inspect.currentframe()+ if frame is None or frame.f_back is None or frame.f_back.f_back is None:+ raise MineruError("internal_error", "Cannot resolve client route method.")+ method_name = frame.f_back.f_back.f_code.co_name+ return getattr(self, method_name)- def config_parsing_rules_rm(self, rule_id: int) -> dict:- return self._delete(f"/config/parsing-rules/{rule_id}")+def _format_path(path: str, path_params: dict[str, object]) -> str:+ for key, value in path_params.items():+ path = path.replace("{" + key + "}", str(value))+ return path-def _error_from_response(error: dict) -> MineruError:- code = error.get("code", "internal_error")- message = error.get("message", "")- param = error.get("param")- return MineruError(code, message, param)++def _compact_params(params: dict[str, object]) -> dict[str, object]:+ return {key: value for key, value in params.items() if value is not None}+++def _decode_response(resp: httpx.Response) -> dict[str, Any]:+ 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()+ raise MineruError("internal_error", "Invalid server response: expected JSON object")+ if "error" in data:+ error = data["error"]+ if isinstance(error, dict):+ raise MineruError(error.get("code", "internal_error"), error.get("message", ""), error.get("param"))+ resp.raise_for_status()+ return datadiff --git a/mineru/doclib/config.py b/mineru/doclib/config.pydeleted file mode 100644index 6c157d4a..00000000--- a/mineru/doclib/config.py+++ /dev/null@@ -1,87 +0,0 @@-import os-import platform-import socket-import tempfile--from pydantic import BaseModel---def _uds_available() -> bool:- try:- socket.socket(socket.AF_UNIX, socket.SOCK_STREAM).close()- return True- except Exception:- return False---def _default_uds_path() -> str:- system = platform.system().lower()- if system not in ("windows", "darwin", "linux"):- raise RuntimeError(f"System [{system}] is not supported.")- if not _uds_available():- raise RuntimeError("Unix domain socket is not available.")- TEMP = tempfile.gettempdir() if system == "windows" else "/tmp"- return os.path.join(TEMP, "mineru.sock")---def _default_data_path() -> str:- HOME = os.path.expanduser("~")- return os.path.join(HOME, "MinerU")---def _default_log_path() -> str:- HOME = os.path.expanduser("~")- return os.path.join(HOME, "MinerU", "mineru.log")---def _default_db_path() -> str:- HOME = os.path.expanduser("~")- return os.path.join(HOME, "MinerU", "mineru.db")---class UDSConfig(BaseModel):- path: str = _default_uds_path()- permission: int = 0o600---class HTTPConfig(BaseModel):- enabled: bool = False- host: str = "127.0.0.1"- port: int = 15980- strict_port: bool = False- backlog: int = 128- timeout: int = 600---class LogConfig(BaseModel):- path: str = _default_log_path()- level: str = "info"- # max_bytes: 5242880 # 5MB 轮转- # backup_count: 3---class ServerConfig(BaseModel):- uds: UDSConfig = UDSConfig()- http: HTTPConfig = HTTPConfig()- log: LogConfig = LogConfig()- data_dir: str = _default_data_path()- ingest_workers: int = 2- parse_workers: int = 2- compaction_interval_sec: int = 3600---class SQLiteConfig(BaseModel):- path: str = _default_db_path()- mmap_size: int = 268435456 # 256 MB- cache_size: int = -20000 # 20 MB (negative = KB)- wal_autocheckpoint: int = 1000- journal_size_limit: int = 33_554_432 # 32 MB- temp_store: str = "memory"- synchronous: str = "NORMAL"---class Config(BaseModel):- """Configurations mainly needed before server was started."""-- server: ServerConfig = ServerConfig()- sqlite: SQLiteConfig = SQLiteConfig()diff --git a/mineru/doclib/constants.py b/mineru/doclib/constants.pynew file mode 100644index 00000000..2d5254e5--- /dev/null+++ b/mineru/doclib/constants.py@@ -0,0 +1,56 @@+"""Shared file type whitelists and constants."""++from __future__ import annotations++# ── file types ─────────────────────────────────────────────────────++TEXT_EXTENSIONS: set[str] = {+ "csv",+ "md",+ "markdown",+ "rst",+ "tex",+ "txt",+}++ALLOWED_EXTENSIONS: set[str] = {+ "pdf",+ "docx",+ "pptx",+ "xlsx",+ "html",+ "htm",+ *TEXT_EXTENSIONS,+ # Unsupported legacy Office formats:+ # "doc",+ # "xls",+ # "ppt",+ # Unsupported document/e-book/archive-like formats:+ # "epub",+ # "key",+ # "mobi",+ # "numbers",+ # "ods",+ # "odt",+ # "pages",+ # "rtf",+ # Unsupported mail formats:+ # "eml",+ # "mbox",+}++DEFAULT_EXCLUDE_PATTERNS: list[str] = [+ "*/Library/*",+ "*/.git/*",+ "*/node_modules/*",+ "*/vendor/*",+ "*/go/pkg/*",+ "*/__pycache__/*",+ "*/.venv/*",+ "*/miniconda3/*",+ "*/.nvm/*",+ "*/.docker/*",+ "*/target/*",+ "*/dist/*",+ "*/build/*",+]diff --git a/mineru/doclib/core/db.py b/mineru/doclib/core/db.pyindex 02f97b5b..de2d92bf 100644--- a/mineru/doclib/core/db.py+++ b/mineru/doclib/core/db.py@@ -6,9 +6,9 @@ from pathlib import Pathimport aiosqlite-from ..config import SQLiteConfig+from ...config import SQLiteConfig-SCHEMA_VERSION = 2+SCHEMA_VERSION = 1_MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"_CREATE_TABLES_SQL: list[str] = [] # filled by _load_init_sql()@@ -111,12 +111,13 @@ class DatabaseManager:"INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)", (key, value))+ now = _now_ms()for name, pattern in DEFAULT_EXCLUDE_RULES:await conn.execute(- "INSERT OR IGNORE INTO rules (name, rule_type, pattern, priority) "- "SELECT ?, 'exclude', ?, 0 "- "WHERE NOT EXISTS (SELECT 1 FROM rules WHERE rule_type='exclude' AND pattern=?)",- (name, pattern, pattern),+ "INSERT INTO exclude_rules (name, pattern, priority, created_at, updated_at) "+ "SELECT ?, ?, 0, ?, ? "+ "WHERE NOT EXISTS (SELECT 1 FROM exclude_rules WHERE pattern=?)",+ (name, pattern, now, now, pattern),)await conn.commit()@@ -200,7 +201,7 @@ async def _apply_migration(conn: aiosqlite.Connection, version: int) -> None: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("--")]+ lines = [line for line in raw.splitlines() if not line.strip().startswith("--")]sql = "\n".join(lines)for stmt in sql.split(";"):stmt = stmt.strip()diff --git a/mineru/doclib/core/file_io.py b/mineru/doclib/core/file_io.pyindex 41cbc244..0b93e020 100644--- a/mineru/doclib/core/file_io.py+++ b/mineru/doclib/core/file_io.py@@ -54,9 +54,6 @@ async def get_file_stat(filepath: str) -> dict:return {"size_bytes": st.st_size,"mtime_ms": int(st.st_mtime * 1000),- "birthtime_ms": int(st.st_birthtime * 1000)- if hasattr(st, "st_birthtime")- else int(st.st_ctime * 1000),}return await asyncio.to_thread(_stat)@@ -71,13 +68,11 @@ async def extract_metadata(filepath: str) -> dict:ext = Path(filepath).suffix.lower().lstrip(".")result = {- "mime_type": None,"page_count": None,"title": None,"author": None,"subject": None,"keywords": None,- "is_encrypted": 0,"is_scanned": 0,}@@ -116,8 +111,6 @@ async def _extract_pdf_meta(filepath: str, result: dict) -> None:result["subject"] = meta.get("Subject") or Noneresult["keywords"] = meta.get("Keywords") or None- # pypdfium2 doesn't expose is_encrypted directly;- # trying to access pages on an encrypted doc raises.finally:pdf.close()diff --git a/mineru/doclib/core/fts.py b/mineru/doclib/core/fts.pyindex 0a5b3030..b792e8e0 100644--- a/mineru/doclib/core/fts.py+++ b/mineru/doclib/core/fts.py@@ -2,11 +2,14 @@from __future__ import annotations+from typing import cast+try:import jiebaexcept ImportError:jieba = None # type: ignore[assignment]+from ...types import Tierfrom .db import DatabaseManagerFTS_SEP = ""@@ -47,7 +50,7 @@ class FTSManager:self,*,sha256: str,- tier: str,+ tier: Tier,text: str,title: str,author: str,@@ -83,11 +86,11 @@ class FTSManager:except Exception:return []- async def get_tier(self, sha256: str) -> str | None:+ async def get_tier(self, sha256: str) -> Tier | None:row = await self.db.fetchone("SELECT tier FROM fts_contents WHERE sha256=?", (sha256,))- return row["tier"] if row else None+ return cast(Tier, row["tier"]) if row else Noneasync def delete(self, sha256: str) -> None:await self.db.execute("DELETE FROM fts_contents WHERE sha256=?", (sha256,))diff --git a/mineru/doclib/migrations/001_init.sql b/mineru/doclib/migrations/001_init.sqlindex d95879e7..e79331f5 100644--- a/mineru/doclib/migrations/001_init.sql+++ b/mineru/doclib/migrations/001_init.sql@@ -8,7 +8,6 @@ CREATE TABLE IF NOT EXISTS files (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',@@ -26,9 +25,9 @@ CREATE INDEX IF NOT EXISTS idx_files_sha256_status ON files(sha256, scan_status)CREATE TABLE IF NOT EXISTS docs (sha256 TEXT PRIMARY KEY NOT NULL,size_bytes INTEGER NOT NULL,- mime_type TEXT,+ doc_type TEXT,page_count INTEGER,- lang TEXT,+ language TEXT,title TEXT,author TEXT,subject TEXT,diff --git a/mineru/doclib/migrations/002_add_parse_columns.sql b/mineru/doclib/migrations/002_add_parse_columns.sqldeleted file mode 100644index c616c0f0..00000000--- a/mineru/doclib/migrations/002_add_parse_columns.sql+++ /dev/null@@ -1,6 +0,0 @@--- 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/cleanup.py b/mineru/doclib/routes/cleanup.pydeleted file mode 100644index 03c585a6..00000000--- a/mineru/doclib/routes/cleanup.py+++ /dev/null@@ -1,41 +0,0 @@-"""Cleanup routes."""--from __future__ import annotations--from fastapi import APIRouter, Query, Request--router = APIRouter(tags=["cleanup"])--[email protected]("/cleanup/deleted")-async def cleanup_deleted(- request: Request,- older_than_days: int = Query(30, ge=1),- dry_run: bool = Query(True),-) -> dict:- state = request.state.app- count = await state.cleanup_svc.cleanup_deleted(- older_than_days=older_than_days,- dry_run=dry_run,- )- return {"deleted_files": count, "dry_run": dry_run}--[email protected]("/cleanup/orphans")-async def cleanup_orphans(- request: Request,- dry_run: bool = Query(True),-) -> dict:- state = request.state.app- count = await state.cleanup_svc.cleanup_orphans(dry_run=dry_run)- return {"orphan_docs": count, "dry_run": dry_run}--[email protected]("/cleanup/temp")-async def cleanup_temp(- request: Request,- older_than_days: int = Query(7, ge=1),-) -> dict:- state = request.state.app- count = await state.cleanup_svc.cleanup_temp_files(older_than_days=older_than_days)- return {"temp_files_removed": count}diff --git a/mineru/doclib/routes/config.py b/mineru/doclib/routes/config.pydeleted file mode 100644index dc3e1255..00000000--- a/mineru/doclib/routes/config.py+++ /dev/null@@ -1,145 +0,0 @@-"""Config routes: watch, exclude, parsing-rules, global config."""--from __future__ import annotations--from fastapi import APIRouter, Query, Request-from pydantic import BaseModel---class WatchRequest(BaseModel):- path: str- removable: bool = False- label: str | None = None---class RuleRequest(BaseModel):- pattern: str- name: str | None = None- tier: str | None = None- pages: str | None = None- remote: bool = False- priority: int = 0---router = APIRouter(tags=["config"])---# ── global config ────────────────────────────────────────────────--[email protected]("/config")-async def get_config(request: Request) -> dict:- state = request.state.app- cfg = await state.config_svc.get_all()- watches = await state.config_svc.list_watches()- rules = await state.config_svc.list_rules()- return {"config": cfg, "watches": watches, "rules": rules}--[email protected]("/config")-async def set_config(request: Request) -> dict:- """Set a single config key-value pair. Body: {key: str, value: str}."""- import json as _json-- body = await request.json()- key = body.get("key")- value = body.get("value")- if not key or value is None:- from fastapi.responses import JSONResponse-- return JSONResponse(- status_code=400,- content={"error": {"type": "invalid_request_error", "code": "invalid_request", "message": "Missing key or value"}},- )- state = request.state.app- await state.config_svc.set(key, str(value))- return {"key": key, "value": value}---# ── watch ────────────────────────────────────────────────────────--[email protected]("/config/watch")-async def list_watches(request: Request) -> dict:- state = request.state.app- watches = await state.config_svc.list_watches()- return {"watches": watches}--[email protected]("/config/watch")-async def add_watch(req: WatchRequest, request: Request) -> dict:- state = request.state.app- w = await state.config_svc.add_watch(- req.path,- removable=req.removable,- label=req.label,- )- return w--[email protected]("/config/watch")-async def remove_watch(request: Request, path: str = Query(...)) -> dict:- state = request.state.app- await state.config_svc.remove_watch(path)- return {"message": f"Watch removed: {path}"}---# ── exclude ──────────────────────────────────────────────────────--[email protected]("/config/exclude")-async def list_excludes(request: Request) -> dict:- state = request.state.app- rules = await state.config_svc.list_rules("exclude")- return {"rules": rules}--[email protected]("/config/exclude")-async def add_exclude(req: RuleRequest, request: Request) -> dict:- state = request.state.app- rid = await state.config_svc.add_rule(- req.name or "用户规则",- "exclude",- req.pattern,- priority=req.priority,- )- return {"id": rid}--[email protected]("/config/exclude/{rule_id}")-async def remove_exclude(rule_id: int, request: Request) -> dict:- state = request.state.app- await state.config_svc.remove_rule(rule_id)- return {"message": f"Exclude rule {rule_id} removed"}---# ── parsing-rules ────────────────────────────────────────────────--[email protected]("/config/parsing-rules")-async def list_parsing_rules(request: Request) -> dict:- state = request.state.app- rules = await state.config_svc.list_rules("parsing_rule")- return {"rules": rules}--[email protected]("/config/parsing-rules")-async def add_parsing_rule(req: RuleRequest, request: Request) -> dict:- state = request.state.app- rid = await state.config_svc.add_rule(- req.name or "规则",- "parsing_rule",- req.pattern,- tier=req.tier,- pages=req.pages,- remote=req.remote,- priority=req.priority,- )- return {"id": rid}--[email protected]("/config/parsing-rules/{rule_id}")-async def remove_parsing_rule(rule_id: int, request: Request) -> dict:- state = request.state.app- await state.config_svc.remove_rule(rule_id)- return {"message": f"Parsing rule {rule_id} removed"}diff --git a/mineru/doclib/routes/info.py b/mineru/doclib/routes/info.pydeleted file mode 100644index 030e49da..00000000--- a/mineru/doclib/routes/info.py+++ /dev/null@@ -1,62 +0,0 @@-"""Info route."""--from __future__ import annotations--from fastapi import APIRouter, Query, Request--router = APIRouter(tags=["info"])--[email protected]("/info")-async def info(request: Request, path: str = Query(...)) -> dict:- state = request.state.app-- file_row = await state.db.fetchone(- "SELECT * FROM files WHERE path=? AND scan_status='active'", (path,)- )- if file_row is None:- return {"path": path, "found": False}-- sha = file_row["sha256"]- doc = (- await state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha,))- if sha- else None- )-- # aggregate parse batches- parse_rows = (- await state.db.fetchall(- "SELECT * FROM parses WHERE sha256=? ORDER BY tier, created_at DESC", (sha,)- )- if sha- else []- )-- tiers: list[dict] = []- for pr in parse_rows:- tiers.append(- {- "tier": pr["tier"],- "status": pr["status"],- "pages": pr["pages"],- "done_at": pr["done_at"],- }- )-- return {- "path": file_row["path"],- "filename": file_row["filename"],- "ext": file_row["ext"],- "size_bytes": file_row["size_bytes"],- "mtime_ms": file_row["mtime_ms"],- "sha256": sha,- "scan_status": file_row["scan_status"],- "title": doc["title"] if doc else None,- "author": doc["author"] if doc else None,- "page_count": doc["page_count"] if doc else None,- "lang": doc["lang"] if doc else None,- "is_encrypted": doc["is_encrypted"] if doc else 0,- "tiers": tiers,- "found": True,- }diff --git a/mineru/doclib/routes/parse.py b/mineru/doclib/routes/parse.pydeleted file mode 100644index 7cb6dad1..00000000--- a/mineru/doclib/routes/parse.py+++ /dev/null@@ -1,117 +0,0 @@-"""Parse routes."""--from __future__ import annotations--import os--from fastapi import APIRouter, Query, Request--from ..types import ParseRequest--router = APIRouter(tags=["parse"])--[email protected]("/parse")-async def parse(req: ParseRequest, request: Request) -> dict:- state = request.state.app- result = await state.parse_svc.request_parse(- req.path,- tier=req.tier,- pages=req.pages,- force=req.force,- remote=req.remote,- remote_url=req.remote_url,- )- return result--[email protected]("/parse/status")-async def parse_status(- request: Request,- sha256: str = Query(...),- tier: str = Query(...),-) -> dict:- state = request.state.app- result = await state.parse_svc.get_parse_status(sha256, tier)- if result is None:- return {"sha256": sha256, "tier": tier, "status": "not_found"}- 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--[email protected]("/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:- """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"}-- # 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(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 all_pages:- return {"sha256": sha256, "tier": tier, "content": None, "error": "Content not found"}-- 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)- with open(output, "w", encoding="utf-8") as f:- f.write(content)- return {"sha256": sha256, "tier": tier, "output": os.path.abspath(output)}-- return {"sha256": sha256, "tier": tier, "content": content}diff --git a/mineru/doclib/routes/search.py b/mineru/doclib/routes/search.pydeleted file mode 100644index a39e6c6e..00000000--- a/mineru/doclib/routes/search.py+++ /dev/null@@ -1,36 +0,0 @@-"""Search routes."""--from __future__ import annotations--from fastapi import APIRouter, Query, Request--router = APIRouter(tags=["search"])--[email protected]("/search")-async def search(- request: Request,- q: str = Query(..., description="Search query"),- type: str | None = Query(None),- limit: int = Query(20, ge=1, le=200),- offset: int = Query(0, ge=0),-) -> dict:- state = request.state.app- results, total = await state.search_svc.search(- query=q,- file_type=type,- limit=limit,- offset=offset,- )- return {"results": results, "total": total, "query": q}--[email protected]("/find")-async def find(- request: Request,- q: str = Query(..., description="Filename search query"),- limit: int = Query(50, ge=1, le=500),-) -> dict:- state = request.state.app- results, total = await state.search_svc.search_filenames(query=q, limit=limit)- return {"results": results, "total": total, "query": q}diff --git a/mineru/doclib/routes/server.py b/mineru/doclib/routes/server.pydeleted file mode 100644index 9900d747..00000000--- a/mineru/doclib/routes/server.py+++ /dev/null@@ -1,93 +0,0 @@-"""Server routes: status and shutdown."""--from __future__ import annotations--import os-import signal-import time--from fastapi import APIRouter, Request--router = APIRouter(tags=["server"])--[email protected]("/server/status")-async def server_status(request: Request) -> dict:- state = request.state.app-- files_total = await state.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE scan_status='active'"- )- docs_total = await state.db.fetchone("SELECT COUNT(*) as cnt FROM docs")- parse_q = await state.parse_svc.get_queue_length()- ingest_q = await state.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND scan_status='active'"- )- watches = await state.config_svc.list_watches()- uptime = time.time() - state.start_time if hasattr(state, "start_time") else 0-- return {- "running": True,- "pid": state.pid,- "uptime_seconds": uptime,- "socket_path": getattr(state, "socket_path", ""),- "data_dir": getattr(state, "data_dir", ""),- "files_total": files_total["cnt"] if files_total else 0,- "docs_total": docs_total["cnt"] if docs_total else 0,- "parse_queue_length": parse_q,- "ingest_queue_length": ingest_q["cnt"] if ingest_q else 0,- "parse_server": _build_parse_server_status(),- "watch_count": len(watches),- "watches": [- {- "id": w["id"],- "path": w["path"],- "removable": bool(w["removable"]),- "watch_status": w["watch_status"],- }- 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:]--[email protected]("/shutdown")-async def shutdown(request: Request) -> dict:- """Gracefully shut down the server."""- # Signal shutdown in a background task so we can return a response first- import asyncio-- async def _shutdown() -> None:- await asyncio.sleep(0.1)- os.kill(os.getpid(), signal.SIGTERM)-- asyncio.create_task(_shutdown())- return {"message": "Server shutting down..."}---def _build_parse_server_status() -> dict:- from mineru.doclib.background.parse_server_health import get_health-- health = get_health()- return {- "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": {- "healthy": health.remote_healthy,- "supported_tiers": health.remote_supported_tiers,- },- }diff --git a/mineru/doclib/services/cleanup_svc.py b/mineru/doclib/services/cleanup_svc.pyindex 77c288a2..d65804ac 100644--- a/mineru/doclib/services/cleanup_svc.py+++ b/mineru/doclib/services/cleanup_svc.py@@ -7,10 +7,11 @@ import shutilimport timefrom ..core.db import DatabaseManager+from ..types import SCAN_STATUS_ACTIVE, SCAN_STATUS_DELETEDclass CleanupService:- def __init__(self, db: DatabaseManager, data_dir: str = "~/MinerU") -> None:+ def __init__(self, db: DatabaseManager, data_dir: str) -> None:self.db = dbself.data_dir = os.path.expanduser(data_dir)@@ -19,8 +20,9 @@ class CleanupService:async def find_orphan_docs(self) -> list[dict]:return await self.db.fetchall("SELECT d.* FROM docs d WHERE NOT EXISTS ("- " SELECT 1 FROM files f WHERE f.sha256 = d.sha256 AND f.scan_status = 'active'"- ")"+ " SELECT 1 FROM files f WHERE f.sha256 = d.sha256 AND f.scan_status = ?"+ ")",+ (SCAN_STATUS_ACTIVE,),)async def cleanup_orphans(self, dry_run: bool = True) -> int:@@ -48,16 +50,16 @@ class CleanupService:self, older_than_days: int = 30, dry_run: bool = True) -> int:row = await self.db.fetchone(- "SELECT COUNT(*) as cnt FROM files WHERE scan_status='deleted' "+ "SELECT COUNT(*) as cnt FROM files WHERE scan_status=? ""AND deleted_at < ?",- (_days_ago_ms(older_than_days),),+ (SCAN_STATUS_DELETED, _days_ago_ms(older_than_days)),)count = row["cnt"] if row else 0if not dry_run and count > 0:await self.db.execute(- "DELETE FROM files WHERE scan_status='deleted' AND deleted_at < ?",- (_days_ago_ms(older_than_days),),+ "DELETE FROM files WHERE scan_status=? AND deleted_at < ?",+ (SCAN_STATUS_DELETED, _days_ago_ms(older_than_days)),)await self.db.commit()await self.cleanup_orphans(dry_run=False)diff --git a/mineru/doclib/services/config_svc.py b/mineru/doclib/services/config_svc.pyindex 60403ed8..6ed9fb60 100644--- a/mineru/doclib/services/config_svc.py+++ b/mineru/doclib/services/config_svc.py@@ -8,7 +8,18 @@ import timeimport fnvhash+from ...types import Tierfrom ..core.db import DatabaseManager+from ..types import (+ RULE_TYPE_EXCLUDE,+ RULE_TYPE_PARSING_RULE,+ SCAN_STATUS_ACTIVE,+ SCAN_STATUS_DELETED,+ SCAN_STATUS_UNREACHABLE,+ WATCH_STATUS_UNREACHABLE,+ RuleType,+ WatchStatus,+)class ConfigService:@@ -44,10 +55,13 @@ class ConfigService:if wid >= 2**63:wid -= 2**64+ now = int(time.time() * 1000)await self.db.execute(- "INSERT OR REPLACE INTO watch_targets (id, path, label, removable) "- "VALUES (?, ?, ?, ?)",- (wid, path, label, int(removable)),+ "INSERT INTO watch_targets (id, path, label, removable, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?) "+ "ON CONFLICT(path) DO UPDATE SET "+ "label=excluded.label, removable=excluded.removable, updated_at=excluded.updated_at",+ (wid, path, label, int(removable), now, now),)return await self.db.fetchone("SELECT * FROM watch_targets WHERE id=?", (wid,))@@ -57,24 +71,46 @@ class ConfigService:)async def remove_watch(self, path: str) -> None:- await self.db.execute("DELETE FROM watch_targets WHERE path=?", (path,))+ watch = await self.db.fetchone("SELECT * FROM watch_targets WHERE path=?", (path,))+ if watch is None:+ return++ now = int(time.time() * 1000)+ await self.db.execute_atomic(+ [+ (+ "UPDATE files SET watch_id=NULL, updated_at=? "+ "WHERE watch_id=? AND scan_status IN (?, ?)",+ (now, watch["id"], SCAN_STATUS_ACTIVE, SCAN_STATUS_DELETED),+ ),+ (+ "UPDATE files SET watch_id=NULL, scan_status=?, deleted_at=?, updated_at=? "+ "WHERE watch_id=? AND scan_status=?",+ (SCAN_STATUS_DELETED, now, now, watch["id"], SCAN_STATUS_UNREACHABLE),+ ),+ ("DELETE FROM watch_targets WHERE id=?", (watch["id"],)),+ ]+ )- async def get_watches_by_status(self, watch_status: str) -> list[dict]:+ async def get_watches_by_status(self, watch_status: WatchStatus) -> list[dict]:return await self.db.fetchall("SELECT * FROM watch_targets WHERE watch_status=? AND enabled=1",(watch_status,),)- async def update_watch_status(self, watch_id: int, status: str) -> None:+ async def update_watch_status(self, watch_id: int, status: WatchStatus) -> None:+ now = int(time.time() * 1000)+ unreachable_at = now if status == WATCH_STATUS_UNREACHABLE else Noneawait self.db.execute(- "UPDATE watch_targets SET watch_status=? WHERE id=?", (status, watch_id)+ "UPDATE watch_targets SET watch_status=?, unreachable_at=?, updated_at=? WHERE id=?",+ (status, unreachable_at, now, watch_id),)async def update_watch_scan_stats(self, watch_id: int, file_count: int) -> None:now = int(time.time() * 1000)await self.db.execute(- "UPDATE watch_targets SET last_scan_at=?, last_scan_files=? WHERE id=?",- (now, file_count, watch_id),+ "UPDATE watch_targets SET last_scan_at=?, last_scan_files=?, updated_at=? WHERE id=?",+ (now, file_count, now, watch_id),)# ── rules ───────────────────────────────────────────────────@@ -82,48 +118,92 @@ class ConfigService:async def add_rule(self,name: str,- rule_type: str,+ rule_type: RuleType,pattern: str,- tier: str | None = None,+ tier: Tier | None = None,pages: str | None = None,remote: bool = False,priority: int = 0,) -> int:- return await self.db.execute_insert(- "INSERT INTO rules (name, rule_type, pattern, tier, pages, remote, priority) "- "VALUES (?, ?, ?, ?, ?, ?, ?)",- (name, rule_type, pattern, tier, pages, int(remote), priority),- )+ now = int(time.time() * 1000)+ if rule_type == RULE_TYPE_EXCLUDE:+ return await self.db.execute_insert(+ "INSERT INTO exclude_rules (name, pattern, priority, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?)",+ (name, pattern, priority, now, now),+ )+ if rule_type == RULE_TYPE_PARSING_RULE:+ return await self.db.execute_insert(+ "INSERT INTO parsing_rules (name, pattern, tier, pages, remote, priority, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",+ (name, pattern, tier, pages, int(remote), priority, now, now),+ )+ raise ValueError(f"Unsupported rule type: {rule_type}")- async def list_rules(self, rule_type: str | None = None) -> list[dict]:- if rule_type:+ async def list_rules(self, rule_type: RuleType | None = None) -> list[dict]:+ if rule_type == RULE_TYPE_EXCLUDE:+ return await self.db.fetchall(+ "SELECT id, name, ? AS rule_type, pattern, NULL AS tier, NULL AS pages, "+ "0 AS remote, enabled, priority, hit_count, created_at, updated_at "+ "FROM exclude_rules WHERE enabled=1 ORDER BY priority DESC",+ (RULE_TYPE_EXCLUDE,),+ )+ if rule_type == RULE_TYPE_PARSING_RULE:return await self.db.fetchall(- "SELECT * FROM rules WHERE rule_type=? AND enabled=1 ORDER BY priority DESC",- (rule_type,),+ "SELECT id, name, ? AS rule_type, pattern, tier, pages, remote, "+ "enabled, priority, hit_count, created_at, updated_at "+ "FROM parsing_rules WHERE enabled=1 ORDER BY priority DESC",+ (RULE_TYPE_PARSING_RULE,),)+ if rule_type is not None:+ raise ValueError(f"Unsupported rule type: {rule_type}")return await self.db.fetchall(- "SELECT * FROM rules WHERE enabled=1 ORDER BY rule_type, priority DESC"+ "SELECT id, name, ? AS rule_type, pattern, NULL AS tier, NULL AS pages, "+ "0 AS remote, enabled, priority, hit_count, created_at, updated_at "+ "FROM exclude_rules WHERE enabled=1 "+ "UNION ALL "+ "SELECT id, name, ? AS rule_type, pattern, tier, pages, remote, "+ "enabled, priority, hit_count, created_at, updated_at "+ "FROM parsing_rules WHERE enabled=1 "+ "ORDER BY rule_type, priority DESC",+ (RULE_TYPE_EXCLUDE, RULE_TYPE_PARSING_RULE),)- async def remove_rule(self, rule_id: int) -> None:- await self.db.execute("DELETE FROM rules WHERE id=?", (rule_id,))-- async def match_rules(self, file_path: str, rule_type: str) -> list[dict]:- rules = await self.db.fetchall(- "SELECT * FROM rules WHERE rule_type=? AND enabled=1 ORDER BY priority DESC",- (rule_type,),- )+ async def remove_rule(self, rule_id: int, rule_type: RuleType | None = None) -> None:+ if rule_type == RULE_TYPE_EXCLUDE:+ await self.db.execute("DELETE FROM exclude_rules WHERE id=?", (rule_id,))+ return+ if rule_type == RULE_TYPE_PARSING_RULE:+ await self.db.execute("DELETE FROM parsing_rules WHERE id=?", (rule_id,))+ return+ if rule_type is not None:+ raise ValueError(f"Unsupported rule type: {rule_type}")+ await self.db.execute("DELETE FROM exclude_rules WHERE id=?", (rule_id,))+ await self.db.execute("DELETE FROM parsing_rules WHERE id=?", (rule_id,))++ async def match_rules(self, file_path: str, rule_type: RuleType) -> list[dict]:+ rules = await self.list_rules(rule_type)+ table = _rule_table(rule_type)matched: list[dict] = []for rule in rules:if fnmatch.fnmatch(file_path, rule["pattern"]):matched.append(rule)await self.db.execute(- "UPDATE rules SET hit_count=hit_count+1 WHERE id=?", (rule["id"],)+ f"UPDATE {table} SET hit_count=hit_count+1, updated_at=? WHERE id=?",+ (int(time.time() * 1000), rule["id"]),)if matched:await self.db.commit()return matchedasync def is_path_excluded(self, file_path: str) -> bool:- matched = await self.match_rules(file_path, "exclude")+ matched = await self.match_rules(file_path, RULE_TYPE_EXCLUDE)return len(matched) > 0+++def _rule_table(rule_type: RuleType) -> str:+ if rule_type == RULE_TYPE_EXCLUDE:+ return "exclude_rules"+ if rule_type == RULE_TYPE_PARSING_RULE:+ return "parsing_rules"+ raise ValueError(f"Unsupported rule type: {rule_type}")diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex 30aeeb6c..7349baaf 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -8,6 +8,7 @@ import osimport timefrom dataclasses import dataclassfrom pathlib import Path+from typing import Literalfrom ...errors import MineruErrorfrom ...types import PageInfo, TIER_ORDER, Tier@@ -23,6 +24,10 @@ from ..types import (PARSE_STATUS_SUPERSEDED,RULE_TYPE_PARSING_RULE,SCAN_STATUS_ACTIVE,+ SCAN_STATUS_DELETED,+ SCAN_STATUS_UNREACHABLE,+ WATCH_STATUS_UNREACHABLE,+ FileInfo,)from .config_svc import ConfigService@@ -42,13 +47,25 @@ class ParseFailure(MineruError):MAX_FTS_CHARS = 30_000FTS_HEAD_HALF = 15_000+DOC_TYPE_BY_EXT = {+ "md": "markdown",+ "markdown": "markdown",+ "htm": "html",+ "html": "html",+}+++FileRefreshStatus = Literal["known", "new", "changed", "missing", "deleted", "unreachable", "unsupported", "error"]+@dataclass(frozen=True)-class DiscoverResult:- file: dict | None- changed: bool- needs_ingest: bool- unsupported: bool = False+class FileRefreshResult:+ file: FileInfo | None+ status: FileRefreshStatus++ @property+ def needs_ingest(self) -> bool:+ return self.file is not None and self.file.sha256 is None# ── range helpers ──────────────────────────────────────────────────@@ -171,28 +188,56 @@ class ParseService:# ── discovery / ingestion (shared) ──────────────────────- async def discover_file(self, path: str, watch_id: int | None = None) -> DiscoverResult:- """Discover a path and mark it for ingest if stat changed.+ async def refresh_file(+ self,+ path: str,+ watch_id: int | None = None,+ *,+ ensure_ingested: bool = False,+ ) -> FileRefreshResult:+ """Refresh one source path against the files table.- This is the lightweight path used by watch and by synchronous path- operations before they trust ``files.sha256``.+ This method owns file stat, DB row lookup, new/changed/known/missing/deleted+ classification, and optional synchronous ingest."""ext = Path(path).suffix.lower().lstrip(".")+ existing = await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))if ext not in ALLOWED_EXTENSIONS:- return DiscoverResult(file=None, changed=False, needs_ingest=False, unsupported=True)+ return FileRefreshResult(file=_file_info(existing), status="unsupported")- stat = await get_file_stat(path)+ try:+ stat = await get_file_stat(path)+ except FileNotFoundError:+ return await self._refresh_missing_file(path, existing)+ except PermissionError as exc:+ return await self._refresh_stat_error(existing, "file_permission_denied", str(exc))+ except OSError as exc:+ return await self._refresh_stat_error(existing, "stat_failed", str(exc))++ result = await self._refresh_existing_file_with_stat(path, ext, stat, existing, watch_id)+ if ensure_ingested and result.needs_ingest:+ row = await self.ingest_file(path, watch_id=watch_id)+ return FileRefreshResult(file=_file_info(row), status=result.status)+ return result++ async def _refresh_existing_file_with_stat(+ self,+ path: str,+ ext: str,+ stat: dict,+ existing: dict | None,+ watch_id: int | None,+ ) -> FileRefreshResult:now = _now_ms()filename = Path(path).name- existing = await self.db.fetchone("SELECT * FROM files WHERE path=? AND scan_status=?", (path, SCAN_STATUS_ACTIVE))- if existing:+ if existing and existing["scan_status"] == SCAN_STATUS_ACTIVE:unchanged = existing["mtime_ms"] == stat["mtime_ms"] and existing["size_bytes"] == stat["size_bytes"]if unchanged:- return DiscoverResult(file=existing, changed=False, needs_ingest=existing["sha256"] is None)+ return FileRefreshResult(file=_file_info(existing), status="known")await self.db.execute(- "UPDATE files SET filename=?, ext=?, size_bytes=?, mtime_ms=?, birthtime_ms=?, "+ "UPDATE files SET filename=?, ext=?, size_bytes=?, mtime_ms=?, ""sha256=NULL, watch_id=COALESCE(?, watch_id), locked_at=NULL, error_code=NULL, error_msg=NULL, updated_at=? ""WHERE id=?",(@@ -200,63 +245,105 @@ class ParseService:ext,stat["size_bytes"],stat["mtime_ms"],- stat["birthtime_ms"],watch_id,now,existing["id"],),)row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],))- return DiscoverResult(file=row, changed=True, needs_ingest=True)+ return FileRefreshResult(file=_file_info(row), status="changed")- existing_any_status = await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))- if existing_any_status:+ if existing:await self.db.execute(- "UPDATE files SET filename=?, ext=?, size_bytes=?, mtime_ms=?, birthtime_ms=?, "- "sha256=NULL, watch_id=?, scan_status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, "+ "UPDATE files SET filename=?, ext=?, size_bytes=?, mtime_ms=?, "+ "sha256=NULL, watch_id=COALESCE(?, watch_id), scan_status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, ""deleted_at=NULL, updated_at=? WHERE id=?",(filename,ext,stat["size_bytes"],stat["mtime_ms"],- stat["birthtime_ms"],watch_id,SCAN_STATUS_ACTIVE,now,- existing_any_status["id"],+ existing["id"],),)- row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing_any_status["id"],))- return DiscoverResult(file=row, changed=True, needs_ingest=True)+ row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],))+ return FileRefreshResult(file=_file_info(row), status="changed")file_id = await self.db.execute_insert("INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, "- "birthtime_ms, watch_id, first_seen_at, updated_at) "- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ "watch_id, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",(path,filename,ext,stat["size_bytes"],stat["mtime_ms"],- stat["birthtime_ms"],watch_id,now,now,),)row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (file_id,))- return DiscoverResult(file=row, changed=True, needs_ingest=True)+ return FileRefreshResult(file=_file_info(row), status="new")++ async def _refresh_missing_file(self, path: str, existing: dict | None) -> FileRefreshResult:+ if existing is None:+ return FileRefreshResult(file=None, status="missing")++ now = _now_ms()+ scan_status = SCAN_STATUS_DELETED+ deleted_at = now+ if existing["scan_status"] != SCAN_STATUS_DELETED and await self._is_missing_due_to_unreachable_watch(existing):+ scan_status = SCAN_STATUS_UNREACHABLE+ deleted_at = None++ await self.db.execute(+ "UPDATE files SET scan_status=?, locked_at=NULL, error_code=NULL, error_msg=NULL, deleted_at=?, updated_at=? WHERE id=?",+ (scan_status, deleted_at, now, existing["id"]),+ )+ row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],))+ status: FileRefreshStatus = "unreachable" if scan_status == SCAN_STATUS_UNREACHABLE else "deleted"+ return FileRefreshResult(file=_file_info(row), status=status)++ async def _is_missing_due_to_unreachable_watch(self, file_row: dict) -> bool:+ watch_id = file_row.get("watch_id")+ if watch_id is None:+ return False+ watch = await self.db.fetchone("SELECT * FROM watch_targets WHERE id=?", (watch_id,))+ if not watch or not watch.get("removable"):+ return False+ if watch["watch_status"] == WATCH_STATUS_UNREACHABLE:+ return True+ try:+ await get_file_stat(watch["path"])+ except OSError:+ if self.config_svc is not None:+ await self.config_svc.update_watch_status(watch_id, WATCH_STATUS_UNREACHABLE)+ return True+ return False++ async def _refresh_stat_error(self, existing: dict | None, error_code: str, error_msg: str) -> FileRefreshResult:+ if existing is None:+ return FileRefreshResult(file=None, status="error")++ now = _now_ms()+ await self.db.execute(+ "UPDATE files SET sha256=NULL, locked_at=NULL, error_code=?, error_msg=?, updated_at=? WHERE id=?",+ (error_code, error_msg[:500], now, existing["id"]),+ )+ row = await self.db.fetchone("SELECT * FROM files WHERE id=?", (existing["id"],))+ return FileRefreshResult(file=_file_info(row), status="error")async def ensure_ingested(self, path: str, watch_id: int | None = None) -> dict | None:"""Synchronously discover and ingest a source path when needed."""- discovered = await self.discover_file(path, watch_id=watch_id)- if discovered.file is None:+ refreshed = await self.refresh_file(path, watch_id=watch_id, ensure_ingested=True)+ if refreshed.file is None:return None- if not discovered.needs_ingest:- return discovered.file- return await self.ingest_file(path, watch_id=watch_id)+ return await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))async def ingest_file(self, path: str, watch_id: int | None = None) -> dict | None:"""Ingest a discovered file: SHA-256 + metadata + trigger default parse."""@@ -280,7 +367,7 @@ class ParseService:# to the existing doc without duplicating docs/parses.if existing_path:await self.db.execute(- "UPDATE files SET filename=?, ext=?, size_bytes=?, mtime_ms=?, birthtime_ms=?, "+ "UPDATE files SET filename=?, ext=?, size_bytes=?, mtime_ms=?, ""sha256=?, watch_id=COALESCE(?, watch_id), locked_at=NULL, error_code=NULL, error_msg=NULL, updated_at=? ""WHERE id=?",(@@ -288,7 +375,6 @@ class ParseService:ext,stat["size_bytes"],stat["mtime_ms"],- stat["birthtime_ms"],sha256,watch_id,now,@@ -298,15 +384,14 @@ class ParseService:else:await self.db.execute("INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, "- "birthtime_ms, sha256, watch_id, first_seen_at, updated_at) "- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ "sha256, watch_id, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",(path,filename,ext,stat["size_bytes"],stat["mtime_ms"],- stat["birthtime_ms"],sha256,watch_id,now,@@ -327,7 +412,6 @@ class ParseService:metadata_error_code = "metadata_failed"metadata_error_msg = str(exc)[:500] or "Failed to extract document metadata"metadata = {- "mime_type": None,"page_count": None,"title": None,"author": None,@@ -347,15 +431,14 @@ class ParseService:now = _now_ms()await self.db.execute("INSERT OR IGNORE INTO files (path, filename, ext, size_bytes, mtime_ms, "- "birthtime_ms, watch_id, first_seen_at, updated_at) "- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ "watch_id, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",(path,filename,ext,stat["size_bytes"],stat["mtime_ms"],- stat["birthtime_ms"],watch_id,now,now,@@ -363,13 +446,13 @@ class ParseService:)await self.db.execute(- "INSERT OR IGNORE INTO docs (sha256, size_bytes, mime_type, page_count, "+ "INSERT OR IGNORE INTO docs (sha256, size_bytes, doc_type, page_count, ""title, author, subject, keywords, error_code, error_msg, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",(sha256,stat["size_bytes"],- metadata["mime_type"],+ _doc_type_from_ext(ext),page_count,metadata["title"],metadata["author"],@@ -1008,6 +1091,14 @@ def _local_parse_server_url(mode: str, health: object) -> str | None:return None+def _file_info(row: dict | None) -> FileInfo | None:+ return FileInfo.model_validate(row) if row is not None else None++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+++def _doc_type_from_ext(ext: str) -> str:+ return DOC_TYPE_BY_EXT.get(ext, ext or "unknown")diff --git a/mineru/doclib/services/search_svc.py b/mineru/doclib/services/search_svc.pyindex ef290d53..e4d05a67 100644--- a/mineru/doclib/services/search_svc.py+++ b/mineru/doclib/services/search_svc.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom ..core.db import DatabaseManagerfrom ..core.fts import FTSManager, strip_sep+from ..types import SCAN_STATUS_ACTIVEclass SearchService:@@ -33,9 +34,9 @@ class SearchService:sql = ("SELECT f.*, d.title, d.author, d.page_count ""FROM files f JOIN docs d ON f.sha256 = d.sha256 "- f"WHERE f.sha256 IN ({placeholders}) AND f.scan_status = 'active'"+ f"WHERE f.sha256 IN ({placeholders}) AND f.scan_status = ?")- params = list(sha256s)+ params = [*sha256s, SCAN_STATUS_ACTIVE]if file_type:sql += " AND f.ext = ?"@@ -95,8 +96,8 @@ class SearchService:file_rows = await self.db.fetchall(f"SELECT f.*, d.title "f"FROM files f LEFT JOIN docs d ON f.sha256 = d.sha256 "- f"WHERE f.id IN ({placeholders}) AND f.scan_status = 'active'",- file_ids,+ f"WHERE f.id IN ({placeholders}) AND f.scan_status = ?",+ [*file_ids, SCAN_STATUS_ACTIVE],)files_by_id = {fr["id"]: fr for fr in file_rows}diff --git a/mineru/doclib/types.py b/mineru/doclib/types.pyindex 1b3dbc6d..357c1925 100644--- a/mineru/doclib/types.py+++ b/mineru/doclib/types.py@@ -134,7 +134,6 @@ class FileInfo(DoclibModel):ext: strsize_bytes: intmtime_ms: int- birthtime_ms: int | None = Nonesha256: str | None = Nonewatch_id: int | None = Nonescan_status: ScanStatus@@ -148,13 +147,13 @@ class FileInfo(DoclibModel):class DocInfo(DoclibModel):sha256: strsize_bytes: int- mime_type: str | None = None+ doc_type: str | None = Nonetitle: str | None = Noneauthor: str | None = Nonesubject: str | None = Nonekeywords: str | None = Nonepage_count: int | None = None- lang: str | None = None+ language: str | None = Noneis_scanned: int = 0meta_tier: Tier | None = Noneerror_code: str | None = Nonediff --git a/mineru/doclib/utils/__init__.py b/mineru/doclib/utils/__init__.pynew file mode 100644index 00000000..8b137891--- /dev/null+++ b/mineru/doclib/utils/__init__.py@@ -0,0 +1 @@+diff --git a/mineru/doclib/utils/route_utils.py b/mineru/doclib/utils/route_utils.pynew file mode 100644index 00000000..f11129fd--- /dev/null+++ b/mineru/doclib/utils/route_utils.py@@ -0,0 +1,66 @@+"""HTTP route metadata shared by doclib client and server implementations."""++from __future__ import annotations++from collections.abc import Callable, Sequence+from dataclasses import dataclass+from typing import Any, Literal, TypeVar++RouteMethod = Literal["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]++F = TypeVar("F", bound=Callable[..., Any])+_global_route_index = 0+++@dataclass(frozen=True, slots=True)+class RouteInfo:+ """HTTP route metadata attached to concrete doclib implementation methods."""++ method: RouteMethod+ path: str+ tags: tuple[str, ...] = ()+ index: int = 0++ def __post_init__(self) -> None:+ if self.method not in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}:+ raise ValueError(f"unsupported route method: {self.method}")+ if not self.path.startswith("/"):+ raise ValueError(f"route path must start with '/': {self.path}")+ if self.path != "/" and self.path.endswith("/"):+ raise ValueError(f"route path must not end with '/': {self.path}")+ if any(not tag for tag in self.tags):+ raise ValueError("route tags must not contain empty values")+ if self.index < 0:+ raise ValueError(f"route index must be non-negative: {self.index}")+++def route(method: RouteMethod, path: str, *, tags: Sequence[str] = ()) -> Callable[[F], F]:+ """Attach HTTP route metadata to a concrete client/server method."""++ global _global_route_index+ _global_route_index += 1+ route_info = RouteInfo(method=method, path=path, tags=tuple(tags), index=_global_route_index)++ def decorator(func: F) -> F:+ setattr(func, "_route_info", route_info)+ return func++ return decorator+++def get_route_info(func: Callable[..., Any]) -> RouteInfo:+ """Return route metadata attached by ``@route``."""++ target = getattr(func, "__func__", func)+ route_info = getattr(target, "_route_info", None)+ if not isinstance(route_info, RouteInfo):+ name = getattr(target, "__qualname__", repr(target))+ raise ValueError(f"{name} does not have doclib route metadata")+ return route_info+++def has_route_info(func: Callable[..., Any]) -> bool:+ """Return whether a callable has doclib route metadata."""++ target = getattr(func, "__func__", func)+ return isinstance(getattr(target, "_route_info", None), RouteInfo)diff --git a/mineru/parser/__init__.py b/mineru/parser/__init__.pyindex 1198fe95..d73e5cfa 100644--- a/mineru/parser/__init__.py+++ b/mineru/parser/__init__.py@@ -3,13 +3,17 @@ from __future__ import annotationsfrom pathlib import Path+from ..types import Tierfrom .api_client import MinerUApiParserfrom .base import DocumentParser, ParseResultfrom .html import HtmlParserfrom .office import DocxParser, PptxParser, XlsxParserfrom .pdf import PdfFlashParser, PdfHybridParser, PdfPipelineParser, PdfVlmParser+from .tier import PARSER_BACKENDS, backend_for_tier, resolve_tier_and_backend__all__ = [+ "backend_for_tier",+ "PARSER_BACKENDS","DocumentParser","DocxParser","HtmlParser",@@ -22,25 +26,38 @@ __all__ = ["PptxParser","XlsxParser","parse",+ "parse_async",+ "resolve_tier_and_backend",]-def parse(+def _build_parser(path: str | Path,*,- backend: str = "hybrid-auto-engine",- method: str = "auto",- lang: str = "ch",- formula_enable: bool = True,- table_enable: bool = True,- image_analysis: bool = True,+ tier: Tier | None = None,+ backend: str | None = None,+ language: str = "ch",+ ocr_mode: str = "auto",+ disable_table: bool = False,+ disable_formula: bool = False,+ disable_image_analysis: bool = False,server_url: str | None = None,- page_range: str = "",-) -> ParseResult:+ method: str | None = None,+ lang: str | None = None,+ table_enable: bool | None = None,+ formula_enable: bool | None = None,+ image_analysis: bool | None = None,+) -> DocumentParser:from ..utils.guess_suffix_or_lang import guess_suffix_by_pathpath = Path(path)suffix = guess_suffix_by_path(path)+ _, resolved_backend = resolve_tier_and_backend(tier=tier, backend=backend)+ resolved_ocr_mode = method or ocr_mode+ resolved_language = lang or language+ resolved_table_enable = (not disable_table) if table_enable is None else table_enable+ resolved_formula_enable = (not disable_formula) if formula_enable is None else formula_enable+ resolved_image_analysis = (not disable_image_analysis) if image_analysis is None else image_analysisif suffix in ("docx", "pptx", "xlsx"):parser_cls: type[DocumentParser] = {@@ -48,38 +65,110 @@ def parse("pptx": PptxParser,"xlsx": XlsxParser,}[suffix]- parser = parser_cls()+ return parser_cls()elif suffix in ("html", "htm"):- parser = HtmlParser()- elif backend == "pipeline":- parser = PdfPipelineParser(- backend=backend,- method=method,- lang=lang,- formula_enable=formula_enable,- table_enable=table_enable,+ return HtmlParser()+ elif resolved_backend == "pipeline":+ return PdfPipelineParser(+ backend=resolved_backend,+ method=resolved_ocr_mode,+ lang=resolved_language,+ formula_enable=resolved_formula_enable,+ table_enable=resolved_table_enable,)- elif backend.startswith("vlm-"):- parser = PdfVlmParser(- backend=backend,- formula_enable=formula_enable,- table_enable=table_enable,+ elif resolved_backend.startswith("vlm-"):+ return PdfVlmParser(+ backend=resolved_backend,+ formula_enable=resolved_formula_enable,+ table_enable=resolved_table_enable,server_url=server_url,- image_analysis=image_analysis,+ image_analysis=resolved_image_analysis,)- elif backend.startswith("hybrid-"):- parser = PdfHybridParser(- backend=backend,- method=method,- lang=lang,- formula_enable=formula_enable,- table_enable=table_enable,+ elif resolved_backend.startswith("hybrid-"):+ return PdfHybridParser(+ backend=resolved_backend,+ method=resolved_ocr_mode,+ lang=resolved_language,+ formula_enable=resolved_formula_enable,+ table_enable=resolved_table_enable,server_url=server_url,- image_analysis=image_analysis,+ image_analysis=resolved_image_analysis,)- elif backend == "flash":- parser = PdfFlashParser()+ elif resolved_backend == "flash":+ return PdfFlashParser()else:- raise ValueError(f"Unknown backend: {backend}")+ raise ValueError(f"Unknown backend: {resolved_backend}")++def parse(+ path: str | Path,+ *,+ tier: Tier | None = None,+ backend: str | None = None,+ language: str = "ch",+ ocr_mode: str = "auto",+ disable_table: bool = False,+ disable_formula: bool = False,+ disable_image_analysis: bool = False,+ server_url: str | None = None,+ page_range: str = "",+ method: str | None = None,+ lang: str | None = None,+ table_enable: bool | None = None,+ formula_enable: bool | None = None,+ image_analysis: bool | None = None,+) -> ParseResult:+ parser = _build_parser(+ path,+ tier=tier,+ backend=backend,+ language=language,+ ocr_mode=ocr_mode,+ disable_table=disable_table,+ disable_formula=disable_formula,+ disable_image_analysis=disable_image_analysis,+ server_url=server_url,+ method=method,+ lang=lang,+ table_enable=table_enable,+ formula_enable=formula_enable,+ image_analysis=image_analysis,+ )return parser.parse(path, page_range=page_range)+++async def parse_async(+ path: str | Path,+ *,+ tier: Tier | None = None,+ backend: str | None = None,+ language: str = "ch",+ ocr_mode: str = "auto",+ disable_table: bool = False,+ disable_formula: bool = False,+ disable_image_analysis: bool = False,+ server_url: str | None = None,+ page_range: str = "",+ method: str | None = None,+ lang: str | None = None,+ table_enable: bool | None = None,+ formula_enable: bool | None = None,+ image_analysis: bool | None = None,+) -> ParseResult:+ parser = _build_parser(+ path,+ tier=tier,+ backend=backend,+ language=language,+ ocr_mode=ocr_mode,+ disable_table=disable_table,+ disable_formula=disable_formula,+ disable_image_analysis=disable_image_analysis,+ server_url=server_url,+ method=method,+ lang=lang,+ table_enable=table_enable,+ formula_enable=formula_enable,+ image_analysis=image_analysis,+ )+ return await parser.parse_async(path, page_range=page_range)diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.pyindex 23b434ef..b28e2ca6 100644--- a/mineru/parser/api_client.py+++ b/mineru/parser/api_client.py@@ -2,8 +2,8 @@"""DocumentParser implementation for the MinerU v1 REST API.``MinerUApiParser`` extends ``DocumentParser`` and talks to a v1 API-server (local or cloud). All :class:`DocumentParser` constructor-parameters are mapped to the v1 API job payload automatically.+server (local or cloud). It exposes API tier semantics directly and+does not expose parser backend selection."""from __future__ import annotations@@ -13,19 +13,8 @@ import json as _jsonfrom pathlib import Pathfrom typing import Any-from mineru.types import PageInfo-from .base import DocumentParser, ParseResult---def _tier_to_backend(tier: str) -> str:- """Map NEXT-API tier values to api_parser backend names."""- mapping: dict[str, str] = {- "standard": "pipeline",- "pro": "vlm",- "auto": "auto",- }- return mapping.get(tier, "pipeline")+from ..types import PageInfo, Tierclass MinerUApiParser(DocumentParser):@@ -34,24 +23,21 @@ class MinerUApiParser(DocumentParser):Works with local-server, LAN, and cloud (mineru.net) deployments::# local deployment — uses ``local`` source, no upload needed- parser = MinerUApiParser(api_url="http://localhost:8000/api", backend="pipeline")+ parser = MinerUApiParser(api_url="http://localhost:8000/api", tier="standard")# cloud (paid)parser = MinerUApiParser(api_url="https://mineru.net/api", api_key="msk_...",- backend="vlm",+ tier="pro",)result = parser.parse("report.pdf")print(result.markdown())- Constructor parameters (matching :class:`DocumentParser`):+ Constructor parameters:- - ``backend`` → v1 ``tier`` (``"standard"`` / ``"pro"`` / ``"auto"``)- - ``method`` → v1 ``ocr`` (``"auto"`` / ``"ocr"`` / ``"txt"``)- - ``image_analysis`` → mapped directly- - ``return_md`` / ``return_middle_json`` / ``return_content_list`` /- ``return_images`` → v1 ``output_formats``+ - ``tier`` → v1 ``tier`` (``"standard"`` / ``"pro"``); ``None`` omits the field+ - ``page_range`` → per-file v1 ``page_range``"""def __init__(@@ -59,16 +45,12 @@ class MinerUApiParser(DocumentParser):*,api_url: str,api_key: str | None = None,- tier: str | None = None,- method: str = "auto",- image_analysis: bool = True,+ tier: Tier | None = None,) -> None:self._base = api_url.rstrip("/")self._api_key = api_keyself._local = self._is_localhost(self._base)- self.backend = _tier_to_backend(tier) if tier else "auto"- self.method = method- self.image_analysis = image_analysis+ self.tier = tier# ── DocumentParser interface ─────────────────────────────────────@@ -81,7 +63,9 @@ class MinerUApiParser(DocumentParser):job = self._do_parse(payload)return self._build_result(job, file_path.name)- async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:+ async def parse_async(+ self, path: str | Path, *, page_range: str = ""+ ) -> ParseResult:file_path = Path(path)if not file_path.exists():raise FileNotFoundError(file_path)@@ -101,37 +85,20 @@ class MinerUApiParser(DocumentParser):file_id = self._upload(file_path)source = {"type": "file_id", "file_id": file_id}- options: dict[str, Any] = {- "ocr": self._ocr_mode(),- "image_analysis": self.image_analysis,- }+ file_entry: dict[str, Any] = {"source": source}if page_range:- options["page_range"] = page_range+ file_entry["page_range"] = page_range- return {- "files": [{"source": source, "options": options}],- "tier": self._tier(),+ payload: dict[str, Any] = {+ "files": [file_entry],"output_formats": self._output_formats(),}-- def _tier(self) -> str:- if self.backend == "pipeline":- return "standard"- if self.backend.startswith("vlm"):- return "pro"- if self.backend.startswith("html"):- return "auto"- return "auto"-- def _ocr_mode(self) -> str:- if self.method == "ocr":- return "true"- if self.method == "txt":- return "txt"- return "auto"+ if self.tier is not None:+ payload["tier"] = self.tier+ return payloaddef _output_formats(self) -> list[str]:- return ["json"]+ return ["middle_json"]# ── HTTP helpers ─────────────────────────────────────────────────@@ -162,7 +129,11 @@ class MinerUApiParser(DocumentParser):if "error" in data:err = data["error"]raise _V1APIError(err.get("code", "unknown"), err.get("message", str(err)))- if "detail" in data and isinstance(data["detail"], dict) and "error" in data["detail"]:+ if (+ "detail" in data+ and isinstance(data["detail"], dict)+ and "error" in data["detail"]+ ):err = data["detail"]["error"]raise _V1APIError(err.get("code", "unknown"), err.get("message", str(err)))return data@@ -198,7 +169,10 @@ class MinerUApiParser(DocumentParser):r2 = cli.put(upload_url, content=fh.read())self._check(r2)- r3 = cli.post(f"{self._base}/v1/uploads/{resp['id']}/complete", headers=self._headers())+ r3 = cli.post(+ f"{self._base}/v1/uploads/{resp['id']}/complete",+ headers=self._headers(),+ )resp3 = self._check(r3)return resp3["file"]["id"]@@ -231,7 +205,10 @@ class MinerUApiParser(DocumentParser):r2 = await cli.put(upload_url, content=data)self._check(r2)- r3 = await cli.post(f"{self._base}/v1/uploads/{resp['id']}/complete", headers=self._headers())+ r3 = await cli.post(+ f"{self._base}/v1/uploads/{resp['id']}/complete",+ headers=self._headers(),+ )resp3 = self._check(r3)return resp3["file"]["id"]@@ -242,11 +219,13 @@ class MinerUApiParser(DocumentParser):payload["wait"] = 600with httpx.Client(timeout=httpx.Timeout(660, connect=30)) as cli:- r = cli.post(f"{self._base}/v1/parse/jobs", headers=self._headers(), json=payload)+ r = cli.post(+ f"{self._base}/v1/parse/jobs", headers=self._headers(), json=payload+ )job = self._check(r)- if job.get("status") not in ("completed", "partial", "failed"):- # poll if wait timed out- job = self._poll(cli, job["job_id"])+ if job.get("status") not in ("completed", "partial", "failed", "canceled"):+ # poll if wait timed out+ job = self._poll(cli, job["job_id"])return jobasync def _async_do_parse(self, payload: dict[str, Any]) -> dict[str, Any]:@@ -254,10 +233,12 @@ class MinerUApiParser(DocumentParser):payload["wait"] = 600async with httpx.AsyncClient(timeout=httpx.Timeout(660, connect=30)) as cli:- r = await cli.post(f"{self._base}/v1/parse/jobs", headers=self._headers(), json=payload)+ r = await cli.post(+ f"{self._base}/v1/parse/jobs", headers=self._headers(), json=payload+ )job = self._check(r)- if job.get("status") not in ("completed", "partial", "failed"):- job = await self._async_poll(cli, job["job_id"])+ if job.get("status") not in ("completed", "partial", "failed", "canceled"):+ job = await self._async_poll(cli, job["job_id"])return jobdef _poll(self, cli: Any, job_id: str) -> dict[str, Any]:@@ -268,7 +249,7 @@ class MinerUApiParser(DocumentParser):time.sleep(delay)r = cli.get(f"{self._base}/v1/parse/jobs/{job_id}", headers=self._headers())job = self._check(r)- if job.get("status") in ("completed", "partial", "failed"):+ if job.get("status") in ("completed", "partial", "failed", "canceled"):return jobdelay = min(delay * 2, 30)raise _V1APIError("timeout", f"Job {job_id} did not complete within timeout")@@ -279,9 +260,11 @@ class MinerUApiParser(DocumentParser):delay = 2for _ in range(150):await asyncio.sleep(delay)- r = await cli.get(f"{self._base}/v1/parse/jobs/{job_id}", headers=self._headers())+ r = await cli.get(+ f"{self._base}/v1/parse/jobs/{job_id}", headers=self._headers()+ )job = self._check(r)- if job.get("status") in ("completed", "partial", "failed"):+ if job.get("status") in ("completed", "partial", "failed", "canceled"):return jobdelay = min(delay * 2, 30)raise _V1APIError("timeout", f"Job {job_id} did not complete within timeout")@@ -291,7 +274,9 @@ class MinerUApiParser(DocumentParser):def _build_result(self, job: dict[str, Any], file_name: str) -> ParseResult:return _parse_result_from_job(job, file_name, self)- async def _async_build_result(self, job: dict[str, Any], file_name: str) -> ParseResult:+ async def _async_build_result(+ self, job: dict[str, Any], file_name: str+ ) -> ParseResult:return await _async_parse_result_from_job(job, file_name, self)@@ -328,7 +313,9 @@ def _mime_type(path: Path) -> str:}.get(ext, "application/octet-stream")-def _parse_result_from_job(job: dict[str, Any], file_name: str, parser: MinerUApiParser) -> ParseResult:+def _parse_result_from_job(+ job: dict[str, Any], file_name: str, parser: MinerUApiParser+) -> ParseResult:files = job.get("files", [])outputs: dict[str, Any] = {}if files and files[0].get("output_files"):@@ -336,17 +323,14 @@ def _parse_result_from_job(job: dict[str, Any], file_name: str, parser: MinerUApmid_json = _download_json(parser, outputs)- from mineru.version import __version__-return ParseResult(pages=_pages_from_middle_json(mid_json),- _backend=parser.backend,- _version_name=f"v1-api-{__version__}",- _file_name=file_name,)-async def _async_parse_result_from_job(job: dict[str, Any], file_name: str, parser: MinerUApiParser) -> ParseResult:+async def _async_parse_result_from_job(+ job: dict[str, Any], file_name: str, parser: MinerUApiParser+) -> ParseResult:files = job.get("files", [])outputs: dict[str, Any] = {}if files and files[0].get("output_files"):@@ -354,18 +338,15 @@ async def _async_parse_result_from_job(job: dict[str, Any], file_name: str, parsmid_json = await _async_download_json(parser, outputs)- from mineru.version import __version__-return ParseResult(pages=_pages_from_middle_json(mid_json),- _backend=parser.backend,- _version_name=f"v1-api-{__version__}",- _file_name=file_name,)-def _download_json(parser: MinerUApiParser, outputs: dict[str, Any]) -> dict[str, Any] | None:- ref = outputs.get("json") or outputs.get("json_")+def _download_json(+ parser: MinerUApiParser, outputs: dict[str, Any]+) -> dict[str, Any] | None:+ ref = outputs.get("middle_json") or outputs.get("json") or outputs.get("json_")if not ref or not ref.get("file_id"):return Nonetry:@@ -375,8 +356,10 @@ def _download_json(parser: MinerUApiParser, outputs: dict[str, Any]) -> dict[strreturn None-async def _async_download_json(parser: MinerUApiParser, outputs: dict[str, Any]) -> dict[str, Any] | None:- ref = outputs.get("json") or outputs.get("json_")+async def _async_download_json(+ parser: MinerUApiParser, outputs: dict[str, Any]+) -> dict[str, Any] | None:+ ref = outputs.get("middle_json") or outputs.get("json") or outputs.get("json_")if not ref or not ref.get("file_id"):return Nonetry:@@ -390,7 +373,9 @@ def _download_bytes(parser: MinerUApiParser, file_id: str) -> bytes:import httpxwith httpx.Client(timeout=httpx.Timeout(120, connect=30)) as cli:- r = cli.get(f"{parser._base}/v1/files/{file_id}/content", headers=parser._headers())+ r = cli.get(+ f"{parser._base}/v1/files/{file_id}/content", headers=parser._headers()+ )parser._check(r)return r.content@@ -399,7 +384,9 @@ async def _async_download_bytes(parser: MinerUApiParser, file_id: str) -> bytes:import httpxasync with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30)) as cli:- r = await cli.get(f"{parser._base}/v1/files/{file_id}/content", headers=parser._headers())+ r = await cli.get(+ f"{parser._base}/v1/files/{file_id}/content", headers=parser._headers()+ )parser._check(r)return r.content@@ -416,7 +403,12 @@ def _pages_from_middle_json(mid_json: dict[str, Any] | list[Any] | None) -> listif isinstance(pages, dict):raw_pages = pages.get("preproc_blocks", [])return [- PageInfo(page_idx=i, page_size=(raw.get("width", 0), raw.get("height", 0)) if isinstance(raw, dict) else (0, 0))+ PageInfo(+ page_idx=i,+ page_size=(raw.get("width", 0), raw.get("height", 0))+ if isinstance(raw, dict)+ else (0, 0),+ )for i, raw in enumerate(raw_pages)]return []diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex e10b7c6a..514163cd 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -30,7 +30,13 @@ from fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.responses import JSONResponse, StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field-# ── literal type aliases (no enum imports) ──────────────────────────+from ..types import Tier+from .tier import PARSER_BACKENDS+from .tier import resolve_tier_and_backend++_API_SERVER_BACKENDS = tuple(backend for backend in PARSER_BACKENDS if backend != "flash")++# ── literal type aliases ────────────────────────────────────────────JobStatus = Literal["queued", "running", "completed", "partial", "failed", "canceled"]"""Job lifecycle states."""@@ -41,14 +47,11 @@ FileStatus = Literal["queued", "running", "completed", "failed"]UploadStatus = Literal["pending", "completed", "cancelled", "expired"]"""Upload lifecycle states."""-Tier = Literal["auto", "standard", "pro"]-"""Pre-configured parsing tier."""-OutputFormat = Literal["markdown",- "json",+ "middle_json","content_list",- "content_list_v2",+ "structured_content","images","html","latex",@@ -63,9 +66,6 @@ OutputFormatReqToken = Literal["html", "latex", "docx"]SourceType = Literal["file_id", "url", "inline", "local"]"""File source types."""-OcrMode = Literal["auto", "true", "false", "txt"]-"""OCR mode: auto-detect, force-on, force-off, text-extraction-only."""-AccessLevel = Literal["anonymous", "registered"]"""Account access level determined by API Key."""@@ -136,7 +136,7 @@ class HealthResponse(BaseModel):model_config = _PYDANTIC_CONFIGstatus: str = "ok"version: str- backend_version: str | None = None+ parser_version: str | None = Nonemodels: ModelHealthStatus | None = Nonefeatures: HealthFeatures = Field(default_factory=lambda: HealthFeatures(sse=False, webhook=False))@@ -284,20 +284,10 @@ FileSource = Annotated[]-# ── Job options ──────────────────────────────────────────────────────---class FileOptions(BaseModel):- model_config = _PYDANTIC_CONFIG- ocr: OcrMode = "auto"- image_analysis: bool = True- page_range: str | None = None--class JobFileEntry(BaseModel):model_config = _PYDANTIC_CONFIGsource: FileSource- options: FileOptions | None = None+ page_range: str | None = Noneclass CallbackConfig(BaseModel):@@ -309,7 +299,7 @@ class CallbackConfig(BaseModel):class CreateJobRequest(BaseModel):model_config = _PYDANTIC_CONFIGfiles: list[JobFileEntry] = Field(min_length=1)- tier: Tier = "auto"+ tier: Tier | None = Noneoutput_formats: list[OutputFormat] = ["markdown"]wait: int = Field(default=0, ge=0)callback: CallbackConfig | None = None@@ -332,19 +322,17 @@ class JobProgress(BaseModel):total: int = 0-class FileMetadata(BaseModel):+class FileParseInfo(BaseModel):model_config = _PYDANTIC_CONFIG- pages: int | None = Nonemodel_used: str | None = None- processing_time_ms: int | None = None- backend_version: str | None = None+ duration_ms: int | None = None+ parser_version: str | None = Noneclass OutputFileRef(BaseModel):model_config = _PYDANTIC_CONFIGfile_id: strbytes: int- content: str | dict[str, Any] | None = None # inline for markdown in sync responseclass ImageOutputRef(BaseModel):@@ -355,15 +343,13 @@ class ImageOutputRef(BaseModel):class OutputFiles(BaseModel):- """Per-file output artifacts. `content` is only populated for- `markdown` in sync (wait) responses; all other formats carry only- `file_id` + `bytes` and must be downloaded via the Files API."""+ """Per-file output artifacts. Content is downloaded via the Files API."""- model_config = ConfigDict(extra="forbid", populate_by_name=True)+ model_config = _PYDANTIC_CONFIGmarkdown: OutputFileRef | None = None- json_: OutputFileRef | None = Field(default=None, serialization_alias="json", validation_alias="json")+ middle_json: OutputFileRef | None = Nonecontent_list: OutputFileRef | None = None- content_list_v2: OutputFileRef | None = None+ structured_content: OutputFileRef | None = Nonehtml: OutputFileRef | None = Nonelatex: OutputFileRef | None = Nonedocx: OutputFileRef | None = None@@ -373,10 +359,11 @@ class OutputFiles(BaseModel):class JobFileResult(BaseModel):model_config = _PYDANTIC_CONFIG- file_id: str+ file_id: str | None = Nonename: str+ page_range: strstatus: FileStatus- metadata: FileMetadata | None = None+ parse: FileParseInfo | None = Noneoutput_files: OutputFiles | None = Noneerror: ErrorDetail | None = None@@ -401,7 +388,7 @@ class JobListItem(BaseModel):job_id: strstatus: JobStatuscreated_at: str- files_count: int+ file_count: intclass JobListResponse(BaseModel):@@ -582,7 +569,9 @@ class FileStore:status_code=404,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="upload_not_found", message=f"Upload {upload_id} not found"+ type="invalid_request_error",+ code="upload_not_found",+ message=f"Upload {upload_id} not found",),).model_dump(by_alias=True),)@@ -595,7 +584,9 @@ class FileStore:status_code=409,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="upload_not_ready", message="Upload bytes not yet received"+ type="invalid_request_error",+ code="upload_not_ready",+ message="Upload bytes not yet received",),).model_dump(by_alias=True),)@@ -608,7 +599,9 @@ class FileStore:status_code=409,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="upload_already_terminal", message="Upload is already completed"+ type="invalid_request_error",+ code="upload_already_terminal",+ message="Upload is already completed",),).model_dump(by_alias=True),)@@ -617,7 +610,9 @@ class FileStore:status_code=409,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="upload_already_terminal", message=f"Upload is {rec.status}"+ type="invalid_request_error",+ code="upload_already_terminal",+ message=f"Upload is {rec.status}",),).model_dump(by_alias=True),)@@ -630,14 +625,22 @@ class FileStore:raise HTTPException(status_code=400,detail=ErrorResponse(- error=ErrorDetail(type="invalid_request_error", code="file_hash_mismatch", message="SHA-256 mismatch"),+ error=ErrorDetail(+ type="invalid_request_error",+ code="file_hash_mismatch",+ message="SHA-256 mismatch",+ ),).model_dump(by_alias=True),)if rec.sha256sum and rec.sha256sum != actual_sha:raise HTTPException(status_code=400,detail=ErrorResponse(- error=ErrorDetail(type="invalid_request_error", code="file_hash_mismatch", message="SHA-256 mismatch"),+ error=ErrorDetail(+ type="invalid_request_error",+ code="file_hash_mismatch",+ message="SHA-256 mismatch",+ ),).model_dump(by_alias=True),)@@ -672,7 +675,9 @@ class FileStore:status_code=409,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="upload_already_terminal", message=f"Upload is {rec.status}"+ type="invalid_request_error",+ code="upload_already_terminal",+ message=f"Upload is {rec.status}",),).model_dump(by_alias=True),)@@ -687,7 +692,9 @@ class FileStore:status_code=409,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="upload_already_terminal", message=f"Upload is {rec.status}"+ type="invalid_request_error",+ code="upload_already_terminal",+ message=f"Upload is {rec.status}",),).model_dump(by_alias=True),)@@ -742,7 +749,11 @@ class FileStore:raise HTTPException(status_code=404,detail=ErrorResponse(- error=ErrorDetail(type="invalid_request_error", code="file_not_found", message=f"File {file_id} not found"),+ error=ErrorDetail(+ type="invalid_request_error",+ code="file_not_found",+ message=f"File {file_id} not found",+ ),).model_dump(by_alias=True),)return rec@@ -766,7 +777,9 @@ class FileStore:status_code=403,detail=ErrorResponse(error=ErrorDetail(- type="permission_error", code="feature_requires_api_key", message="Source files cannot be downloaded"+ type="permission_error",+ code="feature_requires_api_key",+ message="Source files cannot be downloaded",),).model_dump(by_alias=True),)@@ -774,7 +787,11 @@ class FileStore:raise HTTPException(status_code=500,detail=ErrorResponse(- error=ErrorDetail(type="api_error", code="internal_error", message="File has no sha256sum"),+ error=ErrorDetail(+ type="api_error",+ code="internal_error",+ message="File has no sha256sum",+ ),).model_dump(by_alias=True),)return self.read_blob(rec.sha256sum)@@ -784,7 +801,11 @@ class FileStore:raise HTTPException(status_code=404,detail=ErrorResponse(- error=ErrorDetail(type="invalid_request_error", code="file_not_found", message=f"File {file_id} not found"),+ error=ErrorDetail(+ type="invalid_request_error",+ code="file_not_found",+ message=f"File {file_id} not found",+ ),).model_dump(by_alias=True),)del self._files[file_id]@@ -866,7 +887,14 @@ _SUPPORTED_SUFFIXES: dict[str, str] = {".htm": "html",}-_OUTPUT_FORMATS_LOCAL = {"markdown", "json", "content_list", "content_list_v2", "images", "zip"}+_OUTPUT_FORMATS_LOCAL = {+ "markdown",+ "middle_json",+ "content_list",+ "structured_content",+ "images",+ "zip",+}@dataclass@@ -876,7 +904,7 @@ class _JobRecord:created_at: str = ""started_at: str | None = Nonefinished_at: str | None = None- tier: Tier = "auto"+ tier: Tier = "standard"output_formats: list[OutputFormat] = None # type: ignore[assignment]progress: JobProgress | None = Nonefiles: list[JobFileResult] = None # type: ignore[assignment]@@ -906,6 +934,8 @@ class JobStore:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")def create(self, req: CreateJobRequest, file_store: FileStore) -> _JobRecord:+ if req.tier is None:+ raise ValueError("CreateJobRequest.tier must be resolved before job creation")job_id = self._new_job_id()now = self._now()rec = _JobRecord(@@ -922,11 +952,11 @@ class JobStore:)for entry in req.files:name = _source_name(entry.source, file_store)- fid = entry.source.file_id if isinstance(entry.source, FileIdSource) else ""rec.files.append(JobFileResult(- file_id=fid,+ file_id=entry.source.file_id if isinstance(entry.source, FileIdSource) else None,name=name,+ page_range=entry.page_range or "",status="queued",))@@ -940,7 +970,11 @@ class JobStore:raise HTTPException(status_code=404,detail=ErrorResponse(- error=ErrorDetail(type="invalid_request_error", code="job_not_found", message=f"Job {job_id} not found"),+ error=ErrorDetail(+ type="invalid_request_error",+ code="job_not_found",+ message=f"Job {job_id} not found",+ ),).model_dump(by_alias=True),)return rec@@ -952,7 +986,9 @@ class JobStore:status_code=409,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="job_already_terminal", message=f"Job is {rec.status}"+ type="invalid_request_error",+ code="job_already_terminal",+ message=f"Job is {rec.status}",),).model_dump(by_alias=True),)@@ -984,7 +1020,15 @@ class JobStore:breakpage = recs[start : start + limit]return JobListResponse(- data=[JobListItem(job_id=r.id, status=r.status, created_at=r.created_at, files_count=len(r.files)) for r in page],+ data=[+ JobListItem(+ job_id=r.id,+ status=r.status,+ created_at=r.created_at,+ file_count=len(r.files),+ )+ for r in page+ ],first_id=page[0].id if page else None,last_id=page[-1].id if page else None,has_more=(start + limit) < len(recs),@@ -1008,8 +1052,7 @@ class JobStore:def usage(self, access_level: AccessLevel) -> UsageResponse:completed = sum(1 for j in self._jobs.values() if j.status in ("completed", "partial"))pages = sum(- sum((fr.metadata and fr.metadata.pages) or 0 for fr in j.files if fr.status == "completed")- for j in self._jobs.values()+ sum(_count_pages_in_range(fr.page_range) for fr in j.files if fr.status == "completed") for j in self._jobs.values())return UsageResponse(access_level=access_level,@@ -1047,6 +1090,51 @@ def _source_name(source: FileSource, file_store: FileStore | None = None) -> strreturn "unknown"+def _compact_page_numbers(page_numbers: list[int]) -> str:+ if not page_numbers:+ return ""+ ordered = sorted(set(page_numbers))+ ranges: list[str] = []+ start = prev = ordered[0]+ for page in ordered[1:]:+ if page == prev + 1:+ prev = page+ continue+ ranges.append(str(start) if start == prev else f"{start}~{prev}")+ start = prev = page+ ranges.append(str(start) if start == prev else f"{start}~{prev}")+ return ",".join(ranges)+++def _page_range_from_result_pages(pages: list[Any]) -> str:+ page_numbers: list[int] = []+ for i, page in enumerate(pages):+ page_idx = getattr(page, "page_idx", i)+ if isinstance(page_idx, int):+ page_numbers.append(page_idx + 1)+ return _compact_page_numbers(page_numbers)+++def _count_pages_in_range(page_range: str) -> int:+ total = 0+ for part in page_range.split(","):+ token = part.strip()+ if not token:+ continue+ if "~" not in token:+ total += 1+ continue+ left, right = token.split("~", 1)+ try:+ start = int(left)+ end = int(right)+ except ValueError:+ total += 1+ continue+ total += max(0, end - start + 1)+ return total++async def _extract_bytes(source: FileSource, file_store: FileStore, *, url_timeout: int = 60) -> bytes:if isinstance(source, FileIdSource):rec = file_store.get_file(source.file_id)@@ -1076,8 +1164,13 @@ async def _run_job(rec: _JobRecord,req: CreateJobRequest,file_store: FileStore,- vlm_available: bool,*,+ server_backend: str,+ language: str,+ ocr_mode: str,+ table_enable: bool,+ formula_enable: bool,+ image_analysis: bool,url_timeout: int = 60,) -> None:rec.status = "running"@@ -1089,6 +1182,7 @@ async def _run_job(breakfr = rec.files[i]try:+ file_started = time.monotonic()data = await _extract_bytes(entry.source, file_store, url_timeout=url_timeout)stype = _suffix_type(fr.name)if not stype:@@ -1099,54 +1193,34 @@ async def _run_job(tmp_path = pathlib.Path(tmpdir) / f"input_{i}{suffix}"tmp_path.write_bytes(data)- opts = entry.options or FileOptions()- kwargs: dict[str, Any] = {- "image_analysis": opts.image_analysis,- }- page_range = opts.page_range or ""-- # route to parser- if stype in ("html",):- from mineru.parser.html import HtmlParser-- parser = HtmlParser(**kwargs)- result = parser.parse(str(tmp_path))- elif stype in ("docx", "pptx", "xlsx"):- from mineru.parser.office import DocxParser, PptxParser, XlsxParser-- cls_map = {"docx": DocxParser, "pptx": PptxParser, "xlsx": XlsxParser}- parser = cls_map[stype](**kwargs)- result = parser.parse(str(tmp_path))- else:- # PDF / image — map tier to actual backend- _tier = rec.tier- if _tier == "auto":- _tier = "pro" if vlm_available else "standard"- if _tier == "pro":- from mineru.parser.pdf import PdfVlmParser-- kwargs["backend"] = "vlm-auto-engine"- parser = PdfVlmParser(**kwargs)- result = await parser.parse_async(str(tmp_path), page_range=page_range)- else:- from mineru.parser.pdf import PdfPipelineParser-- kwargs["backend"] = "pipeline"- pipeline_method = "auto"- if opts.ocr == "true":- pipeline_method = "ocr"- elif opts.ocr == "txt":- pipeline_method = "txt"- kwargs["method"] = pipeline_method- parser = PdfPipelineParser(**kwargs)- result = await asyncio.to_thread(parser.parse, str(tmp_path), page_range=page_range)+ page_range = entry.page_range or ""++ from . import parse_async++ result = await parse_async(+ str(tmp_path),+ tier=rec.tier,+ backend=server_backend,+ language=language,+ ocr_mode=ocr_mode,+ disable_table=not table_enable,+ disable_formula=not formula_enable,+ disable_image_analysis=not image_analysis,+ page_range=page_range,+ )# collect outputsout_formats = set(rec.output_formats)output_files = OutputFiles()import json as _json- for fmt in ("markdown", "json", "content_list", "content_list_v2", "images"):+ for fmt in (+ "markdown",+ "middle_json",+ "content_list",+ "structured_content",+ "images",+ ):if fmt not in out_formats:continueif fmt == "markdown":@@ -1155,8 +1229,8 @@ async def _run_job(sha = hashlib.sha256(content_bytes).hexdigest()file_store.store_blob(content_bytes, sha256hex=sha)fid = file_store.create_file_for_output(f"{fr.name}.md", content_bytes, sha256hex=sha)- output_files.markdown = OutputFileRef(file_id=fid, bytes=len(content_bytes), content=md or "")- elif fmt == "json":+ output_files.markdown = OutputFileRef(file_id=fid, bytes=len(content_bytes))+ elif fmt == "middle_json":mj = _json.dumps({"pages": [dataclasses.asdict(p) for p in result.pages]},ensure_ascii=False,@@ -1164,20 +1238,20 @@ async def _run_job(sha = hashlib.sha256(mj).hexdigest()file_store.store_blob(mj, sha256hex=sha)- fid = file_store.create_file_for_output(f"{fr.name}.json", mj, sha256hex=sha)- output_files.json_ = OutputFileRef(file_id=fid, bytes=len(mj))+ fid = file_store.create_file_for_output(f"{fr.name}.middle.json", mj, sha256hex=sha)+ output_files.middle_json = OutputFileRef(file_id=fid, bytes=len(mj))elif fmt == "content_list":cl = _json.dumps(result.content_list(), ensure_ascii=False).encode("utf-8")sha = hashlib.sha256(cl).hexdigest()file_store.store_blob(cl, sha256hex=sha)fid = file_store.create_file_for_output(f"{fr.name}.content_list.json", cl, sha256hex=sha)output_files.content_list = OutputFileRef(file_id=fid, bytes=len(cl))- elif fmt == "content_list_v2":+ elif fmt == "structured_content":cl2 = _json.dumps(result.content_list_v2(), ensure_ascii=False).encode("utf-8")sha = hashlib.sha256(cl2).hexdigest()file_store.store_blob(cl2, sha256hex=sha)- fid = file_store.create_file_for_output(f"{fr.name}.content_list_v2.json", cl2, sha256hex=sha)- output_files.content_list_v2 = OutputFileRef(file_id=fid, bytes=len(cl2))+ fid = file_store.create_file_for_output(f"{fr.name}.structured_content.json", cl2, sha256hex=sha)+ output_files.structured_content = OutputFileRef(file_id=fid, bytes=len(cl2))elif fmt == "images":img_refs: list[ImageOutputRef] = []for img_path, img_bytes in result.images().items():@@ -1196,15 +1270,16 @@ async def _run_job(with _zipfile.ZipFile(buf, "w", _zipfile.ZIP_DEFLATED) as zf:for fmt_name, attr in [("markdown", "markdown"),- ("json", "json_"),+ ("middle_json", "middle_json"),("content_list", "content_list"),- ("content_list_v2", "content_list_v2"),+ ("structured_content", "structured_content"),]:ref = getattr(output_files, attr)if ref and ref.file_id:try:zf.writestr(- f"{pathlib.Path(fr.name).stem}.{fmt_name}", file_store.read_file_data(ref.file_id)+ f"{pathlib.Path(fr.name).stem}.{fmt_name}",+ file_store.read_file_data(ref.file_id),)except Exception:pass@@ -1221,13 +1296,18 @@ async def _run_job(output_files.zip = OutputFileRef(file_id=zip_fid, bytes=len(zip_bytes))fr.status = "completed"+ fr.page_range = _page_range_from_result_pages(result.pages)fr.output_files = output_files+ from ..version import __version__++ fr.parse = FileParseInfo(+ model_used=None,+ duration_ms=int((time.monotonic() - file_started) * 1000),+ parser_version=__version__,+ )fr.file_id = file_store.create_file_for_output(fr.name, data)rec.progress.completed += 1- if hasattr(parser, "close"):- parser.close()-except Exception as exc:fr.status = "failed"fr.error = ErrorDetail(type="engine_error", code="parse_failed", message=str(exc))@@ -1271,9 +1351,9 @@ _ERR_429: dict[int | str, dict[str, Any]] = {429: {"model": ErrorResponse}})async def get_health() -> HealthResponse:"""Health check endpoint."""- from mineru.version import __version__+ from ..version import __version__- return HealthResponse(version=__version__, backend_version=__version__, models=ModelHealthStatus())+ return HealthResponse(version=__version__, parser_version=__version__, models=ModelHealthStatus())# ── Models ───────────────────────────────────────────────────────────@@ -1311,7 +1391,11 @@ async def get_model(raise HTTPException(status_code=404,detail=ErrorResponse(- error=ErrorDetail(type="invalid_request_error", code="model_not_found", message=f"Model '{model}' not found"),+ error=ErrorDetail(+ type="invalid_request_error",+ code="model_not_found",+ message=f"Model '{model}' not found",+ ),).model_dump(by_alias=True),)now = int(time.time())@@ -1535,7 +1619,9 @@ async def create_job(status_code=400,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="invalid_request", message=f"Unknown output format: {fmt}"+ type="invalid_request_error",+ code="invalid_request",+ message=f"Unknown output format: {fmt}",),).model_dump(by_alias=True),)@@ -1547,45 +1633,82 @@ async def create_job(status_code=400,detail=ErrorResponse(error=ErrorDetail(- type="invalid_request_error", code="invalid_request", message=f"wait must be 0 or [5, {max_wait}]"+ type="invalid_request_error",+ code="invalid_request",+ message=f"wait must be 0 or [5, {max_wait}]",),).model_dump(by_alias=True),)- # validate tier vs server backend- backend: str = request.app.state.backend- vlm_available = backend.startswith("vlm") or backend.startswith("hybrid")- if body.tier == "pro" and not vlm_available:+ # Resolve omitted tier to this server's concrete tier, then validate it.+ body.tier = body.tier or request.app.state.tier+ supported_tiers = {tier["id"] for tier in request.app.state.tiers}+ if body.tier not in supported_tiers:raise HTTPException(status_code=400,detail=ErrorResponse(error=ErrorDetail(type="invalid_request_error",code="invalid_request",- message="Pro tier not available in this server backend",+ message=f"Tier '{body.tier}' not available in this server",),).model_dump(by_alias=True),)rec = job_store.create(body, file_store)+ backend: str = request.app.state.backendurl_timeout_val: int = request.app.state.url_timeout- vlm_available_val = vlm_available+ language_val: str = request.app.state.language+ ocr_mode_val: str = request.app.state.ocr_mode+ table_enable_val: bool = request.app.state.table_enable+ formula_enable_val: bool = request.app.state.formula_enable+ image_analysis_val: bool = request.app.state.image_analysisif body.wait > 0:async with job_store._semaphore:- task = asyncio.create_task(_run_job(rec, body, file_store, vlm_available_val, url_timeout=url_timeout_val))+ task = asyncio.create_task(+ _run_job(+ rec,+ body,+ file_store,+ server_backend=backend,+ language=language_val,+ ocr_mode=ocr_mode_val,+ table_enable=table_enable_val,+ formula_enable=formula_enable_val,+ image_analysis=image_analysis_val,+ url_timeout=url_timeout_val,+ )+ )try:await asyncio.wait_for(task, timeout=body.wait)except asyncio.TimeoutError:passif rec.status in ("completed", "partial"):- return JSONResponse(content=job_store.build_response(rec).model_dump(by_alias=True), status_code=200)- return JSONResponse(content=job_store.build_response(rec).model_dump(by_alias=True), status_code=202)+ return JSONResponse(+ content=job_store.build_response(rec).model_dump(by_alias=True),+ status_code=200,+ )+ return JSONResponse(+ content=job_store.build_response(rec).model_dump(by_alias=True),+ status_code=202,+ )# async — fire and forgetasync def _bg_run() -> None:async with job_store._semaphore:- await _run_job(rec, body, file_store, vlm_available_val, url_timeout=url_timeout_val)+ await _run_job(+ rec,+ body,+ file_store,+ server_backend=backend,+ language=language_val,+ ocr_mode=ocr_mode_val,+ table_enable=table_enable_val,+ formula_enable=formula_enable_val,+ image_analysis=image_analysis_val,+ url_timeout=url_timeout_val,+ )asyncio.create_task(_bg_run())return JSONResponse(content=job_store.build_response(rec).model_dump(by_alias=True), status_code=202)@@ -1643,14 +1766,23 @@ async def get_job_events(for fr in rec.files:name = fr.name or fr.file_idif fr.status == "running" and name not in yielded:- yield _yield_event("file_started", f'{{"file_id":"{fr.file_id}","status":"running"}}')+ yield _yield_event(+ "file_started",+ f'{{"file_id":"{fr.file_id}","status":"running"}}',+ )yielded.add(name)elif fr.status == "completed" and (f"done_{name}" not in yielded):- yield _yield_event("file_completed", f'{{"file_id":"{fr.file_id}","status":"completed"}}')+ yield _yield_event(+ "file_completed",+ f'{{"file_id":"{fr.file_id}","status":"completed"}}',+ )yielded.add(f"done_{name}")elif fr.status == "failed" and (f"done_{name}" not in yielded):err_msg = fr.error.message.replace('"', '\\"') if fr.error else ""- yield _yield_event("file_failed", f'{{"file_id":"{fr.file_id}","status":"failed","error":{{"code":"{fr.error.code}","message":"{err_msg}"}}}}')+ yield _yield_event(+ "file_failed",+ f'{{"file_id":"{fr.file_id}","status":"failed","error":{{"code":"{fr.error.code}","message":"{err_msg}"}}}}',+ )yielded.add(f"done_{name}")await asyncio.sleep(1)@@ -1675,7 +1807,13 @@ async def list_jobs(job_store: JobStore = Depends(_get_job_store),) -> JobListResponse:"""List jobs for the current tenant."""- return job_store.list_jobs(status_filter=status_filter, limit=limit, after=after, order=order, created_after=created_after)+ return job_store.list_jobs(+ status_filter=status_filter,+ limit=limit,+ after=after,+ order=order,+ created_after=created_after,+ )@_router.delete(@@ -1722,14 +1860,73 @@ def _build_v1_router() -> APIRouter:return _router+_API_SERVER_LANGUAGES = (+ "ch",+ "ch_server",+ "ch_lite",+ "en",+ "korean",+ "japan",+ "chinese_cht",+ "ta",+ "te",+ "ka",+ "th",+ "el",+ "latin",+ "arabic",+ "east_slavic",+ "cyrillic",+ "devanagari",+)++_OCR_MODES = ("auto", "txt", "ocr")+++def _resolve_server_tier_and_backend(*, tier: Tier | None, backend: str | None) -> tuple[Tier, str]:+ resolved_tier = tier or os.getenv("MINERU_TIER") or None+ resolved_backend = backend or os.getenv("MINERU_BACKEND") or None+ if resolved_tier is None and resolved_backend is None:+ resolved_tier = "standard"+ resolved_tier, resolved_backend = resolve_tier_and_backend(tier=resolved_tier, backend=resolved_backend)+ if resolved_backend not in _API_SERVER_BACKENDS:+ raise ValueError(f"Unsupported backend '{resolved_backend}'. Supported backends: {', '.join(_API_SERVER_BACKENDS)}")+ return resolved_tier, resolved_backend+++def _model_ids_and_tiers_for_server_tier(tier: Tier) -> tuple[list[str], list[dict[str, Any]]]:+ if tier == "pro":+ return ["MinerU2.5-Pro-2604-1.2B", "MinerU-HTML"], [+ {+ "id": "pro",+ "description": "VLM-based high-accuracy parsing.",+ "current_model": "MinerU2.5-Pro-2604-1.2B",+ },+ ]++ return ["pipeline", "MinerU-HTML"], [+ {+ "id": "standard",+ "description": "Pipeline-based parsing, balanced speed and quality.",+ "current_model": "pipeline",+ },+ ]++def create_app(*,upload_dir: str = "",- backend: str = "pipeline",+ tier: Tier | None = None,+ backend: str | None = None,concurrency: int = 1,url_timeout: int = 60,max_wait: int = 600,api_key: str | None = None,+ language: str = "ch",+ ocr_mode: str = "auto",+ table_enable: bool = True,+ formula_enable: bool = True,+ image_analysis: bool = True,) -> FastAPI:"""Create a FastAPI application implementing the MinerU v1 REST API.@@ -1737,9 +1934,13 @@ def create_app(----------upload_dir:Directory for uploaded files and parse artifacts.+ tier:+ Server parsing tier. ``"standard"`` selects the pipeline backend;+ ``"pro"`` selects the VLM backend. If ``backend`` is also provided,+ both values must be compatible.backend:- Server backend mode. ``"pipeline"`` exposes the traditional CV+OCR- pipeline; ``"vlm"`` exposes ``MinerU2.5-Pro-2604-1.2B``.+ Advanced server backend mode. ``"pipeline"`` exposes the traditional+ CV+OCR pipeline; ``"vlm"`` exposes ``MinerU2.5-Pro-2604-1.2B``.concurrency:Maximum concurrent parse jobs (default 1).url_timeout:@@ -1749,44 +1950,37 @@ def create_app(api_key:Optional API key. When set, clients must pass ``Authorization: Bearer <key>``to access list endpoints and advanced output formats.+ language:+ Parser language hint.+ ocr_mode:+ PDF OCR/text extraction mode for pipeline and hybrid backends.+ table_enable:+ Whether table recognition is enabled.+ formula_enable:+ Whether formula recognition is enabled.+ image_analysis:+ Whether image analysis is enabled for VLM/hybrid backends."""upload_dir = upload_dir or os.getenv("MINERU_UPLOAD_DIR", "")- backend = backend or os.getenv("MINERU_BACKEND", "pipeline")+ tier, backend = _resolve_server_tier_and_backend(tier=tier, backend=backend)concurrency = int(os.getenv("MINERU_CONCURRENCY", str(concurrency)))url_timeout = int(os.getenv("MINERU_URL_TIMEOUT", str(url_timeout)))max_wait = int(os.getenv("MINERU_MAX_WAIT", str(max_wait)))+ language = os.getenv("MINERU_LANGUAGE", language)+ ocr_mode = os.getenv("MINERU_OCR_MODE", ocr_mode)+ table_enable = _env_flag("MINERU_TABLE_ENABLE", default=table_enable)+ formula_enable = _env_flag("MINERU_FORMULA_ENABLE", default=formula_enable)+ image_analysis = _env_flag("MINERU_IMAGE_ANALYSIS", default=image_analysis)_api_key: str | None = api_key or None_upload_dir = pathlib.Path(upload_dir) if upload_dir else pathlib.Path(tempfile.mkdtemp(prefix="mineru_"))_upload_dir.mkdir(parents=True, exist_ok=True)- # resolve models and tiers based on backend- _model_ids: list[str]- _tiers: list[dict[str, Any]]- if backend.startswith("vlm") or backend.startswith("hybrid"):- _model_ids = ["pipeline", "MinerU2.5-Pro-2604-1.2B", "MinerU-HTML"]- _tiers = [- {- "id": "standard",- "description": "Pipeline-based parsing, balanced speed and quality.",- "current_model": "pipeline",- },- {"id": "pro", "description": "VLM-based high-accuracy parsing.", "current_model": "MinerU2.5-Pro-2604-1.2B"},- {"id": "auto", "description": "Platform selects best tier per document.", "current_model": None},- ]- else:- _model_ids = ["pipeline", "MinerU-HTML"]- _tiers = [- {- "id": "standard",- "description": "Pipeline-based parsing, balanced speed and quality.",- "current_model": "pipeline",- },- {"id": "auto", "description": "Platform selects best tier per document.", "current_model": None},- ]+ _model_ids, _tiers = _model_ids_and_tiers_for_server_tier(tier)@asynccontextmanagerasync def _lifespan(application: FastAPI) -> AsyncIterator[None]:application.state.upload_dir = _upload_dir+ application.state.tier = tierapplication.state.backend = backendapplication.state.model_ids = _model_idsapplication.state.tiers = _tiers@@ -1794,6 +1988,11 @@ def create_app(application.state.url_timeout = url_timeoutapplication.state.max_wait = max_waitapplication.state.api_key = _api_key+ application.state.language = language+ application.state.ocr_mode = ocr_mode+ application.state.table_enable = table_enable+ application.state.formula_enable = formula_enable+ application.state.image_analysis = image_analysisyieldif not upload_dir and _upload_dir.exists():shutil.rmtree(_upload_dir, ignore_errors=True)@@ -1809,6 +2008,7 @@ def create_app(lifespan=_lifespan,)application.state.upload_dir = _upload_dir+ application.state.tier = tierapplication.state.backend = backendapplication.state.model_ids = _model_idsapplication.state.tiers = _tiers@@ -1816,6 +2016,11 @@ def create_app(application.state.url_timeout = url_timeoutapplication.state.max_wait = max_waitapplication.state.api_key = _api_key+ application.state.language = language+ application.state.ocr_mode = ocr_mode+ application.state.table_enable = table_enable+ application.state.formula_enable = formula_enable+ application.state.image_analysis = image_analysisFileStore(_upload_dir).install(application.state)JobStore(concurrency=concurrency).install(application.state)application.add_middleware(GZipMiddleware, minimum_size=1000)@@ -1868,9 +2073,15 @@ app = create_app())@click.option("--backend",- default="pipeline",- type=click.Choice(["pipeline", "vlm"]),- help="Server backend: 'pipeline' (CV+OCR) or 'vlm' (Vision Language Model)",+ default=None,+ type=click.Choice(_API_SERVER_BACKENDS),+ help="Advanced parser backend. Defaults from --tier: standard -> pipeline, pro -> hybrid-auto-engine.",+)+ "--tier",+ default=None,+ type=click.Choice(["standard", "pro"]),+ help="Server parsing tier. Defaults to 'standard' when neither --tier nor --backend is provided.",)@click.option("--concurrency",@@ -1890,6 +2101,21 @@ app = create_app()type=int,help="Maximum seconds for the wait parameter (default: 600)",)+ "--language",+ default="ch",+ type=click.Choice(_API_SERVER_LANGUAGES),+ help="Parser language hint.",+)+ "--ocr-mode",+ default="auto",+ type=click.Choice(_OCR_MODES),+ help="PDF OCR/text extraction mode. Applies to pipeline and hybrid-* backends.",+)[email protected]("--disable-table", is_flag=True, help="Disable table recognition.")[email protected]("--disable-formula", is_flag=True, help="Disable formula recognition.")[email protected]("--disable-image-analysis", is_flag=True, help="Disable image analysis for VLM/hybrid backends.")@click.option("--api-key",default=None,@@ -1901,10 +2127,16 @@ def main(port: int,reload: bool,upload_dir: str,- backend: str,+ backend: str | None,+ tier: Tier | None,concurrency: int,url_timeout: int,max_wait: int,+ language: str,+ ocr_mode: str,+ disable_table: bool,+ disable_formula: bool,+ disable_image_analysis: bool,api_key: str | None,) -> None:"""Start the MinerU v1 REST API server."""@@ -1912,22 +2144,41 @@ def main(if upload_dir:os.environ["MINERU_UPLOAD_DIR"] = upload_dir+ if tier:+ os.environ["MINERU_TIER"] = tierif backend:os.environ["MINERU_BACKEND"] = backendos.environ["MINERU_CONCURRENCY"] = str(concurrency)os.environ["MINERU_URL_TIMEOUT"] = str(url_timeout)os.environ["MINERU_MAX_WAIT"] = str(max_wait)+ os.environ["MINERU_LANGUAGE"] = language+ os.environ["MINERU_OCR_MODE"] = ocr_mode+ os.environ["MINERU_TABLE_ENABLE"] = str(not disable_table).lower()+ os.environ["MINERU_FORMULA_ENABLE"] = str(not disable_formula).lower()+ os.environ["MINERU_IMAGE_ANALYSIS"] = str(not disable_image_analysis).lower()if reload:- uvicorn.run("mineru.parser.api_server:create_app", host=host, port=port, reload=True, factory=True)+ uvicorn.run(+ "mineru.parser.api_server:create_app",+ host=host,+ port=port,+ reload=True,+ factory=True,+ )else:uvicorn.run(create_app(upload_dir=upload_dir,+ tier=tier,backend=backend,concurrency=concurrency,url_timeout=url_timeout,max_wait=max_wait,api_key=api_key,+ language=language,+ ocr_mode=ocr_mode,+ table_enable=not disable_table,+ formula_enable=not disable_formula,+ image_analysis=not disable_image_analysis,),host=host,port=port,@@ -1949,7 +2200,6 @@ __all__ = ["AccessLevel","OutputFormat","SourceType",- "OcrMode","FilePurpose","SSEEventType",# request models@@ -1957,7 +2207,6 @@ __all__ = ["CompleteUploadRequest","CreateJobRequest","JobFileEntry",- "FileOptions","CallbackConfig",# source models"FileIdSource",@@ -1981,7 +2230,7 @@ __all__ = ["JobAsyncResponse","JobLinks","JobProgress",- "FileMetadata",+ "FileParseInfo","OutputFileRef","ImageOutputRef","OutputFiles",diff --git a/mineru/parser/base.py b/mineru/parser/base.pyindex 345963b0..e9e3fe8f 100644--- a/mineru/parser/base.py+++ b/mineru/parser/base.py@@ -10,8 +10,8 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from mineru.render import render_content_list, render_content_list_v2, render_markdown-from mineru.types import PageInfo+from ..render import render_content_list, render_content_list_v2, render_markdown+from ..types import PageInfo_INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,([^\"]+)", re.DOTALL)@@ -25,10 +25,7 @@ class ParseResult:"""pages: list[PageInfo]- _backend: str- _version_name: str_pdf_doc: object | None = None- _file_name: str = ""_model_output: Any = None_images_cache: dict[str, bytes] | None = None@@ -58,24 +55,21 @@ class ParseResult:return render_content_list_v2(self.pages)def save(self, writer: Any) -> None:- prefix = self._file_name-- # TODO: need rename these files- writer.write_string(f"{prefix}.md", self.markdown())- writer.write_string(f"{prefix}_middle.json", self.to_json())+ writer.write_string("markdown.md", self.markdown())+ writer.write_string("middle_json.json", self.to_json())writer.write_string(- f"{prefix}_content_list.json",+ "content_list.json",json.dumps(self.content_list(), ensure_ascii=False, indent=4),)writer.write_string(- f"{prefix}_content_list_v2.json",+ "structured_content.json",json.dumps(self.content_list_v2(), ensure_ascii=False, indent=4),)if self._model_output is not None:writer.write_string(- f"{prefix}_model.json",+ "model_output.json",json.dumps(self._model_output, ensure_ascii=False, indent=4),)diff --git a/mineru/parser/html.py b/mineru/parser/html.pyindex f88d55dd..1dd6be66 100644--- a/mineru/parser/html.py+++ b/mineru/parser/html.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom bs4 import BeautifulSoup, Tagfrom .base import DocumentParser, ParseResult-from mineru.types import Block, Line, PageInfo, Span+from ..types import Block, Line, PageInfo, Spanclass HtmlParser(DocumentParser):@@ -20,7 +20,6 @@ class HtmlParser(DocumentParser):if not path.exists():raise FileNotFoundError(path)- file_name = path.stemhtml_text = path.read_text(encoding="utf-8")soup = BeautifulSoup(html_text, "html.parser")@@ -30,9 +29,6 @@ class HtmlParser(DocumentParser):return ParseResult(pages=[PageInfo(page_idx=0, para_blocks=blocks)],- _backend="html",- _version_name=_version(),- _file_name=file_name,)@@ -149,8 +145,3 @@ def _build_code(element: Tag) -> Block:type="code",lines=[Line(spans=[Span(type="code", content=content)])],)---def _version() -> str:- from ..version import __version__- return __version__diff --git a/mineru/parser/office.py b/mineru/parser/office.pyindex a4f0c585..af323719 100644--- a/mineru/parser/office.py+++ b/mineru/parser/office.py@@ -5,9 +5,8 @@ from abc import ABCfrom pathlib import Pathfrom typing import Any-from mineru.types import PageInfo-from .base import DocumentParser, ParseResult+from ..types import PageInfoclass OfficeBaseParser(DocumentParser, ABC):@@ -38,13 +37,8 @@ class OfficeBaseParser(DocumentParser, ABC):file_name: str,model_output: Any = None,) -> ParseResult:- from ..version import __version__-return ParseResult(pages=middle_json,- _backend="office",- _version_name=__version__,- _file_name=file_name,_model_output=model_output if self.return_model_output else None,)diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.pyindex 40cd6eac..0a503b4c 100644--- a/mineru/parser/pdf.py+++ b/mineru/parser/pdf.py@@ -7,9 +7,8 @@ from abc import abstractmethodfrom pathlib import Pathfrom typing import Any-from mineru.types import PageInfo-from .base import DocumentParser, ParseResult+from ..types import PageInfo_IMAGE_SUFFIXES = frozenset({"png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"})@@ -135,14 +134,10 @@ class PdfBaseParser(DocumentParser):file_name: str,) -> ParseResult:from ..utils.pdf_document import PDFDocument- from ..version import __version__return ParseResult(pages=middle_json,- _backend=self._backend,- _version_name=__version__,_pdf_doc=PDFDocument(pdf_bytes),- _file_name=file_name,)@@ -322,7 +317,7 @@ class PdfFlashParser(PdfBaseParser):_backend = "flash"def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:- from mineru.types import Block, Line, PageInfo, Span+ from ..types import Block, Line, PageInfo, Spanfrom ..backend.flash.pdf_extractor import extract_textdiff --git a/mineru/parser/tier.py b/mineru/parser/tier.pynew file mode 100644index 00000000..1616af49--- /dev/null+++ b/mineru/parser/tier.py@@ -0,0 +1,74 @@+# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations++from ..types import Tier++__all__ = [+ "PARSER_BACKENDS",+ "backend_for_tier",+ "resolve_tier_and_backend",+ "tier_for_backend",+]++PARSER_BACKENDS = (+ "pipeline",+ "flash",+ "vlm-auto-engine",+ "vlm-http-client",+ "vlm-transformers",+ "vlm-vllm-engine",+ "vlm-vllm-async-engine",+ "vlm-lmdeploy-engine",+ "vlm-mlx-engine",+ "hybrid-auto-engine",+ "hybrid-http-client",+ "hybrid-transformers",+ "hybrid-vllm-engine",+ "hybrid-vllm-async-engine",+ "hybrid-lmdeploy-engine",+ "hybrid-mlx-engine",+)+++def backend_for_tier(tier: Tier) -> str:+ """Return the local parser backend used for a parser-layer tier fallback."""+ mapping = {+ "flash": "flash",+ "standard": "pipeline",+ "pro": "hybrid-auto-engine",+ }+ return mapping.get(tier, "pipeline")+++def tier_for_backend(backend: str) -> Tier:+ if backend == "flash":+ return "flash"+ if backend == "pipeline":+ return "standard"+ if backend.startswith("vlm-") or backend.startswith("hybrid-"):+ return "pro"+ raise ValueError(f"Unsupported backend '{backend}'. Supported backends: {', '.join(PARSER_BACKENDS)}")+++def _backend_supports_tier(backend: str, tier: Tier) -> bool:+ if backend not in PARSER_BACKENDS:+ raise ValueError(f"Unsupported backend '{backend}'. Supported backends: {', '.join(PARSER_BACKENDS)}")+ if tier == "flash":+ return backend == "flash"+ if tier == "standard":+ return backend == "pipeline"+ if tier == "pro":+ return backend.startswith("vlm-") or backend.startswith("hybrid-")+ return False+++def resolve_tier_and_backend(tier: Tier | None = None, backend: str | None = None) -> tuple[Tier, str]:+ """Resolve public tier and optional expert backend into an executable parser backend."""+ resolved_tier: Tier = tier or "pro"+ if backend:+ if tier is None:+ return tier_for_backend(backend), backend+ if not _backend_supports_tier(backend, resolved_tier):+ raise ValueError(f"tier '{resolved_tier}' is incompatible with backend '{backend}'")+ return tier_for_backend(backend), backend+ return resolved_tier, backend_for_tier(resolved_tier)diff --git a/mineru/types.py b/mineru/types.pyindex dc65f680..bf0c8ec3 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -7,6 +7,25 @@ from typing import Any, Iterator, Literal, TypeAlias, TypeVar, get_type_hintsT = TypeVar("T", bound="_DocElement")+Tier = Literal[+ "flash",+ "standard",+ "pro",+]++TIERS: set[str] = {+ "flash",+ "standard",+ "pro",+}++TIER_ORDER: dict[Tier, int] = {+ "flash": 0,+ "standard": 1,+ "pro": 2,+}++class BlockType:IMAGE = "image"IMAGE_BODY = "image_body"