Skip to content

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

refactor: unify parser module, add page_range and API key auth

jinzhenjce2e3ba4ae88
diff --git a/NEXT-API.md b/NEXT-API.md
index 519e4271..be384809 100644
--- a/NEXT-API.md
+++ b/NEXT-API.md
@@ -10,6 +10,9 @@
| 日期 | 修订内容 |
|------|---------|
+| 2026-06-08 | **本地 Server API Key 鉴权**:本地自部署 server 支持通过 `--api-key` 启用 Bearer 鉴权。未设置 API Key 时所有端点公开(现有行为不变);设置后除 health/models/tiers 外的全部端点要求 `Authorization: Bearer <key>`,不匹配返回 401。详见 §1.3 |
+| 2026-06-08 | **删除 `language` 参数与 `language_detected` 字段**:API 全面支持自动语言探测,不再需要客户端传入 `language` 参数。请求 `files[].options.language` 移除,响应 `metadata.language_detected` 移除。解析器内部自动识别文档语言 |
+| 2026-06-08 | **删除 `formula` / `table` 细粒度开关**:不再支持通过 `files[].options.formula` 和 `files[].options.table` 关闭公式识别和表格识别。公式和表格解析始终开启,由引擎内部自动处理 |
| 2026-06-02 | **`Token` → `API Key`**:全文认证凭证术语从 `Token` 统一为 `API Key`,环境变量 `MINERU_TOKEN` → `MINERU_API_KEY`,SDK 参数 `token=` → `api_key=`,错误码 `invalid_token` → `invalid_api_key`、`feature_requires_token` → `feature_requires_api_key`、`list_requires_token` → `list_requires_api_key`。避免与 LLM token 概念混淆 |
| 2026-06-02 | **错误响应格式对齐 OpenAI**:§2.2 从 `code` + `message` + `details` 改为 OpenAI 兼容的 `type` + `code` + `message` + `param` 四字段结构。新增 `type` 枚举(`invalid_request_error`、`authentication_error`、`permission_error`、`rate_limit_error`、`engine_error`、`api_error`)。详见 NEXT-ERROR.md |
| 2026-06-01 | **`preset` → `tier`**:全文将 `preset` 概念替换为 `tier`,可选值从 `pipeline/vlm/html/auto` 改为 `standard/pro/auto`。`html` 不再作为显式选项,改为系统根据输入文件类型自动路由到 HTML 解析器。与 CLI (`mineru parse --tier`) 命名统一 |
@@ -101,10 +104,25 @@
Authorization: Bearer <MINERU_API_KEY>
```
+**mineru.net 云端**
+
- **缺省 API Key**:匿名访问,自动降级为 anonymous 档。anonymous 用户的身份标识为**请求 IP**,限流和用量均按 IP 统计。
- **有效 API Key**:按 API Key 等级解锁更高配额、`docx`/`html`/`latex` 等高级输出格式。
- **无效 API Key**:返回 `401 Unauthorized`(注意:**不传 API Key ≠ API Key 无效**)。
+**本地自部署 Server**
+
+- **未设置 API Key**(默认):所有端点公开访问,无需认证。适用于单机、内网等信任环境。
+- **设置 API Key**(`--api-key <key>`):除以下 3 个公开端点外,其余全部端点要求携带 `Authorization: Bearer <key>`,不匹配返回 `401 invalid_api_key`。
+
+| 始终公开的端点 | 说明 |
+|---------------|------|
+| `GET /v1/health` | 健康检查 |
+| `GET /v1/models`、`GET /v1/models/{model}` | 模型列表与详情 |
+| `GET /v1/tiers` | 解析档位列表 |
+
+> **设计说明**:local server 的鉴权目标是"防止未授权访问自部署实例",而非 mineru.net 的"按 access level 差异化功能"。当 API Key 设置后,通过认证的请求等同于 `registered` 档,可直接使用全部能力和高级输出格式。
+
### 1.4 通用约定
- **基址(Base URL)**
@@ -1407,10 +1425,7 @@ data: {"type":"response.completed","response":{"id":"resp_...","object":"respons
"file_id": "file-01HXYZ123ABCDEF"
},
"options": {
- "language": "ch",
"ocr": "auto",
- "formula": true,
- "table": true,
"image_analysis": true,
"page_range": "1-10"
}
@@ -1470,10 +1485,7 @@ data: {"type":"response.completed","response":{"id":"resp_...","object":"respons
| 字段 | 类型 | 默认 | 说明 |
|------|------|------|------|
-| `language` | string | `"ch"` | `ch` / `en` / `ja` / `korean` / `ch_lite` / `ch_server` / `japan` / `chinese_cht` / `ta` / `te` / `ka` / `th` / `el` / `latin` / `arabic` / `east_slavic` / `cyrillic` / `devanagari`。不传则默认 `ch` |
| `ocr` | enum | `auto` | `auto` / `true` / `false` / `txt`。`txt` 强制文本提取(不 OCR) |
-| `formula` | bool | `true` | 公式识别 |
-| `table` | bool | `true` | 表格识别 |
| `image_analysis` | bool | `true` | 图片内容分析 |
| `page_range` | string | `null` | 页码范围,推荐用 `~` 分隔(如 `"1~10"`、`"1,3,5~7"`、`"-5~-1"`)。也支持 `-` 分隔(如 `"1-10"`、`"2--2"` 到倒数第二页) |
@@ -1538,7 +1550,6 @@ data: {"type":"response.completed","response":{"id":"resp_...","object":"respons
"metadata": {
"pages": 12,
"model_used": "MinerU2.5-Pro-2604-1.2B",
- "language_detected": "ch",
"processing_time_ms": 8234,
"backend_version": "3.1.14"
},
@@ -1627,7 +1638,6 @@ data: {"type":"response.completed","response":{"id":"resp_...","object":"respons
"metadata": {
"pages": 12,
"model_used": "MinerU2.5-Pro-2604-1.2B",
- "language_detected": "ch",
"processing_time_ms": 8234,
"backend_version": "3.1.14"
},
@@ -1980,6 +1990,15 @@ Authorization: Bearer <MINERU_API_KEY>
- `billing_period` 粒度为天,始终 UTC 零点对齐,无时区歧义
- 若未来引入月度配额上限(如"每月最多 10000 页"),可在 `limits` 中增补字段,向后兼容
+**本地 Server 差异**
+
+本地自部署 server 的 `GET /v1/usage` 语义与 mineru.net 不同:
+
+- `billing_period.start` — 服务进程启动时间(ISO-8601),`end` 为 `null`
+- `current.*` — 自启动以来的累计值,不按租户区分
+- `limits.max_file_retention_days` — `null`(本地不自动清理)
+- `access_level` — 取决于请求是否通过 API Key 认证(§1.3)
+
---
## 13. 端到端示例
@@ -2027,7 +2046,7 @@ curl -X POST https://mineru.net/api/v1/parse/jobs \
-d "{
\"files\": [{
\"source\": {\"type\":\"file_id\",\"file_id\":\"$FILE_ID\"},
- \"options\": {\"language\":\"ch\",\"ocr\":\"auto\"}
+ \"options\": {\"ocr\":\"auto\"}
}],
\"tier\": \"pro\", \"output_formats\": [\"markdown\",\"json\",\"images\"]
}"
@@ -2084,7 +2103,7 @@ curl -X POST https://mineru.net/api/v1/parse/jobs \
-d "{
\"files\": [{
\"source\": {\"type\":\"file_id\",\"file_id\":\"$FILE_ID\"},
- \"options\": {\"language\":\"ch\",\"ocr\":\"auto\"}
+ \"options\": {\"ocr\":\"auto\"}
}],
\"tier\": \"pro\", \"output_formats\": [\"markdown\",\"json\"],
\"wait\": 30
@@ -2280,7 +2299,7 @@ Content-Type: application/json
{
"files":[{"source":{"type":"file_id","file_id":"file-..."},
- "options":{"language":"ch"}}],
+ "options":{}}],
"tier":"standard",
"output_formats":["markdown","json","content_list","images"]
}
@@ -2434,7 +2453,7 @@ Content-Type: application/pdf
POST /v1/parse/jobs
{
"files":[{"source":{"type":"file_id","file_id":"file-01HXYZ..."},
- "options":{"language":"ch","ocr":"auto","page_range":"1-10"}}],
+ "options":{"ocr":"auto","page_range":"1-10"}}],
"tier":"pro",
"output_formats":["markdown","json","images","docx"]
}
@@ -2552,7 +2571,7 @@ POST /v1/uploads
POST /v1/parse/jobs
{
"files":[{"source":{"type":"file_id","file_id":"file-..."},
- "options":{"language":"ch","page_range":"1-5","ocr":"auto"}}],
+ "options":{"page_range":"1-5","ocr":"auto"}}],
"output_formats":["markdown"]
}
→ 202 {"job_id":"job_...","access_level":"anonymous"}
@@ -2563,7 +2582,7 @@ POST /v1/parse/jobs
- 旧:**单文件**任务;新:任意数量文件
- 旧:`{code,msg,data}` envelope;新:扁平资源
- 旧:无 sha256/秒传概念;新:可选秒传
-- 旧:任务参数写在 Call 1 顶层;新:文件级参数(`page_range`, `language`)在 `files[].options`,任务级参数(`tier`, `output_formats`)在 job 顶层
+- 旧:任务参数写在 Call 1 顶层;新:文件级参数(`page_range`)在 `files[].options`,任务级参数(`tier`, `output_formats`)在 job 顶层
#### Call 2 — 上传字节
diff --git a/mineru/__init__.py b/mineru/__init__.py
index 69f394a0..8f3a4f6f 100644
--- a/mineru/__init__.py
+++ b/mineru/__init__.py
@@ -1,23 +1,19 @@
# Copyright (c) Opendatalab. All rights reserved.
from .parser import ( # noqa: F401
- Block,
DocumentParser,
DocxParser,
HtmlParser,
- Line,
MinerUApiParser,
- OfficeBaseParser,
- PageInfo,
ParseResult,
- PdfBaseParser,
+ PdfFlashParser,
PdfHybridParser,
PdfPipelineParser,
PdfVlmParser,
PptxParser,
- Span,
XlsxParser,
parse,
)
+from .types import Block, Line, PageInfo, Span # noqa: F401
__all__ = [
"Block",
@@ -26,10 +22,9 @@ __all__ = [
"HtmlParser",
"Line",
"MinerUApiParser",
- "OfficeBaseParser",
"PageInfo",
"ParseResult",
- "PdfBaseParser",
+ "PdfFlashParser",
"PdfHybridParser",
"PdfPipelineParser",
"PdfVlmParser",
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index 5c910180..e7d8562f 100644
--- a/mineru/backend/utils/middle_json_utils.py
+++ b/mineru/backend/utils/middle_json_utils.py
@@ -80,7 +80,7 @@ def apply_post_ocr(pages: list[PageInfo], ocr_model: Any) -> None:
for blocks in [page_info.preproc_blocks, page_info.discarded_blocks]:
for block in blocks:
for span in _iter_block_spans(block):
- if span._np_img:
+ if span._np_img is not None:
need_ocr_list.append(span)
img_crop_list.append(rotate_vertical_crop_if_needed(span._np_img))
span._np_img = None
@@ -93,11 +93,11 @@ def apply_post_ocr(pages: list[PageInfo], ocr_model: Any) -> None:
for index, span in enumerate(need_ocr_list):
ocr_text, ocr_score = ocr_res_list[index]
if ocr_score > OcrConfidence.min_confidence:
- span["content"] = ocr_text
- span["score"] = float(f"{ocr_score:.3f}")
+ span.content = ocr_text
+ span.score = float(f"{ocr_score:.3f}")
else:
- span["content"] = ""
- span["score"] = 0.0
+ span.content = ""
+ span.score = 0.0
def _iter_block_spans(block: Block) -> Iterator[Span]:
diff --git a/mineru/cli_next/commands/config.py b/mineru/cli_next/commands/config.py
index 4dfc536e..ded19a42 100644
--- a/mineru/cli_next/commands/config.py
+++ b/mineru/cli_next/commands/config.py
@@ -204,6 +204,104 @@ def parsing_rules_rm(rule_id: int = typer.Argument(..., help="Rule ID to remove"
raise typer.Exit(1) from None
+parse_server_app = typer.Typer(help="Parse-server configuration", no_args_is_help=True)
+app.add_typer(parse_server_app, name="parse-server")
+
+
+# ── parse-server config ──────────────────────────────────────────
+
+
+@parse_server_app.command("local.mode")
+def parse_server_local_mode(
+ mode: str = typer.Argument(..., help="Mode: disabled, managed, self_hosted"),
+) -> None:
+ """Set local parse-server mode."""
+ valid = {"disabled", "managed", "self_hosted"}
+ if mode not in valid:
+ 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})
+ print_success(f"Local parse-server mode set to '{mode}'.")
+ except Exception as exc:
+ print_error(str(exc))
+ raise typer.Exit(1) from None
+
+
+@parse_server_app.command("local.managed-tier")
+def parse_server_managed_tier(
+ tier: str = 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})
+ print_success(f"Managed tier set to '{tier}'.")
+ except Exception as exc:
+ print_error(str(exc))
+ raise typer.Exit(1) from None
+
+
+@parse_server_app.command("local.self-hosted-url")
+def parse_server_self_hosted_url(
+ url: str = typer.Argument(..., help="HTTP URL of self-hosted parse-server"),
+) -> 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})
+ print_success(f"Self-hosted URL set to '{url}'.")
+ except Exception as exc:
+ print_error(str(exc))
+ raise typer.Exit(1) from None
+
+
+@parse_server_app.command("local.self-hosted-api-key")
+def parse_server_self_hosted_api_key(
+ api_key: str = typer.Argument(..., help="API key for self-hosted parse-server"),
+) -> 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})
+ print_success("Self-hosted API key set.")
+ except Exception as exc:
+ print_error(str(exc))
+ raise typer.Exit(1) from None
+
+
+@parse_server_app.command("remote.url")
+def parse_server_remote_url(
+ url: str = typer.Argument(..., help="Remote parse-server URL (default: https://mineru.net/api)"),
+) -> None:
+ """Set remote parse-server URL."""
+ try:
+ client = MineruClient(timeout=10)
+ client._post("/config", {"key": "parse_server.remote.url", "value": url})
+ print_success(f"Remote URL set to '{url}'.")
+ except Exception as exc:
+ print_error(str(exc))
+ raise typer.Exit(1) from None
+
+
+@parse_server_app.command("remote.api-key")
+def parse_server_remote_api_key(
+ api_key: str = typer.Argument(..., help="API key for remote parse-server"),
+) -> 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})
+ print_success("Remote API key set.")
+ except Exception as exc:
+ print_error(str(exc))
+ raise typer.Exit(1) from None
+
+
# ── helpers ──────────────────────────────────────────────────────
diff --git a/mineru/cli_next/commands/parse.py b/mineru/cli_next/commands/parse.py
index 63e6694c..7e9a8ac1 100644
--- a/mineru/cli_next/commands/parse.py
+++ b/mineru/cli_next/commands/parse.py
@@ -19,6 +19,8 @@ def parse_cmd(
None, "-p", "--pages", help="Page range, e.g. '1~5' or 'all'"
),
force: bool = typer.Option(False, "--force", help="Force re-parse, ignore cache"),
+ remote: bool = typer.Option(False, "--remote", help="Use remote parse-server (default: mineru.net)"),
+ remote_url: str = typer.Option(None, "--remote-url", help="Custom remote parse-server URL. Requires --remote"),
wait: int = typer.Option(
60, "--wait", help="Max seconds to wait for parse to complete"
),
@@ -49,7 +51,7 @@ def parse_cmd(
# send parse request
try:
- result = client.parse(file_path, tier=tier, pages=pages, force=force)
+ result = client.parse(file_path, tier=tier, pages=pages, force=force, remote=remote, remote_url=remote_url)
except Exception as exc:
print_error(str(exc))
raise typer.Exit(1) from None
diff --git a/mineru/cli_next/output.py b/mineru/cli_next/output.py
index b53d8d10..9b8b8f0a 100644
--- a/mineru/cli_next/output.py
+++ b/mineru/cli_next/output.py
@@ -121,6 +121,22 @@ def format_server_status(data: dict, json_mode: bool = False) -> None:
table.add_row("Ingest queue", str(data.get("ingest_queue_length", 0)))
table.add_row("Watches", str(data.get("watch_count", 0)))
console.print(table)
+
+ # parse-server status
+ ps_data = data.get("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, {})
+ healthy_str = "yes" if ps.get("healthy") else "no"
+ tiers_str = ", ".join(ps.get("supported_tiers", [])) or "-"
+ mode = ps.get("mode", "")
+ label_str = f"{label} ({mode})" if mode else label
+ ps_table.add_row(label_str, healthy_str, tiers_str)
+ console.print(ps_table)
else:
print(f"Server running (PID {data.get('pid')}), {data.get('files_total')} files")
diff --git a/mineru/doclib/background/compaction.py b/mineru/doclib/background/compaction.py
index a9af008e..09ee99fa 100644
--- a/mineru/doclib/background/compaction.py
+++ b/mineru/doclib/background/compaction.py
@@ -111,30 +111,34 @@ class Compaction:
if not os.path.isdir(tier_dir):
return
- # collect all pages from existing JSON files
+ # collect all pages + markdown from existing files
pages_by_idx: dict[int, dict] = {}
+ md_texts: dict[str, str] = {}
for fname in os.listdir(tier_dir):
- if not fname.endswith(".json"):
- continue
try:
- with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:
- for p in _json.load(f).get("pdf_info", []):
- pages_by_idx[p["page_idx"]] = p
+ if fname.endswith(".json"):
+ with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:
+ for p in _json.load(f).get("pdf_info", []):
+ pages_by_idx[p["page_idx"]] = p
+ elif fname.endswith(".md"):
+ stem = fname[:-3] # remove .md
+ with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:
+ md_texts[stem] = f.read()
except Exception:
pass
if not pages_by_idx:
return
- # delete old JSON files
+ # delete old files
for fname in os.listdir(tier_dir):
- if fname.endswith(".json"):
+ if fname.endswith(".json") or fname.endswith(".md"):
try:
os.unlink(os.path.join(tier_dir, fname))
except OSError:
pass
- # write one compacted JSON per merged range
+ # write one compacted JSON + MD per merged range
for pages_str in merged_ranges:
page_set = parse_range_set(pages_str)
json_pages = [
@@ -142,7 +146,8 @@ class Compaction:
]
if not json_pages:
continue
- json_path = os.path.join(tier_dir, f"{_safe_filename(pages_str)}.json")
+ key = _safe_filename(pages_str)
+ json_path = os.path.join(tier_dir, f"{key}.json")
try:
with open(json_path, "w", encoding="utf-8") as f:
_json.dump(
@@ -151,6 +156,14 @@ class Compaction:
except Exception:
pass
+ md_path = os.path.join(tier_dir, f"{key}.md")
+ try:
+ merged_md = "\n".join(md for k, md in sorted(md_texts.items()))
+ with open(md_path, "w", encoding="utf-8") as f:
+ f.write(merged_md)
+ except Exception:
+ pass
+
def _safe_filename(s: str) -> str:
return s # pages string is already safe: "1~5,43~47"
diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.py
new file mode 100644
index 00000000..11630c0e
--- /dev/null
+++ b/mineru/doclib/background/parse_server_health.py
@@ -0,0 +1,128 @@
+"""Parse-server health state and periodic health check task."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import subprocess
+import sys
+from dataclasses import dataclass, field
+
+import httpx
+
+logger = logging.getLogger("mineru.health_check")
+
+CHECK_INTERVAL_SEC = 60
+MAX_RESTART_ATTEMPTS = 3
+
+
+@dataclass
+class ParseServerHealth:
+ local_healthy: bool = False
+ local_supported_tiers: list[str] = field(default_factory=list)
+ local_mode: str = "disabled"
+ self_hosted_url: str | None = None
+ remote_healthy: bool = False
+ remote_supported_tiers: list[str] = field(default_factory=list)
+ restart_count: int = 0
+ managed_proc: subprocess.Popen | None = None
+
+
+_parse_server_health = ParseServerHealth()
+
+
+def get_health() -> ParseServerHealth:
+ return _parse_server_health
+
+
+class ParseServerHealthCheck:
+ """Periodically probes parse-server health via GET /v1/tiers."""
+
+ def __init__(self, config_svc) -> None:
+ self.config_svc = config_svc
+ self.running = False
+
+ async def run(self) -> None:
+ self.running = True
+ health = get_health()
+
+ while self.running:
+ await asyncio.sleep(CHECK_INTERVAL_SEC)
+ if not self.running:
+ break
+
+ # refresh config on each cycle (hot-reload)
+ mode = (await self.config_svc.get("parse_server.local.mode")) or "disabled"
+ health.local_mode = mode
+ self_hosted_url = await self.config_svc.get("parse_server.local.self_hosted_url")
+ health.self_hosted_url = self_hosted_url if self_hosted_url else None
+
+ # probe local
+ if health.local_mode != "disabled":
+ url = self._local_url(health)
+ if url:
+ healthy, tiers = await self._probe(url)
+ health.local_healthy = healthy
+ health.local_supported_tiers = tiers
+
+ # probe remote
+ remote_url = (await self.config_svc.get("parse_server.remote.url")) or "https://mineru.net/api"
+ healthy, tiers = await self._probe(remote_url)
+ health.remote_healthy = healthy
+ health.remote_supported_tiers = tiers
+
+ # managed mode: restart if crashed
+ if health.local_mode == "managed" and not health.local_healthy:
+ await self._try_restart_managed(health)
+
+ async def _try_restart_managed(self, health: ParseServerHealth) -> None:
+ if health.restart_count >= MAX_RESTART_ATTEMPTS:
+ logger.error(
+ f"Managed parse-server failed {health.restart_count} restarts, disabling"
+ )
+ health.local_mode = "disabled"
+ return
+
+ health.restart_count += 1
+ managed_tier = (await self.config_svc.get("parse_server.local.managed_tier")) or "standard"
+ logger.info(f"Restarting managed parse-server (attempt {health.restart_count}/{MAX_RESTART_ATTEMPTS})")
+ try:
+ proc = subprocess.Popen(
+ [sys.executable, "-m", "mineru.parser.api_server", "--backend", managed_tier, "--port", "15981"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ health.managed_proc = proc
+ except Exception as exc:
+ logger.error(f"Failed to restart managed parse-server: {exc}")
+
+ @staticmethod
+ async def _probe(base_url: str) -> tuple[bool, list[str]]:
+ 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", [])]
+ return True, tiers
+ except Exception:
+ pass
+ return False, []
+
+ @staticmethod
+ def _local_url(health: ParseServerHealth) -> str | None:
+ if health.local_mode == "managed":
+ return "http://127.0.0.1:15981"
+ if health.local_mode == "self_hosted":
+ return health.self_hosted_url
+ return None
+
+ async def stop(self) -> None:
+ self.running = False
+ health = get_health()
+ if health.managed_proc:
+ try:
+ health.managed_proc.terminate()
+ health.managed_proc.wait(timeout=10)
+ except Exception:
+ pass
diff --git a/mineru/doclib/client.py b/mineru/doclib/client.py
index fdfaa600..edfeb963 100644
--- a/mineru/doclib/client.py
+++ b/mineru/doclib/client.py
@@ -79,6 +79,8 @@ class MineruClient:
tier: str | None = None,
pages: str | None = None,
force: bool = False,
+ remote: bool = False,
+ remote_url: str | None = None,
) -> dict:
return self._post(
"/parse",
@@ -87,6 +89,8 @@ class MineruClient:
"tier": tier,
"pages": pages,
"force": force,
+ "remote": remote,
+ "remote_url": remote_url,
},
)
diff --git a/mineru/doclib/core/db.py b/mineru/doclib/core/db.py
index 63e5ff6b..600fbd6a 100644
--- a/mineru/doclib/core/db.py
+++ b/mineru/doclib/core/db.py
@@ -65,6 +65,9 @@ CREATE_TABLES_SQL = [
locked_at INTEGER,
error_code TEXT,
error_msg TEXT,
+ privacy TEXT NOT NULL DEFAULT 'local',
+ remote_url TEXT,
+ via TEXT,
output_path TEXT,
done_at INTEGER,
created_at INTEGER NOT NULL,
@@ -148,6 +151,9 @@ DEFAULT_CONFIG = {
"ingest_lock_timeout_sec": "60",
"parse_lock_timeout_sec": "1800",
"device_check_interval_sec": "5",
+ "parse_server.local.mode": "disabled",
+ "parse_server.local.managed_tier": "standard",
+ "parse_server.remote.url": "https://mineru.net/api",
}
DEFAULT_EXCLUDE_RULES = [
diff --git a/mineru/doclib/routes/config.py b/mineru/doclib/routes/config.py
index 28480af8..dc3e1255 100644
--- a/mineru/doclib/routes/config.py
+++ b/mineru/doclib/routes/config.py
@@ -36,6 +36,26 @@ async def get_config(request: Request) -> dict:
return {"config": cfg, "watches": watches, "rules": rules}
+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 ────────────────────────────────────────────────────────
diff --git a/mineru/doclib/routes/parse.py b/mineru/doclib/routes/parse.py
index 8b9056c4..c94ccded 100644
--- a/mineru/doclib/routes/parse.py
+++ b/mineru/doclib/routes/parse.py
@@ -19,6 +19,8 @@ async def parse(req: ParseRequest, request: Request) -> dict:
tier=req.tier,
pages=req.pages,
force=req.force,
+ remote=req.remote,
+ remote_url=req.remote_url,
)
return result
@@ -43,7 +45,7 @@ async def parse_content(
tier: str = Query(...),
output: str | None = Query(None),
) -> dict:
- """Read parsed markdown content from per-batch JSON files."""
+ """Read parsed markdown content from saved .md files."""
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)
@@ -56,22 +58,18 @@ async def parse_content(
"error": "Content not found",
}
- import json as _json
-
- # merge all JSON files by page_idx
- pages_by_idx: dict[int, dict] = {}
+ # merge all .md files, sorted by filename
+ parts: list[str] = []
for fname in sorted(os.listdir(tier_dir)):
- if not fname.endswith(".json"):
+ if not fname.endswith(".md"):
continue
try:
with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:
- data = _json.load(f)
- for p in data.get("pdf_info", []):
- pages_by_idx[p["page_idx"]] = p
+ parts.append(f.read())
except Exception:
pass
- if not pages_by_idx:
+ if not parts:
return {
"sha256": sha256,
"tier": tier,
@@ -79,8 +77,7 @@ async def parse_content(
"error": "Content not found",
}
- sorted_pages = [pages_by_idx[i] for i in sorted(pages_by_idx)]
- content = _markdown_from_pages(sorted_pages)
+ content = "\n".join(parts)
if output and output != "-":
os.makedirs(os.path.dirname(os.path.abspath(output)), exist_ok=True)
@@ -89,15 +86,3 @@ async def parse_content(
return {"sha256": sha256, "tier": tier, "output": os.path.abspath(output)}
return {"sha256": sha256, "tier": tier, "content": content}
-
-
-def _markdown_from_pages(pages: list[dict]) -> str:
- """Generate markdown from page dicts — iterate blocks/lines/spans."""
- parts: list[str] = []
- for page in pages:
- for block in page.get("para_blocks", []):
- for line in block.get("lines", []):
- for span in line.get("spans", []):
- if span.get("content"):
- parts.append(span["content"])
- return "\n\n".join(parts)
diff --git a/mineru/doclib/routes/server.py b/mineru/doclib/routes/server.py
index 303db18f..53773aa9 100644
--- a/mineru/doclib/routes/server.py
+++ b/mineru/doclib/routes/server.py
@@ -36,6 +36,7 @@ async def server_status(request: Request) -> dict:
"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": [
{
@@ -61,3 +62,20 @@ async def shutdown(request: Request) -> dict:
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,
+ "supported_tiers": health.local_supported_tiers,
+ },
+ "remote": {
+ "healthy": health.remote_healthy,
+ "supported_tiers": health.remote_supported_tiers,
+ },
+ }
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index fe0026e2..917758a9 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -7,6 +7,8 @@ import errno
import logging
import os
import socket
+import subprocess
+import sys
import time
from collections.abc import Callable
from logging.handlers import RotatingFileHandler
@@ -42,6 +44,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:
from .background.parse_worker import ParseWorkerPool
from .background.device_monitor import DeviceMonitor
from .background.compaction import Compaction
+ from .background.parse_server_health import ParseServerHealthCheck, get_health
data_dir = os.path.expanduser(cfg.server.data_dir)
os.makedirs(data_dir, exist_ok=True)
@@ -67,6 +70,24 @@ def create_app(cfg: Config | None = None) -> FastAPI:
"UPDATE parses SET locked_at = NULL, status = 'failed' WHERE status = 'parsing'"
)
+ # managed mode: start parse-server
+ 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:
+ proc = subprocess.Popen(
+ [sys.executable, "-m", "mineru.parser.api_server", "--backend", managed_tier, "--port", "15981"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ state.parse_server_proc = proc
+ health.managed_proc = proc
+ except Exception:
+ pass
+
# background tasks
state.watch = WatchLoop(state.db, state.config_svc, state.parse_svc)
state.ingest_workers = IngestWorkerPool(
@@ -79,12 +100,14 @@ def create_app(cfg: Config | None = None) -> FastAPI:
state.compaction = Compaction(
state.db, interval_sec=cfg.server.compaction_interval_sec
)
+ 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()
@@ -95,12 +118,21 @@ def create_app(cfg: Config | None = None) -> FastAPI:
@app.on_event("shutdown")
async def shutdown() -> None:
+ # stop managed parse-server
+ if state.parse_server_proc:
+ try:
+ state.parse_server_proc.terminate()
+ state.parse_server_proc.wait(timeout=10)
+ except Exception:
+ pass
+
for comp in [
"watch",
"ingest_workers",
"parse_workers",
"device_monitor",
"compaction",
+ "health_check",
]:
c = getattr(state, comp, None)
if c and hasattr(c, "stop"):
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index 6bb79f39..d53e44be 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -19,6 +19,14 @@ def _now_ms() -> int:
return int(time.time() * 1000)
+class ParseFailure(Exception):
+ """Raised when a parse cannot be completed. Carries an error code for the parses row."""
+
+ def __init__(self, code: str, message: str) -> None:
+ self.code = code
+ self.message = message
+
+
MAX_FTS_CHARS = 30_000
FTS_HEAD_HALF = 15_000
@@ -113,9 +121,7 @@ def expand_pages(pages: str | None, page_count: int) -> str:
# ── text truncation ────────────────────────────────────────────────
-def truncate_head_tail(
- text: str, max_chars: int = MAX_FTS_CHARS, half: int = FTS_HEAD_HALF
-) -> str:
+def truncate_head_tail(text: str, max_chars: int = MAX_FTS_CHARS, half: int = FTS_HEAD_HALF) -> str:
if len(text) <= max_chars:
return text
return text[:half] + "\n...\n" + text[-half:]
@@ -139,25 +145,19 @@ class ParseService:
# ── ingestion (shared) ──────────────────────────────────
- async def ingest_file(
- self, path: str, watch_id: int | None = None
- ) -> dict | None:
+ async def ingest_file(self, path: str, watch_id: int | None = None) -> dict | None:
"""Ingest a file: SHA-256 + metadata + trigger default parse."""
stat = await get_file_stat(path)
sha256 = await compute_sha256(path)
now = _now_ms()
# check if this path is already ingested
- existing_path = await self.db.fetchone(
- "SELECT * FROM files WHERE path=?", (path,)
- )
+ existing_path = await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))
if existing_path and existing_path["sha256"]:
return existing_path
# check if same content (sha256) is already tracked by another path
- existing_sha = await self.db.fetchone(
- "SELECT * FROM files WHERE sha256=?", (sha256,)
- )
+ existing_sha = await self.db.fetchone("SELECT * FROM files WHERE sha256=?", (sha256,))
if existing_sha:
# same file, different path — just add this path pointing to the same doc
await self.db.execute("DELETE FROM files WHERE path=?", (path,))
@@ -279,12 +279,12 @@ class ParseService:
tier: str | None = None,
pages: str | None = None,
force: bool = False,
+ remote: bool = False,
+ remote_url: str | None = None,
) -> dict:
"""Handle a parse request from CLI. Returns info for status polling."""
# ensure file is ingested
- file_row = await self.db.fetchone(
- "SELECT * FROM files WHERE path=? AND scan_status='active'", (path,)
- )
+ file_row = await self.db.fetchone("SELECT * FROM files WHERE path=? AND scan_status='active'", (path,))
if file_row is None or file_row["sha256"] is None:
file_row = await self.ingest_file(path)
if file_row is None:
@@ -296,9 +296,7 @@ class ParseService:
}
sha256 = file_row["sha256"]
- doc = await self.db.fetchone(
- "SELECT page_count FROM docs WHERE sha256=?", (sha256,)
- )
+ doc = await self.db.fetchone("SELECT page_count FROM docs WHERE sha256=?", (sha256,))
page_count = doc["page_count"] if doc else 1
requested_tier = tier or Tier.FLASH
@@ -308,14 +306,15 @@ class ParseService:
if ext in ("docx", "pptx", "xlsx", "doc", "xls", "ppt"):
requested_tier = Tier.FLASH
+ # resolve privacy / remote_url
+ privacy = "remote" if remote else "local"
+
# expand pages
- default_pages = (
- "1~5,-5~-1" if page_count and page_count > 10 else f"1~{page_count}"
- )
+ default_pages = "1~5,-5~-1" if page_count and page_count > 10 else f"1~{page_count}"
raw_pages = pages or default_pages
pages_str = expand_pages(raw_pages, page_count or 1)
- # check cache
+ # check cache — (sha256, tier) regardless of privacy
if not force:
done_batches = await self.db.fetchall(
"SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done'",
@@ -330,7 +329,6 @@ class ParseService:
"status": "done",
"tip": "Cached. Use --force to re-parse.",
}
- # only parse pages not yet covered
uncovered = pages_uncovered(pages_str, done_batches)
if not uncovered:
return {
@@ -360,8 +358,9 @@ class ParseService:
# insert new batch
now = _now_ms()
await self.db.execute(
- "INSERT INTO parses (sha256, tier, pages, status, priority, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?)",
- (sha256, requested_tier, pages_str, ParseStatus.PENDING, now, now),
+ "INSERT INTO parses (sha256, tier, pages, status, privacy, remote_url, priority, created_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)",
+ (sha256, requested_tier, pages_str, ParseStatus.PENDING, privacy, remote_url, now, now),
)
return {
@@ -399,11 +398,11 @@ class ParseService:
sha256 = task["sha256"]
tier = task["tier"]
pages = task["pages"]
+ privacy = task.get("privacy", "local")
+ remote_url = task.get("remote_url")
# guard
- current = await self.db.fetchone(
- "SELECT status FROM parses WHERE id=?", (task["id"],)
- )
+ current = await self.db.fetchone("SELECT status FROM parses WHERE id=?", (task["id"],))
if current is None or current["status"] != ParseStatus.PARSING:
return False
@@ -413,57 +412,27 @@ class ParseService:
(sha256,),
)
if file_row is None:
- await self.db.execute(
- "UPDATE parses SET status=?, error_code=?, error_msg=?, locked_at=NULL WHERE id=?",
- (
- ParseStatus.FAILED,
- "no_accessible_file",
- "No active file found for this document",
- task["id"],
- ),
- )
+ await self._fail_task(task["id"], "no_accessible_file", "No active file found for this document")
return False
output_dir = os.path.join(self.data_dir, "parsed", sha256[:2], sha256, tier)
os.makedirs(output_dir, exist_ok=True)
- # call mineru.parser
+ # route parse based on tier
+ via = "local"
try:
- from mineru.parser import parse
- except ImportError:
- await self.db.execute(
- "UPDATE parses SET status=?, error_code=?, error_msg=?, locked_at=NULL WHERE id=?",
- (
- ParseStatus.FAILED,
- "no_engine",
- "mineru.parser module not available",
- task["id"],
- ),
- )
+ if tier == Tier.FLASH:
+ results = await self._parse_via_local(file_row, tier, pages)
+ else:
+ results, via = await self._parse_via_api(file_row, tier, pages, privacy, remote_url)
+ except ParseFailure as exc:
+ await self._fail_task(task["id"], exc.code, exc.message)
return False
-
- try:
- # parse each contiguous range sequentially, collect results
- results: list = []
- ranges = _split_ranges(pages, file_row, sha256)
- for start, end in ranges:
- result = await asyncio.to_thread(
- parse,
- file_row["path"],
- backend=_tier_to_backend(tier),
- start_page_id=start,
- end_page_id=end,
- output_dir=output_dir,
- )
- results.append(result)
except Exception as exc:
- await self.db.execute(
- "UPDATE parses SET status=?, error_code=?, error_msg=?, locked_at=NULL WHERE id=?",
- (ParseStatus.FAILED, "parse_failed", str(exc)[:500], task["id"]),
- )
+ await self._fail_task(task["id"], "parse_failed", str(exc)[:500])
return False
- # save per-batch JSON (each parses row → one JSON file)
+ # save per-batch markdown + JSON
md_text = ""
for result in results:
md = result.markdown() if hasattr(result, "markdown") else ""
@@ -473,12 +442,18 @@ class ParseService:
import json as _json
pages_key = _safe_filename(task["pages"])
+ md_path = os.path.join(output_dir, f"{pages_key}.md")
json_path = os.path.join(output_dir, f"{pages_key}.json")
+ os.makedirs(output_dir, exist_ok=True)
+ try:
+ with open(md_path, "w", encoding="utf-8") as f:
+ f.write(md_text)
+ except Exception:
+ pass
new_pages: list[dict] = []
for r in results:
if hasattr(r, "to_dict"):
new_pages.extend(r.to_dict().get("pdf_info", []))
-
os.makedirs(output_dir, exist_ok=True)
try:
with open(json_path, "w", encoding="utf-8") as f:
@@ -495,11 +470,122 @@ class ParseService:
# mark done
now = _now_ms()
await self.db.execute(
- "UPDATE parses SET status=?, done_at=?, locked_at=NULL, output_path=?, updated_at=? WHERE id=?",
- (ParseStatus.DONE, now, output_dir, now, task["id"]),
+ "UPDATE parses SET status=?, done_at=?, locked_at=NULL, via=?, output_path=?, updated_at=? WHERE id=?",
+ (ParseStatus.DONE, now, via, output_dir, now, task["id"]),
)
return True
+ # ── parse routing helpers ─────────────────────────────────────
+
+ async def _parse_via_local(self, file_row: dict, tier: str, pages: str) -> list:
+ """Parse via local library call."""
+ from mineru.parser import parse
+
+ result = await asyncio.to_thread(
+ parse,
+ file_row["path"],
+ backend=_tier_to_backend(tier),
+ page_range=pages,
+ )
+ return [result]
+
+ async def _parse_via_api(
+ self,
+ file_row: dict,
+ tier: str,
+ pages: str,
+ privacy: str,
+ remote_url: str | None,
+ ) -> tuple[list, str]:
+ """Parse via HTTP API (local or remote parse-server). Returns (results, via)."""
+ from mineru.parser.api_client import MinerUApiParser
+
+ base_url, api_key, via = await self._resolve_api_target(privacy, remote_url, tier)
+
+ # resolve and validate tier against server capabilities
+ resolved_tier = self._resolve_tier(tier, via)
+
+ parser = MinerUApiParser(
+ api_url=base_url,
+ api_key=api_key,
+ tier=resolved_tier,
+ )
+ result = await parser.parse_async(file_row["path"], page_range=pages)
+ return [result], via
+
+ @staticmethod
+ def _resolve_tier(tier: str, via: str) -> str:
+ """Resolve and validate tier against parse-server capabilities.
+
+ - ``auto`` → pick best available tier from health check (pro > standard)
+ - specified tier → validate against supported_tiers, raise tier_mismatch if unsupported
+ """
+ from mineru.doclib.background.parse_server_health import get_health
+
+ health = get_health()
+ if via == "remote":
+ supported = health.remote_supported_tiers
+ else:
+ supported = health.local_supported_tiers
+
+ if not supported:
+ raise ParseFailure("engine_unavailable", "Parse-server health status unknown, cannot validate tier")
+
+ if tier == "auto":
+ tier_order = ["pro", "standard"]
+ for t in tier_order:
+ if t in supported:
+ return t
+ raise ParseFailure("tier_mismatch", f"No supported tier found. Available: {supported}")
+
+ if tier not in supported:
+ raise ParseFailure("tier_mismatch", f"Tier '{tier}' not supported by parse-server. Available: {supported}")
+ return tier
+
+ async def _resolve_api_target(self, privacy: str, remote_url: str | None, tier: str) -> tuple[str, str | None, str]:
+ """Resolve the api target URL based on privacy and config.
+
+ Returns (base_url, api_key, via_label).
+ """
+ from mineru.doclib.background.parse_server_health import get_health
+
+ health = get_health()
+
+ if privacy == "remote":
+ url = remote_url or (await self.config_svc.get("parse_server.remote.url")) or "https://mineru.net/api"
+ api_key = os.environ.get("MINERU_API_KEY") or (await self.config_svc.get("parse_server.remote.api_key"))
+ if not health.remote_healthy:
+ # try fallback to local
+ local_mode = (await self.config_svc.get("parse_server.local.mode")) or "disabled"
+ if local_mode != "disabled" and health.local_healthy:
+ local_url = _local_parse_server_url(local_mode, health)
+ if local_url:
+ return local_url, api_key, "local"
+ raise ParseFailure("parse_server_unavailable", "Remote parse-server unavailable and no local fallback")
+ return url, api_key, "remote"
+
+ # privacy == local
+ local_mode = (await self.config_svc.get("parse_server.local.mode")) or "disabled"
+ if local_mode == "disabled":
+ raise ParseFailure("no_engine", "Local parse-server is disabled. Use --tier flash or --remote.")
+
+ local_url = _local_parse_server_url(local_mode, health)
+ if local_url is None:
+ raise ParseFailure("engine_unavailable", "Local parse-server URL not configured.")
+
+ if not health.local_healthy:
+ raise ParseFailure("engine_unavailable", "Local parse-server is not ready. Please wait or check server status.")
+
+ api_key = os.environ.get("MINERU_API_KEY") or (await self.config_svc.get("parse_server.local.self_hosted_api_key"))
+ return local_url, api_key, "local"
+
+ async def _fail_task(self, task_id: int, code: str, message: str) -> None:
+ now = _now_ms()
+ await self.db.execute(
+ "UPDATE parses SET status=?, error_code=?, error_msg=?, locked_at=NULL, updated_at=? WHERE id=?",
+ (ParseStatus.FAILED, code, message, now, task_id),
+ )
+
async def get_parse_status(self, sha256: str, tier: str) -> dict | None:
"""Get aggregate status for a doc+tier. Returns latest batch info."""
done = await self.db.fetchone(
@@ -538,13 +624,9 @@ class ParseService:
# ── internal helpers ────────────────────────────────────────
- async def _maybe_update_fts(
- self, sha256: str, tier: str, text: str, file_row: dict
- ) -> None:
+ async def _maybe_update_fts(self, sha256: str, tier: str, text: str, file_row: dict) -> None:
existing_tier = await self.fts.get_tier(sha256)
- if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(
- tier, -1
- ):
+ if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(tier, -1):
return # current FTS data is from a higher or equal tier
text = truncate_head_tail(text)
@@ -558,15 +640,11 @@ class ParseService:
)
async def _maybe_update_docs_meta(self, sha256: str, tier: str) -> None:
- doc = await self.db.fetchone(
- "SELECT meta_tier FROM docs WHERE sha256=?", (sha256,)
- )
+ doc = await self.db.fetchone("SELECT meta_tier FROM docs WHERE sha256=?", (sha256,))
if doc is None:
return
existing_tier = doc.get("meta_tier")
- if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(
- tier, -1
- ):
+ if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(tier, -1):
return
# for now just update meta_tier; full metadata update comes when
@@ -590,29 +668,13 @@ def _tier_to_backend(tier: str) -> str:
return mapping.get(tier, "pipeline")
-def _split_ranges(
- pages: str, file_row: dict, sha256: str
-) -> list[tuple[int, int | None]]:
- """Split a pages range string into contiguous (start, end) tuples
- suitable for the current parse() API. start is 0-based, end is inclusive."""
- page_set = parse_range_set(pages)
- if not page_set:
- return [(0, None)]
-
- sorted_pages = sorted(page_set)
- ranges: list[tuple[int, int | None]] = []
- start = sorted_pages[0]
- end = start
-
- for p in sorted_pages[1:]:
- if p == end + 1:
- end = p
- else:
- ranges.append((start - 1, end - 1)) # convert to 0-based
- start = p
- end = p
- ranges.append((start - 1, end - 1))
- return ranges
+def _local_parse_server_url(mode: str, health: object) -> str | None:
+ """Resolve local parse-server URL from mode and health state."""
+ if mode == "managed":
+ return "http://127.0.0.1:15981"
+ if mode == "self_hosted":
+ return getattr(health, "self_hosted_url", None)
+ return None
def _safe_filename(s: str) -> str:
diff --git a/mineru/doclib/types.py b/mineru/doclib/types.py
index 3d8bcf98..5bdb349f 100644
--- a/mineru/doclib/types.py
+++ b/mineru/doclib/types.py
@@ -13,6 +13,8 @@ class ParseRequest(BaseModel):
tier: str | None = None
pages: str | None = None
force: bool = False
+ remote: bool = False
+ remote_url: str | None = None
class ParseResponse(BaseModel):
diff --git a/mineru/errors.py b/mineru/errors.py
index 92431107..aee4fefa 100644
--- a/mineru/errors.py
+++ b/mineru/errors.py
@@ -23,6 +23,7 @@ _ERROR_TYPE_MAP: dict[str, str] = {
"job_already_terminal": "invalid_request_error",
"model_not_found": "invalid_request_error",
"not_cached": "invalid_request_error",
+ "tier_mismatch": "invalid_request_error",
# authentication_error
"invalid_api_key": "authentication_error",
# permission_error
@@ -43,6 +44,7 @@ _ERROR_TYPE_MAP: dict[str, str] = {
"server_busy": "api_error",
"remote_timeout": "api_error",
"remote_unreachable": "api_error",
+ "parse_server_unavailable": "api_error",
}
diff --git a/mineru/parser/__init__.py b/mineru/parser/__init__.py
index a94aa513..1198fe95 100644
--- a/mineru/parser/__init__.py
+++ b/mineru/parser/__init__.py
@@ -3,31 +3,23 @@ from __future__ import annotations
from pathlib import Path
-from mineru.types import Block, Line, PageInfo, Span
-
-from .api_parser import MinerUApiParser
-from .base import DocumentParser
-from .html_parser import HtmlParser
-from .office_parser import DocxParser, OfficeBaseParser, PptxParser, XlsxParser
-from .parse_result import ParseResult
-from .pdf_parser import PdfBaseParser, PdfHybridParser, PdfPipelineParser, PdfVlmParser
+from .api_client import MinerUApiParser
+from .base import DocumentParser, ParseResult
+from .html import HtmlParser
+from .office import DocxParser, PptxParser, XlsxParser
+from .pdf import PdfFlashParser, PdfHybridParser, PdfPipelineParser, PdfVlmParser
__all__ = [
- "Block",
"DocumentParser",
"DocxParser",
"HtmlParser",
- "Line",
"MinerUApiParser",
- "OfficeBaseParser",
- "PageInfo",
"ParseResult",
- "PdfBaseParser",
+ "PdfFlashParser",
"PdfHybridParser",
"PdfPipelineParser",
"PdfVlmParser",
"PptxParser",
- "Span",
"XlsxParser",
"parse",
]
@@ -43,9 +35,7 @@ def parse(
table_enable: bool = True,
image_analysis: bool = True,
server_url: str | None = None,
- start_page_id: int = 0,
- end_page_id: int | None = None,
- output_dir: str = "./output",
+ page_range: str = "",
) -> ParseResult:
from ..utils.guess_suffix_or_lang import guess_suffix_by_path
@@ -58,9 +48,9 @@ def parse(
"pptx": PptxParser,
"xlsx": XlsxParser,
}[suffix]
- parser = parser_cls(output_dir=output_dir)
+ parser = parser_cls()
elif suffix in ("html", "htm"):
- parser = HtmlParser(output_dir=output_dir)
+ parser = HtmlParser()
elif backend == "pipeline":
parser = PdfPipelineParser(
backend=backend,
@@ -68,9 +58,6 @@ def parse(
lang=lang,
formula_enable=formula_enable,
table_enable=table_enable,
- output_dir=output_dir,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
)
elif backend.startswith("vlm-"):
parser = PdfVlmParser(
@@ -79,9 +66,6 @@ def parse(
table_enable=table_enable,
server_url=server_url,
image_analysis=image_analysis,
- output_dir=output_dir,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
)
elif backend.startswith("hybrid-"):
parser = PdfHybridParser(
@@ -92,52 +76,10 @@ def parse(
table_enable=table_enable,
server_url=server_url,
image_analysis=image_analysis,
- output_dir=output_dir,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
)
elif backend == "flash":
- return _parse_flash(path, start_page_id, end_page_id, output_dir)
+ parser = PdfFlashParser()
else:
raise ValueError(f"Unknown backend: {backend}")
- return parser.parse(path)
-
-
-def _parse_flash(path: str | Path, start_page_id: int, end_page_id: int | None, output_dir: str = "./output") -> ParseResult:
- """Flash parse — extract text via pypdfium2 and build proper ParseResult."""
- from pathlib import Path as P
-
- from mineru.types import Block, Line, PageInfo, Span
-
- from .. import version
- from ..backend.flash.pdf_extractor import extract_text
-
- path = P(path)
- text = extract_text(str(path), start_page=start_page_id, end_page=end_page_id)
- pages_text = text.split("\n\n") # each page separated by double newline
-
- page_count = len(pages_text)
- current_page = start_page_id
-
- pages: list[PageInfo] = []
- for pt in pages_text:
- if not pt.strip():
- continue
- block = Block(
- type="text",
- lines=[Line(spans=[Span(type="text", content=pt.strip())])],
- )
- page = PageInfo(
- page_idx=current_page,
- para_blocks=[block],
- )
- pages.append(page)
- current_page += 1
-
- return ParseResult(
- pages=pages,
- _backend="flash",
- _version_name=version.__version__,
- _file_name=path.stem,
- )
+ return parser.parse(path, page_range=page_range)
diff --git a/mineru/parser/api_parser.py b/mineru/parser/api_client.py
similarity index 90%
rename from mineru/parser/api_parser.py
rename to mineru/parser/api_client.py
index e4ac3934..23b434ef 100644
--- a/mineru/parser/api_parser.py
+++ b/mineru/parser/api_client.py
@@ -15,8 +15,17 @@ from typing import Any
from mineru.types import PageInfo
-from .base import DocumentParser
-from .parse_result import ParseResult
+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")
class MinerUApiParser(DocumentParser):
@@ -29,7 +38,7 @@ class MinerUApiParser(DocumentParser):
# cloud (paid)
parser = MinerUApiParser(
- api_url="https://mineru.net/api", token="msk_...",
+ api_url="https://mineru.net/api", api_key="msk_...",
backend="vlm",
)
@@ -38,11 +47,9 @@ class MinerUApiParser(DocumentParser):
Constructor parameters (matching :class:`DocumentParser`):
- - ``backend`` → v1 ``preset`` (``"pipeline"`` / ``"vlm"`` / ``"auto"``)
+ - ``backend`` → v1 ``tier`` (``"standard"`` / ``"pro"`` / ``"auto"``)
- ``method`` → v1 ``ocr`` (``"auto"`` / ``"ocr"`` / ``"txt"``)
- - ``lang`` → v1 ``language``
- - ``formula_enable`` / ``table_enable`` / ``image_analysis`` → mapped directly
- - ``start_page_id`` / ``end_page_id`` → v1 ``page_range``
+ - ``image_analysis`` → mapped directly
- ``return_md`` / ``return_middle_json`` / ``return_content_list`` /
``return_images`` → v1 ``output_formats``
"""
@@ -51,37 +58,41 @@ class MinerUApiParser(DocumentParser):
self,
*,
api_url: str,
- token: str | None = None,
- **kwargs: Any,
+ api_key: str | None = None,
+ tier: str | None = None,
+ method: str = "auto",
+ image_analysis: bool = True,
) -> None:
- super().__init__(**kwargs)
self._base = api_url.rstrip("/")
- self._token = token
+ self._api_key = api_key
self._local = self._is_localhost(self._base)
+ self.backend = _tier_to_backend(tier) if tier else "auto"
+ self.method = method
+ self.image_analysis = image_analysis
# ── DocumentParser interface ─────────────────────────────────────
- def parse(self, path: str | Path) -> ParseResult:
+ def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
file_path = Path(path)
if not file_path.exists():
raise FileNotFoundError(file_path)
- payload = self._build_payload(file_path)
+ payload = self._build_payload(file_path, page_range)
job = self._do_parse(payload)
return self._build_result(job, file_path.name)
- async def parse_async(self, path: str | Path) -> 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)
- payload = self._build_payload(file_path)
+ payload = self._build_payload(file_path, page_range)
job = await self._async_do_parse(payload)
return await self._async_build_result(job, file_path.name)
# ── payload construction ─────────────────────────────────────────
- def _build_payload(self, file_path: Path) -> dict[str, Any]:
+ def _build_payload(self, file_path: Path, page_range: str) -> dict[str, Any]:
source: dict[str, Any]
if self._local:
source = {"type": "local", "path": str(file_path)}
@@ -91,29 +102,25 @@ class MinerUApiParser(DocumentParser):
source = {"type": "file_id", "file_id": file_id}
options: dict[str, Any] = {
- "language": self.lang,
"ocr": self._ocr_mode(),
- "formula": self.formula_enable,
- "table": self.table_enable,
"image_analysis": self.image_analysis,
}
- page_range = self._page_range_str()
if page_range:
options["page_range"] = page_range
return {
"files": [{"source": source, "options": options}],
- "preset": self._preset(),
+ "tier": self._tier(),
"output_formats": self._output_formats(),
}
- def _preset(self) -> str:
+ def _tier(self) -> str:
if self.backend == "pipeline":
- return "pipeline"
+ return "standard"
if self.backend.startswith("vlm"):
- return "vlm"
+ return "pro"
if self.backend.startswith("html"):
- return "html"
+ return "auto"
return "auto"
def _ocr_mode(self) -> str:
@@ -123,13 +130,6 @@ class MinerUApiParser(DocumentParser):
return "txt"
return "auto"
- def _page_range_str(self) -> str | None:
- if self.start_page_id == 0 and self.end_page_id is None:
- return None
- start = self.start_page_id + 1 # 0-based → 1-based
- end = self.end_page_id or ""
- return f"{start}-{end}".rstrip("-")
-
def _output_formats(self) -> list[str]:
return ["json"]
@@ -137,8 +137,8 @@ class MinerUApiParser(DocumentParser):
def _headers(self) -> dict[str, str]:
h: dict[str, str] = {}
- if self._token:
- h["Authorization"] = f"Bearer {self._token}"
+ if self._api_key:
+ h["Authorization"] = f"Bearer {self._api_key}"
return h
@staticmethod
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
new file mode 100644
index 00000000..e10b7c6a
--- /dev/null
+++ b/mineru/parser/api_server.py
@@ -0,0 +1,1996 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""MinerU v1 REST API — Pydantic models and FastAPI route definitions.
+
+The API surface defined here matches the NEW-API.md specification.
+All route handlers are stubs (raise 501 Not Implemented) — only the
+contract (models, path/query params, response schemas, status codes)
+is defined. Business logic belongs in downstream integration modules.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import dataclasses
+import hashlib
+import os
+import pathlib
+import secrets
+import shutil
+import tempfile
+import time
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Annotated, Any, AsyncIterator, Callable, Literal
+
+import click
+from fastapi import APIRouter, Body, Depends, FastAPI, HTTPException, Path, Query, Request, Response, status
+from fastapi.middleware.gzip import GZipMiddleware
+from fastapi.responses import JSONResponse, StreamingResponse
+from pydantic import BaseModel, ConfigDict, Field
+
+# ── literal type aliases (no enum imports) ──────────────────────────
+
+JobStatus = Literal["queued", "running", "completed", "partial", "failed", "canceled"]
+"""Job lifecycle states."""
+
+FileStatus = Literal["queued", "running", "completed", "failed"]
+"""Per-file status within a job."""
+
+UploadStatus = Literal["pending", "completed", "cancelled", "expired"]
+"""Upload lifecycle states."""
+
+Tier = Literal["auto", "standard", "pro"]
+"""Pre-configured parsing tier."""
+
+OutputFormat = Literal[
+ "markdown",
+ "json",
+ "content_list",
+ "content_list_v2",
+ "images",
+ "html",
+ "latex",
+ "docx",
+ "zip",
+]
+"""Output artifact formats."""
+
+OutputFormatReqToken = Literal["html", "latex", "docx"]
+"""Output formats that require a valid API key."""
+
+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."""
+
+FilePurpose = Literal["parse", "parse_output", "input_image"]
+"""File purpose: source files, parse artifacts, or chat/response input images."""
+
+SSEEventType = Literal[
+ "status",
+ "file_started",
+ "file_completed",
+ "file_failed",
+ "done",
+ "error",
+]
+"""SSE event types."""
+
+
+# ── helper ───────────────────────────────────────────────────────────
+
+
+def _env_flag(name: str, default: bool = True) -> bool:
+ val = os.getenv(name)
+ if val is None:
+ return default
+ return val.strip().lower() in ("1", "true", "yes", "on")
+
+
+# ═══════════════════════════════════════════════════════════════════════
+# MODELS
+# ═══════════════════════════════════════════════════════════════════════
+
+_PYDANTIC_CONFIG = ConfigDict(extra="forbid")
+
+
+# ── Error ────────────────────────────────────────────────────────────
+
+
+class ErrorDetail(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ type: str
+ code: str | None = None
+ message: str
+ param: str | None = None
+
+
+class ErrorResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ error: ErrorDetail
+
+
+# ── Health ───────────────────────────────────────────────────────────
+
+
+class ModelHealthStatus(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ pipeline: str = "ok"
+ vlm: str = "ok"
+ html: str = "ok"
+
+
+class HealthFeatures(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ sse: bool = False
+ webhook: bool = False
+
+
+class HealthResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ status: str = "ok"
+ version: str
+ backend_version: str | None = None
+ models: ModelHealthStatus | None = None
+ features: HealthFeatures = Field(default_factory=lambda: HealthFeatures(sse=False, webhook=False))
+
+
+# ── Models API ───────────────────────────────────────────────────────
+
+
+class ModelInfo(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ id: str
+ object: Literal["model"] = "model"
+ created: int
+ owned_by: str = "mineru"
+ description: str | None = None
+
+
+class ModelListResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ object: Literal["list"] = "list"
+ data: list[ModelInfo]
+
+
+# ── Tiers API ────────────────────────────────────────────────────────
+
+
+class TierInfo(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ id: Tier
+ description: str
+ current_model: str | None = None
+
+
+class TierListResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ object: Literal["list"] = "list"
+ data: list[TierInfo]
+
+
+# ── Upload ───────────────────────────────────────────────────────────
+
+
+class ExpiresAfter(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ anchor: Literal["created_at"] = "created_at"
+ seconds: int = Field(default=3600, ge=3600, le=2592000)
+
+
+class CreateUploadRequest(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ filename: str = Field(min_length=1)
+ bytes: int = Field(gt=0)
+ mime_type: str = Field(min_length=1)
+ purpose: Literal["parse", "input_image"] = "parse"
+ sha256sum: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
+ expires_after: ExpiresAfter | None = None
+
+
+class CompleteUploadRequest(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ sha256sum: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
+
+
+class UploadResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ id: str
+ object: Literal["upload"] = "upload"
+ bytes: int
+ created_at: int
+ expires_at: int
+ filename: str
+ purpose: FilePurpose = "parse"
+ mime_type: str
+ sha256sum: str | None = None
+ status: UploadStatus
+ upload_url: str | None = None
+ upload_method: Literal["PUT"] | None = None
+ upload_headers: dict[str, str] | None = None
+ file: FileObjectModel | None = None
+
+
+# ── File ─────────────────────────────────────────────────────────────
+
+
+class FileObjectModel(BaseModel):
+ """A file resource (source or parse output)."""
+
+ model_config = _PYDANTIC_CONFIG
+ id: str
+ object: Literal["file"] = "file"
+ bytes: int
+ created_at: int
+ expires_at: int | None = None
+ filename: str
+ purpose: FilePurpose
+ sha256sum: str | None = None
+
+
+class FileDeletionResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ id: str
+ object: Literal["file"] = "file"
+ deleted: bool = True
+
+
+class FileListResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ object: Literal["list"] = "list"
+ data: list[FileObjectModel]
+ first_id: str | None = None
+ last_id: str | None = None
+ has_more: bool = False
+
+
+# ── Job sources ──────────────────────────────────────────────────────
+
+
+class FileIdSource(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ type: Literal["file_id"] = "file_id"
+ file_id: str
+
+
+class UrlSource(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ type: Literal["url"] = "url"
+ url: str
+
+
+class InlineSource(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ type: Literal["inline"] = "inline"
+ name: str = Field(min_length=1)
+ data: str = Field(min_length=1)
+
+
+class LocalSource(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ type: Literal["local"] = "local"
+ path: str = Field(min_length=1)
+
+
+FileSource = Annotated[
+ FileIdSource | UrlSource | InlineSource | LocalSource,
+ Field(discriminator="type"),
+]
+
+
+# ── 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_CONFIG
+ source: FileSource
+ options: FileOptions | None = None
+
+
+class CallbackConfig(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ url: str
+ secret: str | None = None
+
+
+class CreateJobRequest(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ files: list[JobFileEntry] = Field(min_length=1)
+ tier: Tier = "auto"
+ output_formats: list[OutputFormat] = ["markdown"]
+ wait: int = Field(default=0, ge=0)
+ callback: CallbackConfig | None = None
+
+
+# ── Job responses ────────────────────────────────────────────────────
+
+
+class JobLinks(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ self: str
+ events: str
+ cancel: str
+
+
+class JobProgress(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ completed: int = 0
+ failed: int = 0
+ total: int = 0
+
+
+class FileMetadata(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ pages: int | None = None
+ model_used: str | None = None
+ processing_time_ms: int | None = None
+ backend_version: str | None = None
+
+
+class OutputFileRef(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ file_id: str
+ bytes: int
+ content: str | dict[str, Any] | None = None # inline for markdown in sync response
+
+
+class ImageOutputRef(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ path: str
+ file_id: str
+ bytes: int
+
+
+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."""
+
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
+ markdown: OutputFileRef | None = None
+ json_: OutputFileRef | None = Field(default=None, serialization_alias="json", validation_alias="json")
+ content_list: OutputFileRef | None = None
+ content_list_v2: OutputFileRef | None = None
+ html: OutputFileRef | None = None
+ latex: OutputFileRef | None = None
+ docx: OutputFileRef | None = None
+ zip: OutputFileRef | None = None
+ images: list[ImageOutputRef] | None = None
+
+
+class JobFileResult(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ file_id: str
+ name: str
+ status: FileStatus
+ metadata: FileMetadata | None = None
+ output_files: OutputFiles | None = None
+ error: ErrorDetail | None = None
+
+
+class JobAsyncResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ job_id: str
+ status: JobStatus
+ created_at: str # ISO-8601 UTC
+ started_at: str | None = None
+ finished_at: str | None = None
+ tier: Tier
+ output_formats: list[OutputFormat]
+ access_level: AccessLevel
+ progress: JobProgress | None = None
+ files: list[JobFileResult]
+ links: JobLinks
+
+
+class JobListItem(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ job_id: str
+ status: JobStatus
+ created_at: str
+ files_count: int
+
+
+class JobListResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ object: Literal["list"] = "list"
+ data: list[JobListItem]
+ first_id: str | None = None
+ last_id: str | None = None
+ has_more: bool = False
+
+
+class JobCancelResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ job_id: str
+ status: Literal["canceled"] = "canceled"
+ canceled_at: str
+
+
+# ── Usage ────────────────────────────────────────────────────────────
+
+
+class UsageBillingPeriod(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ start: str # ISO-8601
+ end: str | None = None
+
+
+class UsageCurrent(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ pages_processed: int = 0
+ files_processed: int = 0
+ jobs_created: int = 0
+
+
+class UsageLimits(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ max_pages_per_file: int = 1000
+ max_file_size_bytes: int = 209715200
+ max_files_per_job: int = 100
+ max_concurrent_jobs: int = 1
+ max_file_retention_days: int | None = None
+
+
+class UsageResponse(BaseModel):
+ model_config = _PYDANTIC_CONFIG
+ object: Literal["usage"] = "usage"
+ access_level: AccessLevel
+ billing_period: UsageBillingPeriod
+ current: UsageCurrent
+ limits: UsageLimits
+
+
+# ═══════════════════════════════════════════════════════════════════════
+# STORE
+# ═══════════════════════════════════════════════════════════════════════
+
+
+@dataclass
+class _UploadRecord:
+ id: str
+ filename: str
+ bytes: int
+ mime_type: str
+ created_at: int
+ expires_at: int
+ purpose: FilePurpose = "parse"
+ sha256sum: str | None = None
+ status: UploadStatus = "pending"
+ file_id: str | None = None # set on complete
+
+
+@dataclass
+class _FileRecord:
+ id: str
+ filename: str
+ bytes: int
+ created_at: int
+ purpose: FilePurpose
+ sha256sum: str | None = None
+ expires_at: int | None = None
+ upload_id: str | None = None
+
+
+class FileStore:
+ """Content-addressed blob storage with in-memory metadata."""
+
+ def __init__(self, root: pathlib.Path) -> None:
+ self._root = root
+ self._blobs = root / "blobs"
+ self._blobs.mkdir(parents=True, exist_ok=True)
+ self._uploads: dict[str, _UploadRecord] = {}
+ self._files: dict[str, _FileRecord] = {}
+
+ # ── ID generation ────────────────────────────────────────────────
+
+ @staticmethod
+ def _new_upload_id() -> str:
+ return "upload_" + secrets.token_hex(12)
+
+ @staticmethod
+ def _new_file_id() -> str:
+ return "file-" + secrets.token_hex(12)
+
+ # ── blob helpers ─────────────────────────────────────────────────
+
+ @staticmethod
+ def _blob_path(sha256hex: str) -> pathlib.PurePosixPath:
+ return pathlib.PurePosixPath(sha256hex[:2]) / sha256hex[2:]
+
+ def _blob_abs(self, sha256hex: str) -> pathlib.Path:
+ return self._blobs / self._blob_path(sha256hex)
+
+ def blob_exists(self, sha256hex: str) -> bool:
+ return self._blob_abs(sha256hex).is_file()
+
+ def store_blob(self, data: bytes, *, sha256hex: str) -> None:
+ p = self._blob_abs(sha256hex)
+ if not p.is_file():
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_bytes(data)
+
+ def read_blob(self, sha256hex: str) -> bytes:
+ p = self._blob_abs(sha256hex)
+ if not p.is_file():
+ raise FileNotFoundError(sha256hex)
+ return p.read_bytes()
+
+ # ── uploads ──────────────────────────────────────────────────────
+
+ def create_upload(self, req: CreateUploadRequest, *, base_url: str = "") -> UploadResponse:
+ now = int(time.time())
+ expires_seconds = req.expires_after.seconds if req.expires_after else 3600
+
+ # sha256sum dedup
+ if req.sha256sum and self.blob_exists(req.sha256sum):
+ file_id = self._new_file_id()
+ self._files[file_id] = _FileRecord(
+ id=file_id,
+ filename=req.filename,
+ bytes=req.bytes,
+ created_at=now,
+ purpose=req.purpose,
+ sha256sum=req.sha256sum,
+ expires_at=now + expires_seconds,
+ )
+ upload_id = self._new_upload_id()
+ self._uploads[upload_id] = _UploadRecord(
+ id=upload_id,
+ filename=req.filename,
+ bytes=req.bytes,
+ mime_type=req.mime_type,
+ created_at=now,
+ expires_at=now + expires_seconds,
+ purpose=req.purpose,
+ sha256sum=req.sha256sum,
+ status="completed",
+ file_id=file_id,
+ )
+ return self._make_upload_response(self._uploads[upload_id], base_url=base_url, expose_upload_url=True)
+
+ upload_id = self._new_upload_id()
+ self._uploads[upload_id] = _UploadRecord(
+ id=upload_id,
+ filename=req.filename,
+ bytes=req.bytes,
+ mime_type=req.mime_type,
+ created_at=now,
+ expires_at=now + expires_seconds,
+ purpose=req.purpose,
+ sha256sum=req.sha256sum,
+ )
+ return self._make_upload_response(self._uploads[upload_id], base_url=base_url, expose_upload_url=True)
+
+ def get_upload(self, upload_id: str) -> _UploadRecord:
+ rec = self._uploads.get(upload_id)
+ if rec is None:
+ raise HTTPException(
+ status_code=404,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="invalid_request_error", code="upload_not_found", message=f"Upload {upload_id} not found"
+ ),
+ ).model_dump(by_alias=True),
+ )
+ return rec
+
+ def _read_upload_data(self, upload_id: str) -> bytes:
+ p = self._blobs / "_uploads" / upload_id
+ if not p.is_file():
+ raise HTTPException(
+ status_code=409,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="invalid_request_error", code="upload_not_ready", message="Upload bytes not yet received"
+ ),
+ ).model_dump(by_alias=True),
+ )
+ return p.read_bytes()
+
+ def complete_upload(self, upload_id: str, sha256hex: str | None) -> UploadResponse:
+ rec = self.get_upload(upload_id)
+ if rec.status == "completed":
+ raise HTTPException(
+ status_code=409,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="invalid_request_error", code="upload_already_terminal", message="Upload is already completed"
+ ),
+ ).model_dump(by_alias=True),
+ )
+ if rec.status in ("cancelled", "expired"):
+ raise HTTPException(
+ status_code=409,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="invalid_request_error", code="upload_already_terminal", message=f"Upload is {rec.status}"
+ ),
+ ).model_dump(by_alias=True),
+ )
+
+ # compute sha256 from uploaded data if not provided
+ data = self._read_upload_data(upload_id)
+ actual_sha = hashlib.sha256(data).hexdigest()
+
+ if sha256hex and sha256hex != actual_sha:
+ raise HTTPException(
+ status_code=400,
+ detail=ErrorResponse(
+ 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"),
+ ).model_dump(by_alias=True),
+ )
+
+ # move from upload blob to content-addressed blob
+ sha = sha256hex or actual_sha
+ if not self.blob_exists(sha):
+ self.store_blob(data, sha256hex=sha)
+ # remove temp upload blob
+ (self._blobs / "_uploads" / upload_id).unlink(missing_ok=True)
+
+ now = int(time.time())
+ file_id = self._new_file_id()
+ self._files[file_id] = _FileRecord(
+ id=file_id,
+ filename=rec.filename,
+ bytes=rec.bytes,
+ created_at=now,
+ purpose=rec.purpose,
+ sha256sum=sha,
+ expires_at=rec.expires_at,
+ upload_id=upload_id,
+ )
+ rec.status = "completed"
+ rec.file_id = file_id
+ rec.sha256sum = sha
+ return self._make_upload_response(rec)
+
+ def cancel_upload(self, upload_id: str) -> UploadResponse:
+ rec = self.get_upload(upload_id)
+ if rec.status in ("completed", "cancelled", "expired"):
+ raise HTTPException(
+ status_code=409,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="invalid_request_error", code="upload_already_terminal", message=f"Upload is {rec.status}"
+ ),
+ ).model_dump(by_alias=True),
+ )
+ rec.status = "cancelled"
+ return self._make_upload_response(rec)
+
+ def store_upload_data(self, upload_id: str, data: bytes) -> None:
+ """Store raw bytes for an upload (before complete)."""
+ rec = self.get_upload(upload_id)
+ if rec.status != "pending":
+ raise HTTPException(
+ status_code=409,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="invalid_request_error", code="upload_already_terminal", message=f"Upload is {rec.status}"
+ ),
+ ).model_dump(by_alias=True),
+ )
+ # store temporarily under upload_id in blobs dir
+ p = self._blobs / "_uploads" / upload_id
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_bytes(data)
+
+ def _make_upload_response(
+ self, rec: _UploadRecord, *, base_url: str = "", expose_upload_url: bool = False
+ ) -> UploadResponse:
+ resp = UploadResponse(
+ id=rec.id,
+ bytes=rec.bytes,
+ created_at=rec.created_at,
+ expires_at=rec.expires_at,
+ filename=rec.filename,
+ mime_type=rec.mime_type,
+ purpose=rec.purpose,
+ sha256sum=rec.sha256sum,
+ status=rec.status,
+ )
+ if expose_upload_url and rec.status == "pending":
+ resp.upload_url = f"{base_url}/v1/uploads/{rec.id}/content"
+ resp.upload_method = "PUT"
+ resp.upload_headers = {"Content-Type": rec.mime_type}
+ elif rec.status == "completed" and rec.file_id and rec.file_id in self._files:
+ resp.file = self._make_file_object(self._files[rec.file_id])
+ return resp
+
+ # ── files ────────────────────────────────────────────────────────
+
+ def create_file_for_output(self, filename: str, data: bytes, *, sha256hex: str | None = None) -> str:
+ """Store parse-output data and return a file_id."""
+ sha = sha256hex or hashlib.sha256(data).hexdigest()
+ self.store_blob(data, sha256hex=sha)
+ now = int(time.time())
+ file_id = self._new_file_id()
+ self._files[file_id] = _FileRecord(
+ id=file_id,
+ filename=filename,
+ bytes=len(data),
+ created_at=now,
+ purpose="parse_output",
+ sha256sum=sha,
+ )
+ return file_id
+
+ def get_file(self, file_id: str) -> _FileRecord:
+ rec = self._files.get(file_id)
+ if rec is None:
+ raise HTTPException(
+ status_code=404,
+ detail=ErrorResponse(
+ error=ErrorDetail(type="invalid_request_error", code="file_not_found", message=f"File {file_id} not found"),
+ ).model_dump(by_alias=True),
+ )
+ return rec
+
+ @staticmethod
+ def _make_file_object(rec: _FileRecord) -> FileObjectModel:
+ return FileObjectModel(
+ id=rec.id,
+ bytes=rec.bytes,
+ created_at=rec.created_at,
+ expires_at=rec.expires_at,
+ filename=rec.filename,
+ purpose=rec.purpose,
+ sha256sum=rec.sha256sum,
+ )
+
+ def read_file_data(self, file_id: str) -> bytes:
+ rec = self.get_file(file_id)
+ if rec.purpose != "parse_output":
+ raise HTTPException(
+ status_code=403,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="permission_error", code="feature_requires_api_key", message="Source files cannot be downloaded"
+ ),
+ ).model_dump(by_alias=True),
+ )
+ if rec.sha256sum is None:
+ raise HTTPException(
+ status_code=500,
+ detail=ErrorResponse(
+ error=ErrorDetail(type="api_error", code="internal_error", message="File has no sha256sum"),
+ ).model_dump(by_alias=True),
+ )
+ return self.read_blob(rec.sha256sum)
+
+ def delete_file(self, file_id: str) -> None:
+ if file_id not in self._files:
+ raise HTTPException(
+ status_code=404,
+ detail=ErrorResponse(
+ 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]
+
+ def list_files(
+ self,
+ *,
+ after: str | None,
+ limit: int,
+ order: str,
+ purpose: FilePurpose | None,
+ ) -> FileListResponse:
+ recs = list(self._files.values())
+ # filter
+ if purpose is not None:
+ recs = [r for r in recs if r.purpose == purpose]
+ # sort by created_at
+ reverse = order == "desc"
+ recs.sort(key=lambda r: r.created_at, reverse=reverse)
+ # cursor
+ start = 0
+ if after is not None:
+ for i, r in enumerate(recs):
+ if r.id == after:
+ start = i + 1
+ break
+ page = recs[start : start + limit]
+ return FileListResponse(
+ data=[self._make_file_object(r) 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),
+ )
+
+ # ── defaults → app state ─────────────────────────────────────────
+
+ def install(self, app_state: Any) -> None:
+ app_state.file_store = self
+
+
+# ═══════════════════════════════════════════════════════════════════════
+# DEPENDENCIES
+# ═══════════════════════════════════════════════════════════════════════
+
+
+def _get_store(request: Request) -> FileStore:
+ return request.app.state.file_store
+
+
+def _get_job_store(request: Request) -> JobStore:
+ return request.app.state.job_store
+
+
+def _resolve_access_level(request: Request) -> AccessLevel:
+ """Return ``"registered"`` when the server has an API key configured
+ (the middleware already validated it), ``"anonymous"`` otherwise."""
+ return (
+ "registered" if request.app.state.api_key else "anonymous"
+ ) # ═══════════════════════════════════════════════════════════════════════
+
+
+# JOB STORE
+# ═══════════════════════════════════════════════════════════════════════
+
+_SUPPORTED_SUFFIXES: dict[str, str] = {
+ ".pdf": "pdf",
+ ".png": "image",
+ ".jpg": "image",
+ ".jpeg": "image",
+ ".jp2": "image",
+ ".webp": "image",
+ ".gif": "image",
+ ".bmp": "image",
+ ".tiff": "image",
+ ".docx": "docx",
+ ".pptx": "pptx",
+ ".xlsx": "xlsx",
+ ".html": "html",
+ ".htm": "html",
+}
+
+_OUTPUT_FORMATS_LOCAL = {"markdown", "json", "content_list", "content_list_v2", "images", "zip"}
+
+
+@dataclass
+class _JobRecord:
+ id: str
+ status: JobStatus = "queued"
+ created_at: str = ""
+ started_at: str | None = None
+ finished_at: str | None = None
+ tier: Tier = "auto"
+ output_formats: list[OutputFormat] = None # type: ignore[assignment]
+ progress: JobProgress | None = None
+ files: list[JobFileResult] = None # type: ignore[assignment]
+ links: JobLinks | None = None
+
+ def __post_init__(self) -> None:
+ if self.files is None:
+ self.files = []
+ if self.output_formats is None:
+ self.output_formats = ["markdown"]
+ if self.progress is None:
+ self.progress = JobProgress()
+
+
+class JobStore:
+ def __init__(self, concurrency: int = 1) -> None:
+ self._jobs: dict[str, _JobRecord] = {}
+ self._semaphore = asyncio.Semaphore(max(1, concurrency))
+ self._started_at = JobStore._now()
+
+ @staticmethod
+ def _new_job_id() -> str:
+ return "job_" + secrets.token_hex(12)
+
+ @staticmethod
+ def _now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ def create(self, req: CreateJobRequest, file_store: FileStore) -> _JobRecord:
+ job_id = self._new_job_id()
+ now = self._now()
+ rec = _JobRecord(
+ id=job_id,
+ status="queued",
+ created_at=now,
+ tier=req.tier,
+ output_formats=req.output_formats,
+ links=JobLinks(
+ self=f"/v1/parse/jobs/{job_id}",
+ events=f"/v1/parse/jobs/{job_id}/events",
+ cancel=f"/v1/parse/jobs/{job_id}",
+ ),
+ )
+ 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,
+ name=name,
+ status="queued",
+ )
+ )
+ rec.progress.total = len(rec.files)
+ self._jobs[job_id] = rec
+ return rec
+
+ def get(self, job_id: str) -> _JobRecord:
+ rec = self._jobs.get(job_id)
+ if rec is None:
+ raise HTTPException(
+ status_code=404,
+ detail=ErrorResponse(
+ error=ErrorDetail(type="invalid_request_error", code="job_not_found", message=f"Job {job_id} not found"),
+ ).model_dump(by_alias=True),
+ )
+ return rec
+
+ def cancel(self, job_id: str) -> _JobRecord:
+ rec = self.get(job_id)
+ if rec.status in ("completed", "partial", "failed", "canceled"):
+ raise HTTPException(
+ status_code=409,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="invalid_request_error", code="job_already_terminal", message=f"Job is {rec.status}"
+ ),
+ ).model_dump(by_alias=True),
+ )
+ rec.status = "canceled"
+ return rec
+
+ def list_jobs(
+ self,
+ *,
+ status_filter: str | None,
+ limit: int,
+ after: str | None,
+ created_after: str | None,
+ order: str = "desc",
+ ) -> JobListResponse:
+ recs = list(self._jobs.values())
+ if status_filter:
+ allowed = set(status_filter.split(","))
+ recs = [r for r in recs if r.status in allowed]
+ if created_after:
+ recs = [r for r in recs if r.created_at >= created_after]
+ reverse = order == "desc"
+ recs.sort(key=lambda r: r.created_at, reverse=reverse)
+ start = 0
+ if after:
+ for i, r in enumerate(recs):
+ if r.id == after:
+ start = i + 1
+ break
+ page = 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],
+ first_id=page[0].id if page else None,
+ last_id=page[-1].id if page else None,
+ has_more=(start + limit) < len(recs),
+ )
+
+ def build_response(self, rec: _JobRecord, access_level: AccessLevel = "registered") -> JobAsyncResponse:
+ return JobAsyncResponse(
+ job_id=rec.id,
+ status=rec.status,
+ created_at=rec.created_at,
+ started_at=rec.started_at,
+ finished_at=rec.finished_at,
+ tier=rec.tier,
+ output_formats=rec.output_formats,
+ access_level=access_level,
+ progress=rec.progress,
+ files=rec.files,
+ links=rec.links or JobLinks(self="", events="", cancel=""),
+ )
+
+ 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()
+ )
+ return UsageResponse(
+ access_level=access_level,
+ billing_period=UsageBillingPeriod(start=self._started_at),
+ current=UsageCurrent(
+ pages_processed=pages,
+ files_processed=completed,
+ jobs_created=len(self._jobs),
+ ),
+ limits=UsageLimits(
+ max_concurrent_jobs=self._semaphore._value,
+ ),
+ )
+
+ def install(self, app_state: Any) -> None:
+ app_state.job_store = self
+
+
+# ── source helpers ───────────────────────────────────────────────────
+
+
+def _source_name(source: FileSource, file_store: FileStore | None = None) -> str:
+ if isinstance(source, FileIdSource) and file_store is not None:
+ try:
+ return file_store.get_file(source.file_id).filename
+ except Exception:
+ pass
+ return source.file_id
+ if isinstance(source, UrlSource):
+ return source.url.rsplit("/", 1)[-1].split("?")[0] or "unknown"
+ if isinstance(source, InlineSource):
+ return source.name
+ if isinstance(source, LocalSource):
+ return pathlib.Path(source.path).name
+ return "unknown"
+
+
+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)
+ if rec.sha256sum is None:
+ raise ValueError("File has no content")
+ return file_store.read_blob(rec.sha256sum)
+ if isinstance(source, UrlSource):
+ import httpx
+
+ async with httpx.AsyncClient(timeout=url_timeout) as cli:
+ r = await cli.get(source.url)
+ r.raise_for_status()
+ return r.content
+ if isinstance(source, InlineSource):
+ return base64.b64decode(source.data)
+ if isinstance(source, LocalSource):
+ return pathlib.Path(source.path).read_bytes()
+ raise ValueError(f"Unknown source type: {type(source)}")
+
+
+def _suffix_type(filename: str) -> str:
+ ext = pathlib.Path(filename).suffix.lower()
+ return _SUPPORTED_SUFFIXES.get(ext, "")
+
+
+async def _run_job(
+ rec: _JobRecord,
+ req: CreateJobRequest,
+ file_store: FileStore,
+ vlm_available: bool,
+ *,
+ url_timeout: int = 60,
+) -> None:
+ rec.status = "running"
+ rec.started_at = JobStore._now()
+
+ with tempfile.TemporaryDirectory(prefix="mineru_job_") as tmpdir:
+ for i, entry in enumerate(req.files):
+ if rec.status == "canceled":
+ break
+ fr = rec.files[i]
+ try:
+ data = await _extract_bytes(entry.source, file_store, url_timeout=url_timeout)
+ stype = _suffix_type(fr.name)
+ if not stype:
+ raise ValueError(f"Unsupported file type: {fr.name}")
+
+ # write to temp file for parsers that require a path
+ suffix = pathlib.Path(fr.name).suffix or ".pdf"
+ 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)
+
+ # collect outputs
+ out_formats = set(rec.output_formats)
+ output_files = OutputFiles()
+ import json as _json
+
+ for fmt in ("markdown", "json", "content_list", "content_list_v2", "images"):
+ if fmt not in out_formats:
+ continue
+ if fmt == "markdown":
+ md = result.markdown()
+ content_bytes = (md or "").encode("utf-8")
+ 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":
+ mj = _json.dumps(
+ {"pages": [dataclasses.asdict(p) for p in result.pages]},
+ ensure_ascii=False,
+ ).encode("utf-8")
+
+ 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))
+ 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":
+ 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))
+ elif fmt == "images":
+ img_refs: list[ImageOutputRef] = []
+ for img_path, img_bytes in result.images().items():
+ sha = hashlib.sha256(img_bytes).hexdigest()
+ file_store.store_blob(img_bytes, sha256hex=sha)
+ img_fid = file_store.create_file_for_output(pathlib.Path(img_path).name, img_bytes, sha256hex=sha)
+ img_refs.append(ImageOutputRef(path=img_path, file_id=img_fid, bytes=len(img_bytes)))
+ output_files.images = img_refs
+
+ # zip
+ if "zip" in out_formats:
+ import io as _io
+ import zipfile as _zipfile
+
+ buf = _io.BytesIO()
+ with _zipfile.ZipFile(buf, "w", _zipfile.ZIP_DEFLATED) as zf:
+ for fmt_name, attr in [
+ ("markdown", "markdown"),
+ ("json", "json_"),
+ ("content_list", "content_list"),
+ ("content_list_v2", "content_list_v2"),
+ ]:
+ 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)
+ )
+ except Exception:
+ pass
+ if output_files.images:
+ for ir in output_files.images:
+ try:
+ zf.writestr(ir.path, file_store.read_file_data(ir.file_id))
+ except Exception:
+ pass
+ zip_bytes = buf.getvalue()
+ zip_sha = hashlib.sha256(zip_bytes).hexdigest()
+ file_store.store_blob(zip_bytes, sha256hex=zip_sha)
+ zip_fid = file_store.create_file_for_output(f"{fr.name}.zip", zip_bytes, sha256hex=zip_sha)
+ output_files.zip = OutputFileRef(file_id=zip_fid, bytes=len(zip_bytes))
+
+ fr.status = "completed"
+ fr.output_files = output_files
+ 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))
+ rec.progress.failed += 1
+
+ if rec.status != "canceled":
+ if rec.progress.failed == rec.progress.total:
+ rec.status = "failed"
+ elif rec.progress.failed > 0:
+ rec.status = "partial"
+ else:
+ rec.status = "completed"
+ rec.finished_at = JobStore._now()
+
+
+# ═══════════════════════════════════════════════════════════════════════
+# ROUTER
+# ═══════════════════════════════════════════════════════════════════════
+
+_router = APIRouter(prefix="/v1")
+
+# Reusable error response maps
+_ERR_400: dict[int | str, dict[str, Any]] = {400: {"model": ErrorResponse}}
+_ERR_401: dict[int | str, dict[str, Any]] = {401: {"model": ErrorResponse}}
+_ERR_403: dict[int | str, dict[str, Any]] = {403: {"model": ErrorResponse}}
+_ERR_404: dict[int | str, dict[str, Any]] = {404: {"model": ErrorResponse}}
+_ERR_409: dict[int | str, dict[str, Any]] = {409: {"model": ErrorResponse}}
+_ERR_413: dict[int | str, dict[str, Any]] = {413: {"model": ErrorResponse}}
+_ERR_429: dict[int | str, dict[str, Any]] = {429: {"model": ErrorResponse}}
+
+
+# ── Health ───────────────────────────────────────────────────────────
+
+
+@_router.get(
+ "/health",
+ response_model=HealthResponse,
+ status_code=status.HTTP_200_OK,
+ responses={503: {"model": ErrorResponse}},
+ tags=["Health"],
+)
+async def get_health() -> HealthResponse:
+ """Health check endpoint."""
+ from mineru.version import __version__
+
+ return HealthResponse(version=__version__, backend_version=__version__, models=ModelHealthStatus())
+
+
+# ── Models ───────────────────────────────────────────────────────────
+
+
+@_router.get(
+ "/models",
+ response_model=ModelListResponse,
+ status_code=status.HTTP_200_OK,
+ tags=["Models"],
+)
+async def list_models(request: Request) -> ModelListResponse:
+ """List all available parsing models."""
+ model_ids: list[str] = request.app.state.model_ids
+ now = int(time.time())
+ return ModelListResponse(
+ data=[ModelInfo(id=mid, created=now) for mid in model_ids],
+ )
+
+
+@_router.get(
+ "/models/{model}",
+ response_model=ModelInfo,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404, **_ERR_403},
+ tags=["Models"],
+)
+async def get_model(
+ request: Request,
+ model: str = Path(description="Model ID"),
+) -> ModelInfo:
+ """Retrieve a single model by ID."""
+ model_ids: list[str] = request.app.state.model_ids
+ if model not in model_ids:
+ raise HTTPException(
+ status_code=404,
+ detail=ErrorResponse(
+ 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())
+ return ModelInfo(id=model, created=now)
+
+
+# ── Tiers ────────────────────────────────────────────────────────────
+
+
+@_router.get(
+ "/tiers",
+ response_model=TierListResponse,
+ status_code=status.HTTP_200_OK,
+ tags=["Tiers"],
+)
+async def list_tiers(request: Request) -> TierListResponse:
+ """List all available parser tiers."""
+ tiers: list[dict[str, Any]] = request.app.state.tiers
+ return TierListResponse(
+ data=[TierInfo(**p) for p in tiers],
+ )
+
+
+# ── Uploads ──────────────────────────────────────────────────────────
+
+
+@_router.post(
+ "/uploads",
+ response_model=None,
+ status_code=status.HTTP_200_OK,
+ responses={200: {"model": UploadResponse}, **_ERR_400, **_ERR_413},
+ tags=["Uploads"],
+)
+async def create_upload(
+ body: CreateUploadRequest,
+ request: Request,
+ store: FileStore = Depends(_get_store),
+) -> Response:
+ """Create an Upload."""
+ base = str(request.base_url).rstrip("/")
+ resp = store.create_upload(body, base_url=base)
+ if resp.status == "completed":
+ return JSONResponse(content=resp.model_dump(by_alias=True), status_code=200)
+ return JSONResponse(content=resp.model_dump(by_alias=True), status_code=200)
+
+
+@_router.get(
+ "/uploads/{upload_id}",
+ response_model=UploadResponse,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404},
+ tags=["Uploads"],
+)
+async def get_upload(
+ upload_id: str = Path(description="Upload ID (upload_...)"),
+ store: FileStore = Depends(_get_store),
+) -> UploadResponse:
+ """Retrieve an Upload by ID."""
+ return store._make_upload_response(store.get_upload(upload_id))
+
+
+@_router.put(
+ "/uploads/{upload_id}/content",
+ response_model=None,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404, **_ERR_409},
+ tags=["Uploads"],
+)
+async def upload_content(
+ upload_id: str = Path(description="Upload ID"),
+ data: bytes = Body(media_type="application/octet-stream"),
+ store: FileStore = Depends(_get_store),
+) -> Response:
+ """Upload raw bytes for an upload (OpenAI-compatible)."""
+ store.store_upload_data(upload_id, data)
+ return Response(status_code=200)
+
+
+@_router.post(
+ "/uploads/{upload_id}/complete",
+ response_model=UploadResponse,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_400, **_ERR_404, **_ERR_409},
+ tags=["Uploads"],
+)
+async def complete_upload(
+ upload_id: str = Path(description="Upload ID"),
+ body: CompleteUploadRequest | None = None,
+ store: FileStore = Depends(_get_store),
+) -> UploadResponse:
+ """Complete an upload, creating the File object."""
+ return store.complete_upload(upload_id, body.sha256sum if body else None)
+
+
+@_router.post(
+ "/uploads/{upload_id}/cancel",
+ response_model=UploadResponse,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404, **_ERR_409},
+ tags=["Uploads"],
+)
+async def cancel_upload(
+ upload_id: str = Path(description="Upload ID"),
+ store: FileStore = Depends(_get_store),
+) -> UploadResponse:
+ """Cancel an in-progress upload."""
+ return store.cancel_upload(upload_id)
+
+
+# ── Files ────────────────────────────────────────────────────────────
+
+
+@_router.get(
+ "/files",
+ response_model=FileListResponse,
+ status_code=status.HTTP_200_OK,
+ tags=["Files"],
+)
+async def list_files(
+ after: str | None = Query(default=None, description="Cursor: last_id from previous page"),
+ limit: int = Query(default=100, ge=1, le=1000),
+ order: Literal["asc", "desc"] = Query(default="desc"),
+ purpose: FilePurpose | None = Query(default=None),
+ store: FileStore = Depends(_get_store),
+) -> FileListResponse:
+ """List files for the current tenant."""
+ return store.list_files(after=after, limit=limit, order=order, purpose=purpose)
+
+
+@_router.get(
+ "/files/{file_id}",
+ response_model=FileObjectModel,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404},
+ tags=["Files"],
+)
+async def get_file(
+ file_id: str = Path(description="File ID (file-...)"),
+ store: FileStore = Depends(_get_store),
+) -> FileObjectModel:
+ """Retrieve file metadata."""
+ return store._make_file_object(store.get_file(file_id))
+
+
+@_router.get(
+ "/files/{file_id}/content",
+ response_model=None,
+ status_code=status.HTTP_200_OK,
+ responses={
+ 200: {"description": "File content"},
+ 302: {"description": "Redirect to CDN (cloud mode)"},
+ **_ERR_404,
+ **_ERR_403,
+ },
+ tags=["Files"],
+)
+async def get_file_content(
+ file_id: str = Path(description="File ID"),
+ store: FileStore = Depends(_get_store),
+) -> Response:
+ """Download parse-output content."""
+ data = store.read_file_data(file_id)
+ return Response(content=data, media_type="application/octet-stream")
+
+
+@_router.delete(
+ "/files/{file_id}",
+ response_model=FileDeletionResponse,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404},
+ tags=["Files"],
+)
+async def delete_file(
+ file_id: str = Path(description="File ID"),
+ store: FileStore = Depends(_get_store),
+) -> FileDeletionResponse:
+ """Delete a file from the current tenant view."""
+ store.delete_file(file_id)
+ return FileDeletionResponse(id=file_id, deleted=True)
+
+
+# ── Parse Jobs ───────────────────────────────────────────────────────
+
+
+@_router.post(
+ "/parse/jobs",
+ response_model=None,
+ status_code=status.HTTP_202_ACCEPTED,
+ responses={
+ 200: {"model": JobAsyncResponse},
+ 202: {"model": JobAsyncResponse},
+ **_ERR_400,
+ **_ERR_403,
+ **_ERR_429,
+ },
+ tags=["Jobs"],
+)
+async def create_job(
+ body: CreateJobRequest,
+ request: Request,
+ file_store: FileStore = Depends(_get_store),
+ job_store: JobStore = Depends(_get_job_store),
+ access_level: AccessLevel = Depends(_resolve_access_level),
+) -> Response:
+ """Create a parse job."""
+ # validate output formats — advanced formats require API key
+ for fmt in body.output_formats:
+ if fmt in ("html", "latex", "docx") and access_level == "anonymous":
+ raise HTTPException(
+ status_code=403,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="permission_error",
+ code="feature_requires_api_key",
+ message=f"Output format '{fmt}' requires an API key",
+ ),
+ ).model_dump(by_alias=True),
+ )
+ if fmt not in _OUTPUT_FORMATS_LOCAL:
+ raise HTTPException(
+ status_code=400,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ type="invalid_request_error", code="invalid_request", message=f"Unknown output format: {fmt}"
+ ),
+ ).model_dump(by_alias=True),
+ )
+
+ # validate wait vs server limit
+ max_wait: int = request.app.state.max_wait
+ if body.wait != 0 and (body.wait < 5 or body.wait > max_wait):
+ raise HTTPException(
+ status_code=400,
+ detail=ErrorResponse(
+ error=ErrorDetail(
+ 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:
+ 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",
+ ),
+ ).model_dump(by_alias=True),
+ )
+
+ rec = job_store.create(body, file_store)
+ url_timeout_val: int = request.app.state.url_timeout
+ vlm_available_val = vlm_available
+
+ if 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))
+ try:
+ await asyncio.wait_for(task, timeout=body.wait)
+ except asyncio.TimeoutError:
+ pass
+ if 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)
+
+ # async — fire and forget
+ async def _bg_run() -> None:
+ async with job_store._semaphore:
+ await _run_job(rec, body, file_store, vlm_available_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)
+
+
+@_router.get(
+ "/parse/jobs/{job_id}",
+ response_model=JobAsyncResponse,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404},
+ tags=["Jobs"],
+)
+async def get_job(
+ job_id: str = Path(description="Job ID (job_...)"),
+ job_store: JobStore = Depends(_get_job_store),
+) -> JobAsyncResponse:
+ """Retrieve a job's current status and results."""
+ return job_store.build_response(job_store.get(job_id))
+
+
+@_router.get(
+ "/parse/jobs/{job_id}/events",
+ response_model=None,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404},
+ tags=["Jobs"],
+)
+async def get_job_events(
+ job_id: str = Path(description="Job ID"),
+ job_store: JobStore = Depends(_get_job_store),
+) -> StreamingResponse:
+ """SSE stream of job status events."""
+ rec = job_store.get(job_id)
+
+ async def _event_stream() -> Any:
+ last_status = rec.status
+ yielded: set[str] = set() # file names already yielded per-file events
+
+ def _yield_event(event: str, data: str) -> str:
+ return f"event: {event}\ndata: {data}\n\n"
+
+ yield _yield_event(
+ "status",
+ f'{{"status":"{rec.status}","progress":{{"completed":{rec.progress.completed},"failed":{rec.progress.failed},"total":{rec.progress.total}}}}}',
+ )
+
+ while rec.status in ("queued", "running"):
+ if rec.status != last_status:
+ yield _yield_event(
+ "status",
+ f'{{"status":"{rec.status}","progress":{{"completed":{rec.progress.completed},"failed":{rec.progress.failed},"total":{rec.progress.total}}}}}',
+ )
+ last_status = rec.status
+
+ for fr in rec.files:
+ name = fr.name or fr.file_id
+ if fr.status == "running" and name not in yielded:
+ 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"}}')
+ 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}"}}}}')
+ yielded.add(f"done_{name}")
+
+ await asyncio.sleep(1)
+
+ yield _yield_event("done", f'{{"job_id":"{rec.id}","status":"{rec.status}"}}')
+
+ return StreamingResponse(_event_stream(), media_type="text/event-stream")
+
+
+@_router.get(
+ "/parse/jobs",
+ response_model=JobListResponse,
+ status_code=status.HTTP_200_OK,
+ tags=["Jobs"],
+)
+async def list_jobs(
+ status_filter: str | None = Query(default=None, alias="status", description="Filter by status (comma-separated)"),
+ limit: int = Query(default=20, ge=1, le=100, description="Items per page"),
+ after: str | None = Query(default=None, description="Pagination cursor (last_id from previous page)"),
+ order: Literal["asc", "desc"] = Query(default="desc", description="Sort by created_at"),
+ created_after: str | None = Query(default=None, description="ISO-8601 lower bound for created_at"),
+ 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)
+
+
+@_router.delete(
+ "/parse/jobs/{job_id}",
+ response_model=JobCancelResponse,
+ status_code=status.HTTP_200_OK,
+ responses={**_ERR_404, **_ERR_409},
+ tags=["Jobs"],
+)
+async def cancel_job(
+ job_id: str = Path(description="Job ID"),
+ job_store: JobStore = Depends(_get_job_store),
+) -> JobCancelResponse:
+ """Cancel a queued or running job."""
+ rec = job_store.cancel(job_id)
+ return JobCancelResponse(job_id=rec.id, status="canceled", canceled_at=JobStore._now())
+
+
+# ── Usage ─────────────────────────────────────────────────────────────
+
+
+@_router.get(
+ "/usage",
+ response_model=UsageResponse,
+ status_code=status.HTTP_200_OK,
+ tags=["Usage"],
+)
+async def get_usage(
+ request: Request,
+ job_store: JobStore = Depends(_get_job_store),
+ access_level: AccessLevel = Depends(_resolve_access_level),
+) -> UsageResponse:
+ """Query current usage and limits."""
+ return job_store.usage(access_level)
+
+
+# ═══════════════════════════════════════════════════════════════════════
+# APP FACTORY
+# ═══════════════════════════════════════════════════════════════════════
+
+
+def _build_v1_router() -> APIRouter:
+ """Build and return the /v1 router."""
+ return _router
+
+
+def create_app(
+ *,
+ upload_dir: str = "",
+ backend: str = "pipeline",
+ concurrency: int = 1,
+ url_timeout: int = 60,
+ max_wait: int = 600,
+ api_key: str | None = None,
+) -> FastAPI:
+ """Create a FastAPI application implementing the MinerU v1 REST API.
+
+ Parameters
+ ----------
+ upload_dir:
+ Directory for uploaded files and parse artifacts.
+ backend:
+ 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:
+ Timeout in seconds for downloading url sources (default 60).
+ max_wait:
+ Maximum seconds for the ``wait`` parameter (default 300).
+ api_key:
+ Optional API key. When set, clients must pass ``Authorization: Bearer <key>``
+ to access list endpoints and advanced output formats.
+ """
+ upload_dir = upload_dir or os.getenv("MINERU_UPLOAD_DIR", "")
+ backend = backend or os.getenv("MINERU_BACKEND", "pipeline")
+ 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)))
+ _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},
+ ]
+
+ @asynccontextmanager
+ async def _lifespan(application: FastAPI) -> AsyncIterator[None]:
+ application.state.upload_dir = _upload_dir
+ application.state.backend = backend
+ application.state.model_ids = _model_ids
+ application.state.tiers = _tiers
+ application.state.concurrency = concurrency
+ application.state.url_timeout = url_timeout
+ application.state.max_wait = max_wait
+ application.state.api_key = _api_key
+ yield
+ if not upload_dir and _upload_dir.exists():
+ shutil.rmtree(_upload_dir, ignore_errors=True)
+
+ enable_docs = _env_flag("MINERU_API_ENABLE_FASTAPI_DOCS", default=True)
+
+ application = FastAPI(
+ title="MinerU API",
+ version="1.0.0",
+ openapi_url="/openapi.json" if enable_docs else None,
+ docs_url="/docs" if enable_docs else None,
+ redoc_url="/redoc" if enable_docs else None,
+ lifespan=_lifespan,
+ )
+ application.state.upload_dir = _upload_dir
+ application.state.backend = backend
+ application.state.model_ids = _model_ids
+ application.state.tiers = _tiers
+ application.state.concurrency = concurrency
+ application.state.url_timeout = url_timeout
+ application.state.max_wait = max_wait
+ application.state.api_key = _api_key
+ FileStore(_upload_dir).install(application.state)
+ JobStore(concurrency=concurrency).install(application.state)
+ application.add_middleware(GZipMiddleware, minimum_size=1000)
+
+ _PUBLIC_PATHS = frozenset({"/v1/health", "/v1/models", "/v1/tiers"})
+ _PUBLIC_PREFIXES = ("/openapi", "/docs", "/redoc")
+
+ async def _auth_middleware(request: Request, call_next: Callable[[Request], Any]) -> Any:
+ path = request.url.path
+ if path in _PUBLIC_PATHS or any(path.startswith(p) for p in _PUBLIC_PREFIXES) or path.startswith("/v1/models/"):
+ return await call_next(request)
+ api_key = (request.app.state.api_key or "").strip()
+ if not api_key:
+ return await call_next(request)
+ auth = request.headers.get("Authorization", "")
+ if not auth.startswith("Bearer ") or auth[7:] != api_key:
+ return JSONResponse(
+ status_code=401,
+ content=ErrorResponse(
+ error=ErrorDetail(
+ type="authentication_error",
+ code="invalid_api_key",
+ message="Invalid or missing API key",
+ ),
+ ).model_dump(by_alias=True),
+ )
+ return await call_next(request)
+
+ application.middleware("http")(_auth_middleware)
+ application.include_router(_build_v1_router())
+ return application
+
+
+# Module-level app for uvicorn reload: "mineru.parser.api_server:app"
+app = create_app()
+
+
+# ── CLI ──────────────────────────────────────────────────────────────
+
+
[email protected]("--host", default="127.0.0.1", help="Server host")
[email protected]("--port", default=8000, type=int, help="Server port")
[email protected]("--reload", is_flag=True, help="Enable auto-reload (development)")
+ "--upload-dir",
+ default="",
+ help="Upload directory (default: auto-created temp dir)",
+ type=click.Path(file_okay=False, writable=True, resolve_path=True),
+)
+ "--backend",
+ default="pipeline",
+ type=click.Choice(["pipeline", "vlm"]),
+ help="Server backend: 'pipeline' (CV+OCR) or 'vlm' (Vision Language Model)",
+)
+ "--concurrency",
+ default=1,
+ type=int,
+ help="Maximum concurrent parse jobs (default: 1)",
+)
+ "--url-timeout",
+ default=60,
+ type=int,
+ help="Timeout in seconds for url source downloads (default: 60)",
+)
+ "--max-wait",
+ default=600,
+ type=int,
+ help="Maximum seconds for the wait parameter (default: 600)",
+)
+ "--api-key",
+ default=None,
+ type=str,
+ help="Optional API key. When set, clients must pass Authorization: Bearer <key> to access protected endpoints.",
+)
+def main(
+ host: str,
+ port: int,
+ reload: bool,
+ upload_dir: str,
+ backend: str,
+ concurrency: int,
+ url_timeout: int,
+ max_wait: int,
+ api_key: str | None,
+) -> None:
+ """Start the MinerU v1 REST API server."""
+ import uvicorn
+
+ if upload_dir:
+ os.environ["MINERU_UPLOAD_DIR"] = upload_dir
+ if backend:
+ os.environ["MINERU_BACKEND"] = backend
+ os.environ["MINERU_CONCURRENCY"] = str(concurrency)
+ os.environ["MINERU_URL_TIMEOUT"] = str(url_timeout)
+ os.environ["MINERU_MAX_WAIT"] = str(max_wait)
+ if reload:
+ 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,
+ backend=backend,
+ concurrency=concurrency,
+ url_timeout=url_timeout,
+ max_wait=max_wait,
+ api_key=api_key,
+ ),
+ host=host,
+ port=port,
+ )
+
+
+if __name__ == "__main__":
+ main()
+
+__all__ = [
+ # app
+ "app",
+ "create_app",
+ # enums (Literal aliases)
+ "JobStatus",
+ "FileStatus",
+ "UploadStatus",
+ "Tier",
+ "AccessLevel",
+ "OutputFormat",
+ "SourceType",
+ "OcrMode",
+ "FilePurpose",
+ "SSEEventType",
+ # request models
+ "CreateUploadRequest",
+ "CompleteUploadRequest",
+ "CreateJobRequest",
+ "JobFileEntry",
+ "FileOptions",
+ "CallbackConfig",
+ # source models
+ "FileIdSource",
+ "UrlSource",
+ "InlineSource",
+ "LocalSource",
+ "FileSource",
+ # response models
+ "ErrorDetail",
+ "ErrorResponse",
+ "HealthFeatures",
+ "HealthResponse",
+ "ModelInfo",
+ "ModelListResponse",
+ "TierInfo",
+ "TierListResponse",
+ "UploadResponse",
+ "FileObjectModel",
+ "FileDeletionResponse",
+ "FileListResponse",
+ "JobAsyncResponse",
+ "JobLinks",
+ "JobProgress",
+ "FileMetadata",
+ "OutputFileRef",
+ "ImageOutputRef",
+ "OutputFiles",
+ "JobFileResult",
+ "JobListItem",
+ "JobListResponse",
+ "JobCancelResponse",
+ "UsageBillingPeriod",
+ "UsageCurrent",
+ "UsageLimits",
+ "UsageResponse",
+]
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index 158d22f6..345963b0 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -1,12 +1,153 @@
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
+import base64
+import dataclasses
+import json
+import re
from abc import ABC, abstractmethod
+from dataclasses import dataclass
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import Any
-if TYPE_CHECKING:
- from .parse_result import ParseResult
+from mineru.render import render_content_list, render_content_list_v2, render_markdown
+from mineru.types import PageInfo
+
+_INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,([^\"]+)", re.DOTALL)
+
+
+@dataclass
+class ParseResult:
+ """The parsed result of a document.
+
+ Holds the typed middle representation and exposes markdown / content-list
+ / images as lazily-computed methods. Call ``save(writer)`` to persist.
+ """
+
+ 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
+
+ @staticmethod
+ def from_dict(d: dict[str, Any]) -> ParseResult:
+ # TODO
+ ...
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"pages": [dataclasses.asdict(p) for p in self.pages]}
+
+ @staticmethod
+ def from_json(s: str) -> ParseResult:
+ # TODO
+ ...
+
+ def to_json(self) -> str:
+ return json.dumps(self.to_dict(), ensure_ascii=False, indent=2)
+
+ def markdown(self, *, add_markers: bool = False) -> str:
+ return render_markdown(self.pages, add_markers=add_markers)
+
+ def content_list(self) -> list[dict[str, Any]]:
+ return render_content_list(self.pages)
+
+ def content_list_v2(self) -> list[dict[str, Any]]:
+ 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(
+ f"{prefix}_content_list.json",
+ json.dumps(self.content_list(), ensure_ascii=False, indent=4),
+ )
+ writer.write_string(
+ f"{prefix}_content_list_v2.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",
+ json.dumps(self._model_output, ensure_ascii=False, indent=4),
+ )
+
+ for img_path, img_bytes in self.images().items():
+ writer.write(img_path, img_bytes)
+
+ def images(self) -> dict[str, bytes]:
+ if self._images_cache is not None:
+ return self._images_cache
+ if self._pdf_doc is not None:
+ return self._extract_pdf_images()
+ return self._extract_office_images()
+
+ def _extract_pdf_images(self) -> dict[str, bytes]:
+ result: dict[str, bytes] = {}
+ for page_info in self.pages:
+ pil_img = self._pdf_doc.render_page(page_info.page_idx) # type: ignore[union-attr]
+ for block in page_info.preproc_blocks:
+ result.update(self._crop_block_spans(block, pil_img, 2))
+ for block in page_info.para_blocks:
+ result.update(self._crop_block_spans(block, pil_img, 2))
+ return result
+
+ @staticmethod
+ def _crop_block_spans(block: Any, pil_img: Any, scale: int) -> dict[str, bytes]:
+ from ..utils.pdf_image_tools import get_crop_img, image_to_bytes
+
+ result: dict[str, bytes] = {}
+ for line in block.lines:
+ for span in line.spans:
+ if not span.image_path or span.bbox is None:
+ continue
+ crop = get_crop_img(span.bbox, pil_img, scale=scale)
+ result[span.image_path] = image_to_bytes(crop, image_format="JPEG")
+ for child in block.blocks:
+ result.update(ParseResult._crop_block_spans(child, pil_img, scale))
+ return result
+
+ def _extract_office_images(self) -> dict[str, bytes]:
+ from ..utils.hash_utils import str_sha256
+
+ result: dict[str, bytes] = {}
+ for page_info in self.pages:
+ for block in page_info.para_blocks:
+ for span in self._iter_block_spans(block):
+ result.update(self._decode_span_base64_images(span, str_sha256))
+ return result
+
+ @staticmethod
+ def _iter_block_spans(block: Any):
+ for line in block.lines:
+ yield from line.spans
+ for child in block.blocks:
+ yield from ParseResult._iter_block_spans(child)
+
+ @staticmethod
+ def _decode_span_base64_images(span: Any, hash_fn) -> dict[str, bytes]:
+ result: dict[str, bytes] = {}
+ if span.image_base64:
+ m = _INLINE_IMAGE_DATA_URI_RE.match(span.image_base64)
+ if m:
+ try:
+ result[span.image_path or f"{hash_fn(span.image_base64)}.{m.group(1)}"] = base64.b64decode(m.group(2))
+ except Exception:
+ pass
+ if span.html:
+ for m in _INLINE_IMAGE_DATA_URI_RE.finditer(span.html):
+ try:
+ result[f"{hash_fn(m.group(0))}.{m.group(1)}"] = base64.b64decode(m.group(2))
+ except Exception:
+ pass
+ return result
class DocumentParser(ABC):
@@ -15,47 +156,21 @@ class DocumentParser(ABC):
Subclasses implement ``parse()`` for a specific document category (PDF, DOCX, PPTX, XLSX).
"""
- def __init__(
- self,
- *,
- backend: str = "hybrid-auto-engine",
- method: str = "auto",
- lang: str = "ch",
- formula_enable: bool = True,
- table_enable: bool = True,
- image_analysis: bool = True,
- server_url: str | None = None,
- start_page_id: int = 0,
- end_page_id: int | None = None,
- return_md: bool = True,
- return_middle_json: bool = True,
- return_model_output: bool = True,
- return_content_list: bool = True,
- return_images: bool = True,
- output_dir: str | Path = "./output",
- ):
- self.backend = backend
- self.method = method
- self.lang = lang
- self.formula_enable = formula_enable
- self.table_enable = table_enable
- self.image_analysis = image_analysis
- self.server_url = server_url
- self.start_page_id = start_page_id
- self.end_page_id = end_page_id
- self.return_md = return_md
- self.return_middle_json = return_middle_json
- self.return_model_output = return_model_output
- self.return_content_list = return_content_list
- self.return_images = return_images
- self.output_dir = Path(output_dir)
- self._closed = False
+ _closed: bool = False
@abstractmethod
- def parse(self, path: str | Path) -> ParseResult:
- """Parse a document and return structured results."""
+ def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
+ """Parse a document and return structured results.
+
+ Parameters
+ ----------
+ path:
+ Path to the document file.
+ page_range:
+ 1-based page range string (``"1~5,-3~-1"``). Empty means all pages.
+ """
- async def parse_async(self, path: str | Path) -> ParseResult:
+ async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
"""Asynchronously parse a document.
The default implementation delegates to ``parse()`` via ``asyncio.to_thread``.
@@ -63,17 +178,17 @@ class DocumentParser(ABC):
"""
import asyncio
- return await asyncio.to_thread(self.parse, path)
+ return await asyncio.to_thread(self.parse, path, page_range=page_range)
- def parse_batch(self, paths: list[str | Path]) -> list[ParseResult]:
+ def parse_batch(self, paths: list[str | Path], *, page_range: str = "") -> list[ParseResult]:
"""Parse multiple documents synchronously.
The default implementation calls ``parse()`` for each path in order.
Subclasses may override for batch-optimized execution.
"""
- return [self.parse(p) for p in paths]
+ return [self.parse(p, page_range=page_range) for p in paths]
- async def parse_batch_async(self, paths: list[str | Path]) -> list[ParseResult]:
+ async def parse_batch_async(self, paths: list[str | Path], *, page_range: str = "") -> list[ParseResult]:
"""Parse multiple documents asynchronously.
The default implementation calls ``parse_async()`` concurrently for all paths.
@@ -81,7 +196,7 @@ class DocumentParser(ABC):
"""
import asyncio
- return await asyncio.gather(*(self.parse_async(p) for p in paths))
+ return await asyncio.gather(*(self.parse_async(p, page_range=page_range) for p in paths))
def close(self) -> None:
"""Release resources held by this parser instance.
diff --git a/mineru/parser/engines.py b/mineru/parser/engines.py
deleted file mode 100644
index 472f87b2..00000000
--- a/mineru/parser/engines.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""Tier → backend mapping and engine resolution."""
-
-from __future__ import annotations
-
-from mineru.constants import Tier
-
-TIER_BACKEND_MAP: dict[str, str] = {
- Tier.FLASH: "flash",
- Tier.STANDARD: "pipeline",
- Tier.PRO: "hybrid-auto-engine",
-}
-
-
-def resolve_backend(tier: str, backend: str | None = None) -> str:
- """Resolve tier to a concrete backend. Explicit backend overrides tier."""
- if backend:
- return backend
- return TIER_BACKEND_MAP.get(tier, "pipeline")
diff --git a/mineru/parser/html_parser.py b/mineru/parser/html.py
similarity index 97%
rename from mineru/parser/html_parser.py
rename to mineru/parser/html.py
index 8d9fdc15..f88d55dd 100644
--- a/mineru/parser/html_parser.py
+++ b/mineru/parser/html.py
@@ -5,8 +5,7 @@ from pathlib import Path
from bs4 import BeautifulSoup, Tag
-from .base import DocumentParser
-from .parse_result import ParseResult
+from .base import DocumentParser, ParseResult
from mineru.types import Block, Line, PageInfo, Span
@@ -16,7 +15,7 @@ class HtmlParser(DocumentParser):
HTML elements are mapped to typed blocks inside a single page.
"""
- def parse(self, path: str | Path) -> ParseResult:
+ def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
path = Path(path)
if not path.exists():
raise FileNotFoundError(path)
diff --git a/mineru/parser/model.py b/mineru/parser/model.py
deleted file mode 100644
index 57588700..00000000
--- a/mineru/parser/model.py
+++ /dev/null
@@ -1,6 +0,0 @@
-class LayoutDetectionModel:
- pass
-
-
-class OCRModel:
- pass
diff --git a/mineru/parser/office_parser.py b/mineru/parser/office.py
similarity index 88%
rename from mineru/parser/office_parser.py
rename to mineru/parser/office.py
index 3e8af4b1..a4f0c585 100644
--- a/mineru/parser/office_parser.py
+++ b/mineru/parser/office.py
@@ -7,8 +7,7 @@ from typing import Any
from mineru.types import PageInfo
-from .base import DocumentParser
-from .parse_result import ParseResult
+from .base import DocumentParser, ParseResult
class OfficeBaseParser(DocumentParser, ABC):
@@ -18,10 +17,12 @@ class OfficeBaseParser(DocumentParser, ABC):
"""
_analyze_fn: Any
-
_suffix: str
- def parse(self, path: str | Path) -> ParseResult:
+ def __init__(self, *, return_model_output: bool = True):
+ self.return_model_output = return_model_output
+
+ def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
path = Path(path)
if not path.exists():
raise FileNotFoundError(path)
diff --git a/mineru/parser/parse_result.py b/mineru/parser/parse_result.py
deleted file mode 100644
index 5ebec6c6..00000000
--- a/mineru/parser/parse_result.py
+++ /dev/null
@@ -1,181 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import base64
-import dataclasses
-import json
-import re
-from dataclasses import dataclass
-from typing import Any
-
-from mineru.render import render_content_list, render_content_list_v2, render_markdown
-from mineru.types import PageInfo
-
-from ..utils.pdf_document import PDFDocument
-
-_INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,([^\"]+)", re.DOTALL)
-
-
-def _render_flash_markdown(pages: list) -> str | list:
- """Minimal markdown renderer for flash: just concatenate text from spans."""
- parts: list[str] = []
- for p in pages:
- for block in getattr(p, "para_blocks", []):
- for line in getattr(block, "lines", []):
- for span in getattr(line, "spans", []):
- if getattr(span, "content", ""):
- parts.append(span.content)
- return "\n\n".join(parts)
-
-
-@dataclass
-class ParseResult:
- """The parsed result of a document.
-
- Holds the typed middle representation and exposes markdown / content-list
- / images as lazily-computed methods. Call ``save(writer)`` to persist.
- """
-
- pages: list[PageInfo]
- _backend: str
- _version_name: str
- _pdf_doc: PDFDocument | None = None
- _file_name: str = ""
- _model_output: Any = None
- _images_cache: dict[str, bytes] | None = None
-
- @staticmethod
- def from_dict(d: dict[str, Any]) -> "ParseResult":
- # TODO
- ...
-
- def to_dict(self) -> dict[str, Any]:
- return {"pages": [dataclasses.asdict(p) for p in self.pages]}
-
- @staticmethod
- def from_json(s: str) -> "ParseResult":
- # TODO
- ...
-
- def to_json(self) -> str:
- return json.dumps(self.to_dict(), ensure_ascii=False, indent=2)
-
- def markdown(self) -> str:
- if self._backend == "flash":
- return _render_flash_markdown(self.pages)
- return render_markdown(self.pages)
-
- def markdown_with_markers(self, *, page_count: int | None = None) -> str:
- """Generate markdown with page boundary markers (<!-- page N of M -->)."""
- total = page_count or len(self.pages)
- parts: list[str] = []
- for p in self.pages:
- page_num = p.page_idx + 1 # 1-based
- parts.append(f"<!-- page {page_num} of {total} -->")
- try:
- page_md = render_markdown([p])
- if page_md.strip():
- parts.append(page_md)
- except Exception:
- pass
- return "\n\n".join(parts)
-
- def content_list(self) -> list[dict[str, Any]]:
- return render_content_list(self.pages)
-
- def content_list_v2(self) -> list[dict[str, Any]]:
- 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(
- f"{prefix}_content_list.json",
- json.dumps(self.content_list(), ensure_ascii=False, indent=4),
- )
- writer.write_string(
- f"{prefix}_content_list_v2.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",
- json.dumps(self._model_output, ensure_ascii=False, indent=4),
- )
-
- for img_path, img_bytes in self.images().items():
- writer.write(img_path, img_bytes)
-
- def images(self) -> dict[str, bytes]:
- if self._images_cache is not None:
- return self._images_cache
- if self._pdf_doc is not None:
- return self._extract_pdf_images()
- return self._extract_office_images()
-
- def _extract_pdf_images(self) -> dict[str, bytes]:
- result: dict[str, bytes] = {}
- for page_info in self.pages:
- pil_img = self._pdf_doc.render_page(page_info.page_idx)
- for block in page_info.preproc_blocks:
- result.update(self._crop_block_spans(block, pil_img, 2))
- for block in page_info.para_blocks:
- result.update(self._crop_block_spans(block, pil_img, 2))
- return result
-
- @staticmethod
- def _crop_block_spans(block: Any, pil_img: Any, scale: int) -> dict[str, bytes]:
- from ..utils.pdf_image_tools import get_crop_img, image_to_bytes
-
- result: dict[str, bytes] = {}
- for line in block.lines:
- for span in line.spans:
- if not span.image_path or span.bbox is None:
- continue
- crop = get_crop_img(span.bbox, pil_img, scale=scale)
- result[span.image_path] = image_to_bytes(crop, image_format="JPEG")
- for child in block.blocks:
- result.update(ParseResult._crop_block_spans(child, pil_img, scale))
- return result
-
- def _extract_office_images(self) -> dict[str, bytes]:
- from ..utils.hash_utils import str_sha256
-
- result: dict[str, bytes] = {}
- for page_info in self.pages:
- for block in page_info.para_blocks:
- for span in self._iter_block_spans(block):
- result.update(self._decode_span_base64_images(span, str_sha256))
- return result
-
- @staticmethod
- def _iter_block_spans(block: Any):
- for line in block.lines:
- yield from line.spans
- for child in block.blocks:
- yield from ParseResult._iter_block_spans(child)
-
- @staticmethod
- def _decode_span_base64_images(span: Any, hash_fn) -> dict[str, bytes]:
- result: dict[str, bytes] = {}
- # span-level image_base64 (Office)
- if span.image_base64:
- m = _INLINE_IMAGE_DATA_URI_RE.match(span.image_base64)
- if m:
- try:
- result[span.image_path or f"{hash_fn(span.image_base64)}.{m.group(1)}"] = base64.b64decode(m.group(2))
- except Exception:
- pass
- # inline images inside table html
- if span.html:
- for m in _INLINE_IMAGE_DATA_URI_RE.finditer(span.html):
- try:
- result[f"{hash_fn(m.group(0))}.{m.group(1)}"] = base64.b64decode(m.group(2))
- except Exception:
- pass
- return result
diff --git a/mineru/parser/pdf_parser.py b/mineru/parser/pdf.py
similarity index 67%
rename from mineru/parser/pdf_parser.py
rename to mineru/parser/pdf.py
index 33b5b849..40cd6eac 100644
--- a/mineru/parser/pdf_parser.py
+++ b/mineru/parser/pdf.py
@@ -9,8 +9,7 @@ from typing import Any
from mineru.types import PageInfo
-from .base import DocumentParser
-from .parse_result import ParseResult
+from .base import DocumentParser, ParseResult
_IMAGE_SUFFIXES = frozenset({"png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"})
@@ -41,22 +40,43 @@ class PdfBaseParser(DocumentParser):
_parse_method: str = ""
_backend: str = ""
- def parse(self, path: str | Path) -> ParseResult:
+ def __init__(
+ self,
+ *,
+ backend: str = "hybrid-auto-engine",
+ method: str = "auto",
+ lang: str = "ch",
+ formula_enable: bool = True,
+ table_enable: bool = True,
+ image_analysis: bool = True,
+ server_url: str | None = None,
+ ):
+ self.backend = backend
+ self.method = method
+ self.lang = lang
+ self.formula_enable = formula_enable
+ self.table_enable = table_enable
+ self.image_analysis = image_analysis
+ self.server_url = server_url
+
+ def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
path = Path(path)
if not path.exists():
raise FileNotFoundError(path)
- file_name, pdf_bytes = self._prepare_input(path)
+ file_name, pdf_bytes = self._prepare_input(path, page_range)
middle_json = self._run_analysis(pdf_bytes, image_writer=None)
+ self._fix_page_indices(middle_json)
return self._build_result(middle_json, pdf_bytes, file_name)
- async def parse_async(self, path: str | Path) -> ParseResult:
+ async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
path = Path(path)
if not path.exists():
raise FileNotFoundError(path)
- file_name, pdf_bytes = await asyncio.to_thread(self._prepare_input, path)
+ file_name, pdf_bytes = await asyncio.to_thread(self._prepare_input, path, page_range)
middle_json = await self._arun_analysis(pdf_bytes, image_writer=None)
+ self._fix_page_indices(middle_json)
return self._build_result(middle_json, pdf_bytes, file_name)
@abstractmethod
@@ -66,7 +86,7 @@ class PdfBaseParser(DocumentParser):
async def _arun_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
return await asyncio.to_thread(self._run_analysis, pdf_bytes, image_writer)
- def _prepare_input(self, path: Path) -> tuple[str, bytes]:
+ def _prepare_input(self, path: Path, page_range: str = "") -> tuple[str, bytes]:
from ..utils.guess_suffix_or_lang import guess_suffix_by_path
from ..utils.pdf_document import PDFDocument
@@ -77,22 +97,36 @@ class PdfBaseParser(DocumentParser):
if suffix in _IMAGE_SUFFIXES:
pdf_bytes = PDFDocument.from_image(pdf_bytes).bytes
- pdf_bytes = self._maybe_adjust_pdf_bytes(pdf_bytes, suffix)
+ pdf_bytes = self._maybe_adjust_pdf_bytes(pdf_bytes, suffix, page_range)
return file_name, pdf_bytes
- def _maybe_adjust_pdf_bytes(self, pdf_bytes: bytes, suffix: str) -> bytes:
+ def _maybe_adjust_pdf_bytes(self, pdf_bytes: bytes, suffix: str, page_range: str = "") -> bytes:
if suffix != "pdf":
return pdf_bytes
from ..utils.pdf_document import PDFDocument
+ from ..utils.pdf_page_id import parse_page_range
doc = PDFDocument(pdf_bytes)
- end = self.end_page_id if self.end_page_id is not None else doc.page_count - 1
- if self.start_page_id > 0 or self.end_page_id is not None:
- extracted = doc.extract_page_range(self.start_page_id, end)
- if extracted.bytes:
- return extracted.bytes
- return pdf_bytes
+ self._page_indices = parse_page_range(page_range, doc.page_count)
+
+ if self._page_indices == list(range(doc.page_count)):
+ return pdf_bytes
+
+ from ..utils.pdfium_guard import rewrite_pdf_bytes_with_pdfium
+
+ extracted = rewrite_pdf_bytes_with_pdfium(pdf_bytes, page_indices=self._page_indices)
+ return extracted or pdf_bytes
+
+ def _fix_page_indices(self, pages: list[PageInfo]) -> None:
+ """Rewrite ``page_idx`` so it reflects the original document position
+ when pages were cropped from a subset."""
+ mapping = getattr(self, "_page_indices", None)
+ if not mapping:
+ return
+ for i, p in enumerate(pages):
+ if i < len(mapping):
+ p.page_idx = mapping[i]
def _build_result(
self,
@@ -156,15 +190,15 @@ class PdfPipelineParser(PdfBaseParser):
_parse_method: str = ""
_backend = "pipeline"
- def parse(self, path: str | Path) -> ParseResult:
+ def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
self._parse_method = self.method
- return super().parse(path)
+ return super().parse(path, page_range=page_range)
- async def parse_async(self, path: str | Path) -> ParseResult:
+ async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
self._parse_method = self.method
- return await super().parse_async(path)
+ return await super().parse_async(path, page_range=page_range)
- def parse_batch(self, paths: list[str | Path]) -> list[ParseResult]:
+ def parse_batch(self, paths: list[str | Path], *, page_range: str = "") -> list[ParseResult]:
self._parse_method = self.method
from ..backend.pipeline.pipeline_analyze import doc_analyze_streaming
@@ -172,7 +206,7 @@ class PdfPipelineParser(PdfBaseParser):
file_names: list[str] = []
pdf_bytes_list: list[bytes] = []
for p in paths:
- fn, pb = self._prepare_input(Path(p))
+ fn, pb = self._prepare_input(Path(p), page_range)
file_names.append(fn)
pdf_bytes_list.append(pb)
@@ -199,10 +233,10 @@ class PdfPipelineParser(PdfBaseParser):
return parse_results
- async def parse_batch_async(self, paths: list[str | Path]) -> list[ParseResult]:
+ async def parse_batch_async(self, paths: list[str | Path], *, page_range: str = "") -> list[ParseResult]:
import asyncio
- return await asyncio.to_thread(self.parse_batch, paths)
+ return await asyncio.to_thread(self.parse_batch, paths, page_range=page_range)
def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
from ..backend.pipeline.pipeline_analyze import doc_analyze_streaming
@@ -231,13 +265,13 @@ class PdfHybridParser(PdfBaseParser):
_parse_method: str = ""
_backend = "hybrid"
- def parse(self, path: str | Path) -> ParseResult:
+ def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
self._parse_method = f"hybrid_{self.method}"
- return super().parse(path)
+ return super().parse(path, page_range=page_range)
- async def parse_async(self, path: str | Path) -> ParseResult:
+ async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
self._parse_method = f"hybrid_{self.method}"
- return await super().parse_async(path)
+ return await super().parse_async(path, page_range=page_range)
def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import doc_analyze as hybrid_doc_analyze
@@ -280,3 +314,46 @@ class PdfHybridParser(PdfBaseParser):
)
return middle_json
+
+
+class PdfFlashParser(PdfBaseParser):
+ """PDF / image parser using the flash (CPU-only pypdfium2) backend."""
+
+ _backend = "flash"
+
+ def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
+ from mineru.types import Block, Line, PageInfo, Span
+
+ from ..backend.flash.pdf_extractor import extract_text
+
+ filepath = self._pdf_bytes_to_tempfile(pdf_bytes)
+ text = extract_text(filepath)
+ pages_text = text.split("\n\n")
+
+ pages: list[PageInfo] = []
+ page_idx = self._page_indices[0] if self._page_indices else 0
+ block_idx = 0
+ for pt in pages_text:
+ if not pt.strip():
+ continue
+ span = Span(type="text", bbox=(0.0, 0.0, 0.0, 0.0), content=pt.strip())
+ line = Line(bbox=(0.0, 0.0, 0.0, 0.0), spans=[span])
+ block = Block(index=block_idx, type="text", bbox=(0.0, 0.0, 0.0, 0.0), lines=[line])
+ block_idx += 1
+ page = PageInfo(
+ page_idx=page_idx,
+ para_blocks=[block],
+ )
+ pages.append(page)
+ page_idx += 1
+
+ return pages
+
+ @staticmethod
+ def _pdf_bytes_to_tempfile(pdf_bytes: bytes) -> str:
+ import tempfile
+
+ tmp = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
+ tmp.write(pdf_bytes)
+ tmp.close()
+ return tmp.name
diff --git a/mineru/render/office/__init__.py b/mineru/render/office/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/mineru/render/union_make.py b/mineru/render/union_make.py
index 43eaf510..8a29fd23 100644
--- a/mineru/render/union_make.py
+++ b/mineru/render/union_make.py
@@ -87,9 +87,14 @@ def render_markdown(
formula_enable: bool = True, # TODO
table_enable: bool = True, # TODO
no_rich_content: bool = False,
+ add_markers: bool = False,
) -> str:
- """Render pages to a single Markdown string."""
+ """Render pages to a single Markdown string.
+
+ If *add_markers* is True, each page is prefixed with ``<!-- page N of M -->``.
+ """
backend = _backend_from_pages(pdf_info)
+ total = len(pdf_info)
output_md: list[str] = []
if backend == "office":
for page_info in pdf_info:
@@ -98,6 +103,9 @@ def render_markdown(
img_bucket_path=img_bucket_path,
no_rich_content=no_rich_content,
)
+ if add_markers:
+ page_num = page_info.page_idx + 1
+ output_md.append(f"<!-- page {page_num} of {total} -->")
output_md.extend(page_md)
else: # PDF
for page_info in pdf_info:
@@ -108,6 +116,9 @@ def render_markdown(
formula_as_image=not formula_enable,
no_rich_content=no_rich_content,
)
+ if add_markers:
+ page_num = page_info.page_idx + 1
+ output_md.append(f"<!-- page {page_num} of {total} -->")
output_md.extend(page_md)
return "\n\n".join(output_md)
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index ab6fde19..494bed1c 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -24,7 +24,6 @@ from .check_sys_env import is_windows_environment
from .enum_class import ImageType
from .hash_utils import str_sha256
from .os_env_config import get_load_images_threads, get_load_images_timeout
-from .pdf_page_id import get_end_page_id
from .pdf_reader import image_to_b64str, image_to_bytes, page_to_image
from .pdfium_guard import (
close_pdfium_child,
@@ -420,7 +419,9 @@ def load_images_from_pdf_core(
with pdfium_guard():
pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)
pdf_page_num = len(pdf_doc)
- end_page_id = get_end_page_id(end_page_id, pdf_page_num)
+ end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else pdf_page_num - 1
+ if end_page_id > pdf_page_num - 1:
+ end_page_id = pdf_page_num - 1
for index in range(start_page_id, end_page_id + 1):
# logger.debug(f"Converting page {index}/{pdf_page_num} to image")
@@ -448,7 +449,9 @@ def load_images_from_pdf_doc(
threads: int | None = None,
) -> list[dict[str, Any]]:
pdf_page_num = get_pdfium_document_page_count(pdf_doc)
- normalized_end_page_id = get_end_page_id(end_page_id, pdf_page_num)
+ normalized_end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else pdf_page_num - 1
+ if normalized_end_page_id > pdf_page_num - 1:
+ normalized_end_page_id = pdf_page_num - 1
if pdf_bytes is not None:
return _load_images_from_pdf_bytes_range(
diff --git a/mineru/utils/pdf_page_id.py b/mineru/utils/pdf_page_id.py
index cca3e142..90a915ab 100644
--- a/mineru/utils/pdf_page_id.py
+++ b/mineru/utils/pdf_page_id.py
@@ -1,10 +1,47 @@
# Copyright (c) Opendatalab. All rights reserved.
-from loguru import logger
+from __future__ import annotations
-def get_end_page_id(end_page_id: int | None, pdf_page_num: int) -> int:
- end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else pdf_page_num - 1
- if end_page_id > pdf_page_num - 1:
- logger.debug("end_page_id is out of range, use images length")
- end_page_id = pdf_page_num - 1
- return end_page_id
+def parse_page_range(raw: str, page_count: int) -> list[int]:
+ """Parse a 1-based page-range string into a 0-based flattened list of page indices.
+
+ Format (aligned with NEXT-API ``page_range``):
+ ``"1~5"`` → pages 1 through 5
+ ``"1,3,5~7"`` → pages 1, 3, 5, 6, 7
+ ``"-5~-1"`` → last 5 pages (page_count=100 → [95, 96, 97, 98, 99])
+ ``"5"`` → single page 5
+ ``""`` → all pages
+
+ Separator: ``~`` recommended, ``-`` also accepted.
+ Negative values are resolved against *page_count* (e.g. ``-1`` = last page).
+ Returns an empty list when every resolved segment is outside ``[0, page_count)``.
+ """
+ if not raw:
+ return list(range(page_count))
+
+ result: list[int] = []
+ for segment in raw.split(","):
+ segment = segment.strip()
+ if not segment:
+ continue
+ sep = "~" if "~" in segment else "-"
+ parts = segment.split(sep, 1)
+
+ def _resolve(token: str) -> int:
+ n = int(token.strip())
+ return n + page_count if n < 0 else n
+
+ start_1b = _resolve(parts[0])
+ end_1b = _resolve(parts[1]) if len(parts) > 1 and parts[1].strip() else start_1b
+
+ start_0b = start_1b - 1 # 1-based → 0-based
+ end_0b = end_1b - 1
+
+ lo = max(0, min(start_0b, end_0b))
+ hi = min(page_count - 1, max(start_0b, end_0b))
+ if lo <= hi:
+ result.extend(range(lo, hi + 1))
+
+ if not result:
+ return list(range(page_count))
+ return sorted(set(result))
diff --git a/mineru/utils/pdfium_guard.py b/mineru/utils/pdfium_guard.py
index 07d7f607..83b7abc1 100644
--- a/mineru/utils/pdfium_guard.py
+++ b/mineru/utils/pdfium_guard.py
@@ -6,7 +6,6 @@ from typing import Any, Callable, Iterator, Sequence, TypeVar
from loguru import logger
-from .pdf_page_id import get_end_page_id
_pdfium_lock = threading.RLock()
@@ -81,7 +80,9 @@ def get_loadable_pdfium_page_indices(
return [], []
normalized_start_page_id = max(0, start_page_id)
- normalized_end_page_id = get_end_page_id(end_page_id, total_page_count)
+ normalized_end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else total_page_count - 1
+ if normalized_end_page_id > total_page_count - 1:
+ normalized_end_page_id = total_page_count - 1
if normalized_start_page_id > normalized_end_page_id:
return [], []
@@ -128,7 +129,9 @@ def rewrite_pdf_bytes_with_pdfium(
if not normalized_page_indices:
return b""
else:
- normalized_end_page_id = get_end_page_id(end_page_id, total_page_count)
+ normalized_end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else total_page_count - 1
+ if normalized_end_page_id > total_page_count - 1:
+ normalized_end_page_id = total_page_count - 1
normalized_page_indices = list(range(start_page_id, normalized_end_page_id + 1))
output_doc = pdfium.PdfDocument.new()
diff --git a/mineru/utils/title_level_postprocess.py b/mineru/utils/title_level_postprocess.py
index 2a8eab00..5fcdffd9 100644
--- a/mineru/utils/title_level_postprocess.py
+++ b/mineru/utils/title_level_postprocess.py
@@ -44,7 +44,7 @@ def finalize_client_side_middle_json(middle_json: dict[str, Any]) -> dict[str, A
if not isinstance(middle_json, dict):
raise ValueError("middle_json must be a dict.")
- from ..parser.parse_result import ParseResult
+ from ..parser.base import ParseResult
result = ParseResult.from_dict(middle_json)
backend = result._backend
diff --git a/pyrightconfig.json b/pyrightconfig.json
new file mode 100644
index 00000000..e5788e82
--- /dev/null
+++ b/pyrightconfig.json
@@ -0,0 +1,5 @@
+{
+ "typeCheckingMode": "standard",
+ "include": ["mineru"],
+ "exclude": ["**/node_modules", "**/__pycache__", ".venv"],
+}