Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
Update v1 API source capability handling
jinzhenj23fa60dc7bd5
diff --git a/docs/next/api/README.md b/docs/next/api/README.mdindex a9a8630f..e2e1cd56 100644--- a/docs/next/api/README.md+++ b/docs/next/api/README.md@@ -32,7 +32,7 @@ ID 使用 OpenAI 风格的前缀加随机串。官方 API 使用 24 字符 base6| 部署形态 | Base URL ||----------|----------|| 官方远程 API | `https://mineru.net/api` |-| Local Parse Server | `http://localhost:8000/api` |+| Local Parse Server | `http://localhost:8000` |所有 endpoint 都带 `/v1` 版本前缀,例如 `GET https://mineru.net/api/v1/health`。@@ -93,4 +93,4 @@ Local Parse Server 的目标是复用客户端协议,而不是完整模拟公- 不支持 Webhook。- 上传 URL 可以指向本地 server 的临时上传 endpoint,而不是 OSS。- 文件产物下载可以直接返回 `200 + body`,不必返回 CDN 重定向。-- 支持 `local` source,由 server 直接读取 allowlist 内的本地路径。+- 支持 `local` source,但必须通过 `--allow-local-source` 显式开启;客户端应以 `health.features.sources` 判断当前部署是否允许。diff --git a/docs/next/api/changes.md b/docs/next/api/changes.mdindex d695a9db..c7913acd 100644--- a/docs/next/api/changes.md+++ b/docs/next/api/changes.md@@ -2,6 +2,22 @@范围: NEXT v1 API 标准的破坏性或需要迁移的行为变化。+## 2026-07-08: 明确 Local Parse Server base URL++Local Parse Server 的 base URL 是 `http://localhost:8000`,endpoint 直接挂在 `/v1` 下。`/api` 只属于 `https://mineru.net/api` 这类官方远程 API base URL。++## 2026-07-08: 增加 `features.output_formats`++`GET /v1/health` 的 `features` 增加 `output_formats`,用于声明当前部署实际支持的 parse job 输出格式。客户端应以该字段作为能力发现事实,而不是假设所有部署都支持同一组输出格式。++## 2026-07-08: 增加 `features.sources`++`GET /v1/health` 的 `features` 增加 `sources`,用于声明当前部署允许的 parse job source 类型。客户端应以该字段决定是否可以使用 `local` source;没有声明 `local` 时,应通过 Uploads API 取得 `file_id` 后再创建解析任务。++## 2026-07-08: 收紧 Local Parse Server source 策略++Local Parse Server 对 `local`、`inline` 和 `url` source 增加启动时可配置的安全策略: `local` source 默认关闭,只有显式开启 `--allow-local-source` 后才允许读取 server 进程权限范围内的本地路径;`inline` source 受 `--max-inline-bytes` 限制;`url` source 默认只允许 HTTPS,只有显式开启 `--allow-http-source` 后才允许 HTTP。+## 2026-07-08: 删除 parse job SSE eventsNEXT v1 API 不再定义 `GET /v1/parse/jobs/{job_id}/events`,parse job 响应中也不再返回 `links.events`。客户端统一通过 `GET /v1/parse/jobs/{job_id}` 查询任务状态和结果。diff --git a/docs/next/api/examples.md b/docs/next/api/examples.mdindex d45f672c..ac597376 100644--- a/docs/next/api/examples.md+++ b/docs/next/api/examples.md@@ -111,14 +111,16 @@ curl -L "https://mineru.net/api/v1/files/$MD_FILE_ID/content" \先发现本地能力:```bash-curl http://localhost:8000/api/v1/health-curl http://localhost:8000/api/v1/tiers+curl http://localhost:8000/v1/health+curl http://localhost:8000/v1/tiers```本地 server 可以直接使用 `local` source:```bash-curl -X POST http://localhost:8000/api/v1/parse/jobs \+mineru-kit api-server --allow-local-source++curl -X POST http://localhost:8000/v1/parse/jobs \-H "Content-Type: application/json" \-d '{"files": [{@@ -138,7 +140,7 @@ curl -X POST http://localhost:8000/api/v1/parse/jobs \```bashSIZE=$(stat -f%z report.pdf)-RESP=$(curl -s -X POST http://localhost:8000/api/v1/uploads \+RESP=$(curl -s -X POST http://localhost:8000/v1/uploads \-H "Content-Type: application/json" \-d "{\"filename\":\"report.pdf\",\"bytes\":$SIZE,\"mime_type\":\"application/pdf\",\"purpose\":\"parse\"}")@@ -150,7 +152,7 @@ curl -X "$METHOD" "$URL" \-H "Content-Type: application/pdf" \--data-binary @report.pdf-RESP=$(curl -s -X POST "http://localhost:8000/api/v1/uploads/$UPLOAD_ID/complete")+RESP=$(curl -s -X POST "http://localhost:8000/v1/uploads/$UPLOAD_ID/complete")FILE_ID=$(echo "$RESP" | jq -r '.file.id')```diff --git a/docs/next/api/health-models.md b/docs/next/api/health-models.mdindex 6a9ec8a5..36e59e52 100644--- a/docs/next/api/health-models.md+++ b/docs/next/api/health-models.md@@ -22,7 +22,9 @@ GET /v1/health HTTP/1.1"status": "ok","version": "1.0.0","features": {- "webhook": true+ "webhook": true,+ "output_formats": ["markdown", "middle_json", "content_list", "structured_content", "html", "latex", "docx", "zip"],+ "sources": ["file_id", "url", "inline"]}}```@@ -35,6 +37,8 @@ GET /v1/health HTTP/1.1| `version` | string | 是 | API 服务版本。 || `features` | object | 是 | 当前部署支持的外围能力。 || `features.webhook` | bool | 是 | 是否支持 Webhook 回调。 |+| `features.output_formats` | array | 是 | 当前部署支持的 parse job `output_formats` 值。 |+| `features.sources` | array | 是 | 当前部署允许的 parse job source 类型。 |错误:@@ -173,11 +177,15 @@ Local Parse Server 的 `health` 通常返回:"status": "ok","version": "1.0.0","features": {- "webhook": false+ "webhook": false,+ "output_formats": ["markdown", "middle_json", "content_list", "structured_content", "zip"],+ "sources": ["file_id", "url", "inline"]}}```+如果 Local Parse Server 启动时开启 `--allow-local-source`,`features.sources` 额外包含 `local`。+本地实现可以额外返回运维字段,例如:| 字段 | 类型 | 说明 |diff --git a/docs/next/api/parse-jobs.md b/docs/next/api/parse-jobs.mdindex b09bc836..eea3e87e 100644--- a/docs/next/api/parse-jobs.md+++ b/docs/next/api/parse-jobs.md@@ -107,8 +107,16 @@ Source 字段约束:|--------|----------|------|| `file_id` | `file_id` | File 必须存在、属于当前租户,且 `purpose` 适合解析。 || `url` | `url` | 官方 API 只允许公网 URL;拒绝私有网段、链路本地和 cloud metadata 地址。 |-| `inline` | `name`、`data` | base64 字符串大小不超过 1MB。 |-| `local` | `path` | 仅本地 server 支持;路径必须在 allowlist root 内。 |+| `inline` | `name`、`data` | base64 解码后字节数默认不超过 1MB。 |+| `local` | `path` | 仅本地 server 支持;只有 `features.sources` 包含 `local` 时可用。 |++客户端应以 `GET /v1/health` 返回的 `features.sources` 作为当前部署实际允许的 source 类型。++Local Parse Server 的 source 策略由启动参数决定:++- `--allow-local-source` 控制是否允许 `local` source;未开启时拒绝 `local` source,开启后允许读取 server 进程权限范围内的任意本地路径。+- `--max-inline-bytes` 控制 `inline` source 解码后的最大字节数,默认 1MB。+- `--allow-http-source` 控制 `url` source 是否允许 `http://`;默认只允许 `https://`。### 文件级解析字段@@ -135,6 +143,8 @@ OCR 策略和图片分析能力由 `tier` 与服务端实际引擎自动决定`images` 不是可请求的 `output_formats` 值。需要图片 sidecar 的客户端应请求 `zip`,并从 zip 包内读取 `middle_json` 引用的图片路径。+客户端应以 `GET /v1/health` 返回的 `features.output_formats` 作为当前部署实际支持格式。Local Parse Server 可以只暴露基础格式。+`json`、`content_list_v2` 不是 NEXT 版正式格式名,不进入公开格式集合。命名决策见 [ADR-0001](../decisions/0001-json-output-formats.md)。### 创建响应@@ -339,7 +349,8 @@ OCR 策略和图片分析能力由 `tier` 与服务端实际引擎自动决定Local Parse Server 的任务 API 与官方 API 保持同一结构,但有以下实现差异:- 不支持 Webhook 时,`health.features.webhook` 必须为 `false`;收到 `callback` 时应返回 `400 invalid_request` 或明确忽略。-- 支持 `local` source,但必须限制在配置允许的根目录内。+- `health.features.output_formats` 必须反映本地 server 实际支持的输出格式;当前本地实现支持 `markdown`、`middle_json`、`content_list`、`structured_content` 和 `zip`。+- `health.features.sources` 必须反映本地 server 实际允许的 source 类型;只有启动时开启 `--allow-local-source` 才包含 `local`。- `local` source 可以不生成输入 `file_id`;响应中应保留 `name` 和文件级状态。- 省略 `tier` 或传 `null` 时,只能选择本地可发现的 `medium` 或 `high`,不能回退到 `flash`。- 如果只有 `flash` 可用,应返回 `quality_tier_unavailable`,而不是返回低质量解析结果。diff --git a/docs/next/api/responses.md b/docs/next/api/responses.mdindex ff8f078d..a3b45919 100644--- a/docs/next/api/responses.md+++ b/docs/next/api/responses.md@@ -93,7 +93,6 @@ Idempotency-Key: 7f5b7f7c-5c5a-4b2f-bb89-0c901c9a2d6a| `permission_error` | 权限不足、配额耗尽或功能需要更高 access level。 || `rate_limit_error` | 请求触发限流。 || `engine_error` | 解析引擎不可用、崩溃或解析失败。 |-| `timeout_error` | 请求等待窗口到期,但底层任务不一定失败。 || `api_error` | 服务端内部错误。 |## 常用错误码@@ -112,7 +111,6 @@ Idempotency-Key: 7f5b7f7c-5c5a-4b2f-bb89-0c901c9a2d6a| 403 | `permission_error` | `feature_requires_api_key` || 403 | `permission_error` | `list_requires_api_key` || 404 | `invalid_request_error` | `job_not_found`、`file_not_found`、`upload_not_found`、`model_not_found` |-| 408 | `timeout_error` | `parse_wait_timeout` || 409 | `invalid_request_error` | `job_already_terminal`、`upload_not_ready`、`upload_already_terminal` || 413 | `invalid_request_error` | `file_too_large`、`content_too_large` || 429 | `rate_limit_error` | `rate_limit_exceeded` |diff --git a/docs/next/sdk/api-parser.md b/docs/next/sdk/api-parser.mdindex 006c8806..818252a5 100644--- a/docs/next/sdk/api-parser.md+++ b/docs/next/sdk/api-parser.md@@ -57,7 +57,7 @@ class MinerUApiParser(DocumentParser):| 参数 | 说明 ||------|------|-| `api_url` | v1 API base URL,如 `https://mineru.net/api` 或 `http://127.0.0.1:16580/api`。省略时读取 `MINERU_API_URL`,再退回默认官方 API。 |+| `api_url` | v1 API base URL,如 `https://mineru.net/api` 或 `http://127.0.0.1:16580`。省略时读取 `MINERU_API_URL`,再退回默认官方 API。 || `api_key` | Bearer token。省略时读取 `MINERU_API_KEY`;Local Parse Server 未启用鉴权时可为空。 || `tier` | `flash`、`medium`、`high`、`extra_high` 或 `None`。`None` 表示 SDK 在 HTTP 请求中省略 `tier`,让 v1 API 使用默认选择策略。 || `include_images` | 是否从 zip 产物读取图片 sidecar,并挂载到 `ParseResult` 图片缓存。 |@@ -69,8 +69,8 @@ class MinerUApiParser(DocumentParser):1. 检查文件存在。2. 判断 `api_url` 是否是本地地址。-3. 本地地址优先使用 `local` source。-4. 非本地地址使用 Uploads API: create upload -> PUT upload_url -> complete upload。+3. 本地地址先读取 `GET /v1/health`;只有 `features.sources` 包含 `local` 时才使用 `local` source。+4. 非本地地址,或本地 server 未允许 `local` source 时,使用 Uploads API: create upload -> PUT upload_url -> complete upload,再以 `file_id` source 创建解析任务。5. 调用 `POST /v1/parse/jobs`;默认请求 `output_formats:["middle_json"]`,需要模型输出或图片缓存时请求 `["zip"]`。6. 如果 job 未完成,则轮询 `GET /v1/parse/jobs/{job_id}`。7. 普通模式下载 `middle_json` output file;zip 模式下载 `zip` output file。@@ -79,6 +79,8 @@ class MinerUApiParser(DocumentParser):本地 source:+Local Parse Server 必须通过 `--allow-local-source` 开启,并在 `features.sources` 返回 `local`,SDK 才会使用该形式。+```json{"source": {diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.pyindex 2c959ed4..1ccfee37 100644--- a/mineru/doclib/background/parse_server_health.py+++ b/mineru/doclib/background/parse_server_health.py@@ -85,7 +85,15 @@ def api_server_args_for_tier(tier: Tier, *, host: str, port: int) -> list[str]:backend. Backend remains an api-server implementation detail and must notleak into runtime doclib parse requests."""- return ["--tier", tier, "--host", host, "--port", str(port)]+ return [+ "--tier",+ tier,+ "--host",+ host,+ "--port",+ str(port),+ "--allow-local-source",+ ]def managed_parse_server_url(host: str, port: int) -> str:@@ -228,7 +236,7 @@ class ParseServerHealthCheck:def __init__(self,- config_svc,+ config_svc: "ConfigService",*,interval_sec: int,probe_timeout_sec: int,diff --git a/mineru/kit/commands/api_server.py b/mineru/kit/commands/api_server.pyindex fd04ee87..9610d52c 100644--- a/mineru/kit/commands/api_server.py+++ b/mineru/kit/commands/api_server.py@@ -39,6 +39,9 @@ def api_server_cmd(| None = None,concurrency: int = 1,url_timeout: int = 60,+ allow_local_source: bool = False,+ max_inline_bytes: int = 1024 * 1024,+ allow_http_source: bool = False,language: str = "ch",ocr_mode: Literal["auto", "txt", "ocr"] = "auto",disable_image_analysis: bool = False,@@ -61,11 +64,15 @@ def api_server_cmd(str(concurrency),"--url-timeout",str(url_timeout),+ "--max-inline-bytes",+ str(max_inline_bytes),"--language",normalized_language,"--ocr-mode",ocr_mode,*tier_args,+ *(["--allow-local-source"] if allow_local_source else []),+ *(["--allow-http-source"] if allow_http_source else []),*(["--upload-dir", upload_dir] if upload_dir else []),*(["--disable-image-analysis"] if disable_image_analysis else []),*(["--api-key", api_key] if api_key else []),diff --git a/mineru/kit/main.py b/mineru/kit/main.pyindex e64763de..51b3b8c3 100644--- a/mineru/kit/main.py+++ b/mineru/kit/main.py@@ -87,6 +87,9 @@ def api_server_command(),concurrency: int = typer.Option(1, "--concurrency", help="Maximum concurrent parse jobs"),url_timeout: int = typer.Option(60, "--url-timeout", help="Timeout for URL source downloads"),+ allow_local_source: bool = typer.Option(False, "--allow-local-source", help="Allow local source paths"),+ max_inline_bytes: int = typer.Option(1024 * 1024, "--max-inline-bytes", help="Maximum decoded bytes for inline sources"),+ allow_http_source: bool = typer.Option(False, "--allow-http-source", help="Allow URL sources to use plain HTTP"),language: str = typer.Option("ch","--language",@@ -104,6 +107,9 @@ def api_server_command(tier=tier, # type: ignore[arg-type]concurrency=concurrency,url_timeout=url_timeout,+ allow_local_source=allow_local_source,+ max_inline_bytes=max_inline_bytes,+ allow_http_source=allow_http_source,language=language,ocr_mode=ocr_mode, # type: ignore[arg-type]disable_image_analysis=disable_image_analysis,diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.pyindex 4c08f4c1..0c2052aa 100644--- a/mineru/parser/api_client.py+++ b/mineru/parser/api_client.py@@ -36,8 +36,9 @@ class MinerUApiParser(DocumentParser):Works with local-server, LAN, and cloud (mineru.net) deployments::- # local deployment — uses ``local`` source, no upload needed- parser = MinerUApiParser(api_url="http://localhost:8000/api", tier="medium")+ # local deployment — uses ``local`` source only when the server advertises it.+ # Start the local server with --allow-local-source to skip upload.+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="medium")# cloud (remote)parser = MinerUApiParser(@@ -69,6 +70,7 @@ class MinerUApiParser(DocumentParser):self._api_key = (api_key if api_key is not None else os.environ.get("MINERU_API_KEY")) or Noneself._local = _is_local_network_url(self._base_url)self._trust_env = should_trust_env_for_url(self._base_url)+ self._source_features: set[str] | None = Noneself.tier = validate_tier(tier) if tier is not None else Noneself.include_images = include_imagesself.include_model_output = include_model_output@@ -80,7 +82,7 @@ class MinerUApiParser(DocumentParser):if not file_path.exists():raise FileNotFoundError(file_path)- payload = self._build_payload(file_path, page_range)+ payload = self._build_payload(self._build_source(file_path), page_range)job = self._do_parse(payload)return self._build_result(job, file_path.name)@@ -89,21 +91,30 @@ class MinerUApiParser(DocumentParser):if not file_path.exists():raise FileNotFoundError(file_path)- payload = self._build_payload(file_path, page_range)+ payload = self._build_payload(await self._async_build_source(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, page_range: str) -> dict[str, Any]:- source: dict[str, Any]- if self._local:+ def _build_source(self, file_path: Path) -> dict[str, Any]:+ if self._supports_local_source():source = {"type": "local", "path": str(file_path)}else:# upload flow: create → PUT → complete → file_idfile_id = self._upload(file_path)source = {"type": "file_id", "file_id": file_id}+ return source+ async def _async_build_source(self, file_path: Path) -> dict[str, Any]:+ if await self._async_supports_local_source():+ source = {"type": "local", "path": str(file_path)}+ else:+ file_id = await self._async_upload(file_path)+ source = {"type": "file_id", "file_id": file_id}+ return source++ def _build_payload(self, source: dict[str, Any], page_range: str) -> dict[str, Any]:file_entry: dict[str, Any] = {"source": source}if page_range:file_entry["page_range"] = page_range@@ -116,6 +127,34 @@ class MinerUApiParser(DocumentParser):payload["tier"] = self.tierreturn payload+ def _supports_local_source(self) -> bool:+ if not self._local:+ return False+ return "local" in self._get_source_features()++ async def _async_supports_local_source(self) -> bool:+ if not self._local:+ return False+ return "local" in await self._async_get_source_features()++ def _get_source_features(self) -> set[str]:+ if self._source_features is not None:+ return self._source_features+ with httpx.Client(timeout=httpx.Timeout(30, connect=10), trust_env=self._trust_env) as cli:+ r = cli.get(f"{self._base_url}/v1/health", headers=self._headers())+ health = self._check(r)+ self._source_features = _extract_feature_list(health, "sources")+ return self._source_features++ async def _async_get_source_features(self) -> set[str]:+ if self._source_features is not None:+ return self._source_features+ async with httpx.AsyncClient(timeout=httpx.Timeout(30, connect=10), trust_env=self._trust_env) as cli:+ r = await cli.get(f"{self._base_url}/v1/health", headers=self._headers())+ health = self._check(r)+ self._source_features = _extract_feature_list(health, "sources")+ return self._source_features+def _output_formats(self) -> list[str]:if self.include_model_output or self.include_images:return ["zip"]@@ -287,6 +326,16 @@ def _sha256_file(path: Path) -> str:return h.hexdigest()+def _extract_feature_list(health: dict[str, Any], name: str) -> set[str]:+ features = health.get("features")+ if not isinstance(features, dict):+ return set()+ values = features.get(name)+ if not isinstance(values, list):+ return set()+ return {item for item in values if isinstance(item, str)}++def _mime_type(path: Path) -> str:ext = path.suffix.lower()return {diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex 579c956f..d2c7c8ec 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -28,6 +28,7 @@ from contextlib import asynccontextmanagerfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import Annotated, Any, AsyncIterator, Callable, Literal, NoReturn+from urllib.parse import urlparseimport clickimport httpx@@ -55,6 +56,15 @@ _API_SERVER_TIERS: tuple[Tier, ...] = ("flash", "medium", "high", "extra_high")_DEFAULT_API_SERVER_TIER: Tier = "high"_API_SERVER_LANGUAGES = PUBLIC_OCR_LANGUAGES_MANAGED_PARSE_SERVER_ENV = "MINERU_MANAGED_PARSE_SERVER"+_MAX_INLINE_BYTES_DEFAULT = 1024 * 1024+_LOCAL_PARSE_OUTPUT_FORMATS: tuple[OutputFormat, ...] = (+ "markdown",+ "middle_json",+ "content_list",+ "structured_content",+ "zip",+)+_BASE_PARSE_SOURCES: tuple[SourceType, ...] = ("file_id", "url", "inline")logger = logging.getLogger("mineru.parser.api_server")@@ -273,6 +283,8 @@ class ModelHealthStatus(BaseModel):class HealthFeatures(BaseModel):model_config = _PYDANTIC_CONFIGwebhook: bool = False+ output_formats: list[OutputFormat] = Field(default_factory=lambda: list(_LOCAL_PARSE_OUTPUT_FORMATS))+ sources: list[SourceType] = Field(default_factory=lambda: list(_BASE_PARSE_SOURCES))class HealthResponse(BaseModel):@@ -1000,13 +1012,73 @@ _SUPPORTED_SUFFIXES: dict[str, str] = {".htm": "html",}-_OUTPUT_FORMATS_LOCAL = {- "markdown",- "middle_json",- "content_list",- "structured_content",- "zip",-}+_OUTPUT_FORMATS_LOCAL = set(_LOCAL_PARSE_OUTPUT_FORMATS)+++def _parse_sources_for_server(*, allow_local_source: bool) -> list[SourceType]:+ sources = list(_BASE_PARSE_SOURCES)+ if allow_local_source:+ sources.append("local")+ return sources+++def _decode_inline_data(data: str) -> bytes:+ try:+ return base64.b64decode(data, validate=True)+ except Exception as exc:+ raise ValueError("inline source data must be valid base64") from exc+++def _validate_source_policy(+ source: FileSource,+ *,+ allow_local_source: bool,+ max_inline_bytes: int,+ allow_http_source: bool,+) -> None:+ if isinstance(source, UrlSource):+ scheme = urlparse(source.url).scheme.lower()+ if scheme == "https":+ return+ if scheme == "http" and allow_http_source:+ return+ if scheme == "http":+ raise ValueError("url source must use https unless --allow-http-source is enabled")+ raise ValueError("url source must use http or https")+ if isinstance(source, InlineSource):+ data = _decode_inline_data(source.data)+ if len(data) > max_inline_bytes:+ raise ValueError(f"inline source exceeds max_inline_bytes ({max_inline_bytes})")+ return+ if isinstance(source, LocalSource):+ if not allow_local_source:+ raise ValueError("local source is disabled; enable --allow-local-source")+ return+++def _validate_job_source_policy(+ req: CreateJobRequest,+ *,+ allow_local_source: bool,+ max_inline_bytes: int,+ allow_http_source: bool,+) -> None:+ for index, entry in enumerate(req.files):+ try:+ _validate_source_policy(+ entry.source,+ allow_local_source=allow_local_source,+ max_inline_bytes=max_inline_bytes,+ allow_http_source=allow_http_source,+ )+ except ValueError as exc:+ _raise_api_error(+ 400,+ error_type="invalid_request_error",+ code="invalid_request",+ message=str(exc),+ param=f"files.{index}.source",+ )@dataclassclass _JobRecord:@@ -1237,7 +1309,21 @@ def _count_pages_in_range(page_range: str) -> int:return total-async def _extract_bytes(source: FileSource, file_store: FileStore, *, url_timeout: int = 60) -> bytes:+async def _extract_bytes(+ source: FileSource,+ file_store: FileStore,+ *,+ url_timeout: int = 60,+ allow_local_source: bool = False,+ max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,+ allow_http_source: bool = False,+) -> bytes:+ _validate_source_policy(+ source,+ allow_local_source=allow_local_source,+ max_inline_bytes=max_inline_bytes,+ allow_http_source=allow_http_source,+ )if isinstance(source, FileIdSource):rec = file_store.get_file(source.file_id)if rec.sha256sum is None:@@ -1249,9 +1335,9 @@ async def _extract_bytes(source: FileSource, file_store: FileStore, *, url_timeor.raise_for_status()return r.contentif isinstance(source, InlineSource):- return base64.b64decode(source.data)+ return _decode_inline_data(source.data)if isinstance(source, LocalSource):- return pathlib.Path(source.path).read_bytes()+ return pathlib.Path(source.path).expanduser().resolve(strict=False).read_bytes()raise ValueError(f"Unknown source type: {type(source)}")@@ -1271,6 +1357,9 @@ async def _run_job(image_analysis: bool,effort: str = DEFAULT_HYBRID_EFFORT,url_timeout: int = 60,+ allow_local_source: bool = False,+ max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,+ allow_http_source: bool = False,) -> None:rec.status = "running"rec.started_at = JobStore._now()@@ -1282,7 +1371,14 @@ async def _run_job(fr = rec.files[i]try:file_started = time.monotonic()- data = await _extract_bytes(entry.source, file_store, url_timeout=url_timeout)+ data = await _extract_bytes(+ entry.source,+ file_store,+ url_timeout=url_timeout,+ allow_local_source=allow_local_source,+ max_inline_bytes=max_inline_bytes,+ allow_http_source=allow_http_source,+ )stype = _suffix_type(fr.name)if not stype:raise ValueError(f"Unsupported file type: {fr.name}")@@ -1411,12 +1507,13 @@ _ERR_429: dict[int | str, dict[str, Any]] = {429: {"model": ErrorResponse}}responses={503: {"model": ErrorResponse}},tags=["Health"],)-async def get_health() -> HealthResponse:+async def get_health(request: Request) -> HealthResponse:"""Health check endpoint."""return HealthResponse(version=__version__,parser_version=__version__,models=ModelHealthStatus(),+ features=HealthFeatures(sources=_parse_sources_for_server(allow_local_source=request.app.state.allow_local_source)),)@@ -1699,9 +1796,19 @@ async def create_job(message=f"Tier '{body.tier}' not available in this server",)+ _validate_job_source_policy(+ body,+ allow_local_source=request.app.state.allow_local_source,+ max_inline_bytes=request.app.state.max_inline_bytes,+ allow_http_source=request.app.state.allow_http_source,+ )+rec = job_store.create(body, file_store)backend = runtime.backendurl_timeout_val: int = request.app.state.url_timeout+ allow_local_source_val: bool = request.app.state.allow_local_source+ max_inline_bytes_val: int = request.app.state.max_inline_bytes+ allow_http_source_val: bool = request.app.state.allow_http_sourcelanguage_val: str = request.app.state.languageocr_mode_val: str = request.app.state.ocr_modeeffort_val = runtime.effort@@ -1720,6 +1827,9 @@ async def create_job(effort=effort_val,image_analysis=image_analysis_val,url_timeout=url_timeout_val,+ allow_local_source=allow_local_source_val,+ max_inline_bytes=max_inline_bytes_val,+ allow_http_source=allow_http_source_val,)asyncio.create_task(_bg_run())@@ -1911,6 +2021,9 @@ def create_app(tier: Tier | list[Tier] | tuple[Tier, ...] | None = None,concurrency: int = 1,url_timeout: int = 60,+ allow_local_source: bool = False,+ max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,+ allow_http_source: bool = False,api_key: str | None = None,language: str = "ch",ocr_mode: str = "auto",@@ -1929,6 +2042,12 @@ def create_app(Maximum concurrent parse jobs (default 1).url_timeout:Timeout in seconds for downloading url sources (default 60).+ allow_local_source:+ Whether ``local`` sources may read paths visible to the server process.+ max_inline_bytes:+ Maximum decoded bytes accepted for ``inline`` sources.+ allow_http_source:+ Whether ``url`` sources may use plain HTTP. HTTPS is always allowed.api_key:Optional API key. When set, clients must pass ``Authorization: Bearer <key>``to access list endpoints and advanced output formats.@@ -1953,6 +2072,8 @@ def create_app(_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)+ if max_inline_bytes < 0:+ raise ValueError("max_inline_bytes must be non-negative")language = validate_public_ocr_lang(language)_model_ids, _tiers = _model_ids_and_tiers_for_server_tiers(server_tiers)@@ -1968,6 +2089,9 @@ def create_app(application.state.tiers = _tiersapplication.state.concurrency = concurrencyapplication.state.url_timeout = url_timeout+ application.state.allow_local_source = allow_local_source+ application.state.max_inline_bytes = max_inline_bytes+ application.state.allow_http_source = allow_http_sourceapplication.state.api_key = _api_keyapplication.state.language = languageapplication.state.ocr_mode = ocr_mode@@ -1996,6 +2120,9 @@ def create_app(application.state.tiers = _tiersapplication.state.concurrency = concurrencyapplication.state.url_timeout = url_timeout+ application.state.allow_local_source = allow_local_source+ application.state.max_inline_bytes = max_inline_bytes+ application.state.allow_http_source = allow_http_sourceapplication.state.api_key = _api_keyapplication.state.language = languageapplication.state.ocr_mode = ocr_mode@@ -2097,6 +2224,22 @@ def create_app(type=int,help="Timeout in seconds for url source downloads (default: 60)",)+ "--allow-local-source",+ is_flag=True,+ help="Allow local sources to read any path visible to the server process.",+)+ "--max-inline-bytes",+ default=_MAX_INLINE_BYTES_DEFAULT,+ type=int,+ help=f"Maximum decoded bytes for inline sources (default: {_MAX_INLINE_BYTES_DEFAULT})",+)+ "--allow-http-source",+ is_flag=True,+ help="Allow url sources to use plain HTTP. HTTPS is always allowed.",+)@click.option("--language",default="ch",@@ -2124,6 +2267,9 @@ def main(tier: tuple[Tier, ...],concurrency: int,url_timeout: int,+ allow_local_source: bool,+ max_inline_bytes: int,+ allow_http_source: bool,language: str,ocr_mode: str,disable_image_analysis: bool,@@ -2136,6 +2282,9 @@ def main(tier=tier or None,concurrency=concurrency,url_timeout=url_timeout,+ allow_local_source=allow_local_source,+ max_inline_bytes=max_inline_bytes,+ allow_http_source=allow_http_source,api_key=api_key,language=language,ocr_mode=ocr_mode,diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex 71f6cdb3..05313e33 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -295,6 +295,7 @@ def test_managed_api_server_args_use_tier_and_selected_port_for_process_start()"127.0.0.1","--port","16580",+ "--allow-local-source",]assert api_server_args_for_tier("extra_high", host="127.0.0.2", port=16581) == ["--tier",@@ -303,6 +304,7 @@ def test_managed_api_server_args_use_tier_and_selected_port_for_process_start()"127.0.0.2","--port","16581",+ "--allow-local-source",]diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 8b4154ba..3a79e4e8 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -1,4 +1,5 @@import asyncio+import base64import importlibimport inspectimport io@@ -179,19 +180,132 @@ def test_api_client_builds_file_page_range_without_options(tmp_path: Path) -> Nopdf.write_bytes(b"%PDF-1.7\n")parser = MinerUApiParser(api_url="http://localhost:8000", tier="high")- payload = parser._build_payload(pdf, "1,3~5")+ payload = parser._build_payload({"type": "local", "path": str(pdf)}, "1,3~5")assert payload["output_formats"] == ["middle_json"]assert payload["files"] == [{"source": {"type": "local", "path": str(pdf)}, "page_range": "1,3~5"}]assert "options" not in payload["files"][0]+def test_api_client_uses_file_id_when_local_server_does_not_advertise_local_source(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pdf = tmp_path / "demo.pdf"+ pdf.write_bytes(b"%PDF-1.7\n")+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="high")+ monkeypatch.setattr(parser, "_upload", lambda _path: "file_1")++ class _Response:+ status_code = 200+ text = ""++ def json(self) -> dict[str, object]:+ return {"features": {"sources": ["file_id", "url", "inline"]}}++ class _Client:+ def __init__(self, *, timeout: object, trust_env: bool, **_: object) -> None:+ assert trust_env is False++ def __enter__(self) -> "_Client":+ return self++ def __exit__(self, *args: object) -> None:+ return None++ def get(self, url: str, headers: dict[str, str]) -> _Response:+ assert url == "http://localhost:8000/v1/health"+ assert headers == {}+ return _Response()++ monkeypatch.setattr("mineru.parser.api_client.httpx.Client", _Client)++ source = parser._build_source(pdf)++ assert source == {"type": "file_id", "file_id": "file_1"}+++def test_api_client_uses_local_source_when_health_advertises_it(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ pdf = tmp_path / "demo.pdf"+ pdf.write_bytes(b"%PDF-1.7\n")+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="high")+ monkeypatch.setattr(parser, "_upload", lambda _path: pytest.fail("local source should not upload"))++ class _Response:+ status_code = 200+ text = ""++ def json(self) -> dict[str, object]:+ return {"features": {"sources": ["file_id", "url", "inline", "local"]}}++ class _Client:+ def __init__(self, **_: object) -> None:+ pass++ def __enter__(self) -> "_Client":+ return self++ def __exit__(self, *args: object) -> None:+ return None++ def get(self, url: str, headers: dict[str, str]) -> _Response:+ return _Response()++ monkeypatch.setattr("mineru.parser.api_client.httpx.Client", _Client)++ source = parser._build_source(pdf)++ assert source == {"type": "local", "path": str(pdf)}+++def test_async_api_client_uses_file_id_when_local_server_does_not_advertise_local_source(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pdf = tmp_path / "demo.pdf"+ pdf.write_bytes(b"%PDF-1.7\n")+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="high")++ async def _async_upload(_path: Path) -> str:+ return "file_1"++ monkeypatch.setattr(parser, "_async_upload", _async_upload)++ class _Response:+ status_code = 200+ text = ""++ def json(self) -> dict[str, object]:+ return {"features": {"sources": ["file_id", "url", "inline"]}}++ class _AsyncClient:+ def __init__(self, *, timeout: object, trust_env: bool, **_: object) -> None:+ assert trust_env is False++ async def __aenter__(self) -> "_AsyncClient":+ return self++ async def __aexit__(self, *args: object) -> None:+ return None++ async def get(self, url: str, headers: dict[str, str]) -> _Response:+ assert url == "http://localhost:8000/v1/health"+ assert headers == {}+ return _Response()++ monkeypatch.setattr("mineru.parser.api_client.httpx.AsyncClient", _AsyncClient)++ source = asyncio.run(parser._async_build_source(pdf))++ assert source == {"type": "file_id", "file_id": "file_1"}++def test_api_client_can_request_zip_for_model_output(tmp_path: Path) -> None:pdf = tmp_path / "demo.pdf"pdf.write_bytes(b"%PDF-1.7\n")parser = MinerUApiParser(api_url="http://localhost:8000", tier="high", include_model_output=True)- payload = parser._build_payload(pdf, "")+ payload = parser._build_payload({"type": "local", "path": str(pdf)}, "")assert payload["output_formats"] == ["zip"]@@ -205,7 +319,7 @@ def test_api_client_can_request_zip_for_image_cache(tmp_path: Path) -> None:tier="high",include_images=True,)- payload = parser._build_payload(pdf, "")+ payload = parser._build_payload({"type": "local", "path": str(pdf)}, "")assert payload["output_formats"] == ["zip"]@@ -235,7 +349,7 @@ def test_api_client_uses_tier_without_backend_semantics(tmp_path: Path) -> None:pdf.write_bytes(b"%PDF-1.7\n")parser = MinerUApiParser(api_url="http://localhost:8000", tier="extra_high")- payload = parser._build_payload(pdf, "")+ payload = parser._build_payload({"type": "local", "path": str(pdf)}, "")assert payload["tier"] == "extra_high"assert not hasattr(parser, "backend")@@ -818,8 +932,8 @@ def test_async_api_client_include_images_rejects_unsafe_zip_image_sidecar_paths(def test_api_client_disables_env_proxy_for_local_network_urls() -> None:- assert should_trust_env_for_url("http://localhost:8000/api") is False- assert should_trust_env_for_url("http://127.0.0.1:8000/api") is False+ assert should_trust_env_for_url("http://localhost:8000") is False+ assert should_trust_env_for_url("http://127.0.0.1:8000") is Falseassert should_trust_env_for_url("http://192.168.1.20:8000/api") is Falseassert should_trust_env_for_url("https://staging.mineru.org.cn/api") is True@@ -849,7 +963,7 @@ def test_api_client_passes_trust_env_from_api_url(monkeypatch: pytest.MonkeyPatcmonkeypatch.setattr("mineru.parser.api_client.httpx.Client", _Client)- MinerUApiParser(api_url="http://127.0.0.1:8000/api")._do_parse({"files": []})+ MinerUApiParser(api_url="http://127.0.0.1:8000")._do_parse({"files": []})MinerUApiParser(api_url="https://mineru.net/api")._do_parse({"files": []})assert calls == [False, True]@@ -923,7 +1037,7 @@ def test_api_client_omits_tier_when_unspecified(tmp_path: Path) -> None:pdf.write_bytes(b"%PDF-1.7\n")parser = MinerUApiParser(api_url="http://localhost:8000")- payload = parser._build_payload(pdf, "")+ payload = parser._build_payload({"type": "local", "path": str(pdf)}, "")assert "tier" not in payload@@ -964,7 +1078,7 @@ def test_api_client_omits_page_range_when_unspecified(tmp_path: Path) -> None:pdf.write_bytes(b"%PDF-1.7\n")parser = MinerUApiParser(api_url="http://localhost:8000", tier="high")- payload = parser._build_payload(pdf, "")+ payload = parser._build_payload({"type": "local", "path": str(pdf)}, "")assert payload["files"] == [{"source": {"type": "local", "path": str(pdf)}}]@@ -1103,6 +1217,83 @@ def test_create_job_request_accepts_new_format_names_and_rejects_options() -> No)+def test_api_server_rejects_local_source_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_api_server_dependency_preflight(monkeypatch)+ source = tmp_path / "demo.pdf"+ source.write_bytes(b"%PDF-1.7\n")+ app = create_app(upload_dir=str(tmp_path / "api"), tier="flash")++ with TestClient(app) as client:+ response = client.post(+ "/v1/parse/jobs",+ json={"files": [{"source": {"type": "local", "path": str(source)}}]},+ )++ assert response.status_code == 400+ body = response.json()+ assert body["error"]["code"] == "invalid_request"+ assert body["error"]["param"] == "files.0.source"+ assert "--allow-local-source" in body["error"]["message"]+++def test_api_server_health_sources_reflect_local_source_flag(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_api_server_dependency_preflight(monkeypatch)+ default_app = create_app(upload_dir=str(tmp_path / "default"), tier="flash")+ local_app = create_app(upload_dir=str(tmp_path / "local"), tier="flash", allow_local_source=True)++ with TestClient(default_app) as client:+ default_sources = client.get("/v1/health").json()["features"]["sources"]+ with TestClient(local_app) as client:+ local_sources = client.get("/v1/health").json()["features"]["sources"]++ assert default_sources == ["file_id", "url", "inline"]+ assert local_sources == ["file_id", "url", "inline", "local"]+++def test_api_server_rejects_inline_source_over_configured_limit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_api_server_dependency_preflight(monkeypatch)+ app = create_app(upload_dir=str(tmp_path), tier="flash", max_inline_bytes=3)++ with TestClient(app) as client:+ response = client.post(+ "/v1/parse/jobs",+ json={+ "files": [+ {+ "source": {+ "type": "inline",+ "name": "demo.pdf",+ "data": base64.b64encode(b"1234").decode("ascii"),+ }+ }+ ]+ },+ )++ assert response.status_code == 400+ body = response.json()+ assert body["error"]["code"] == "invalid_request"+ assert body["error"]["param"] == "files.0.source"+ assert "max_inline_bytes" in body["error"]["message"]+++def test_api_server_rejects_plain_http_url_source_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_api_server_dependency_preflight(monkeypatch)+ app = create_app(upload_dir=str(tmp_path), tier="flash")++ with TestClient(app) as client:+ response = client.post(+ "/v1/parse/jobs",+ json={"files": [{"source": {"type": "url", "url": "http://example.test/demo.pdf"}}]},+ )++ assert response.status_code == 400+ body = response.json()+ assert body["error"]["code"] == "invalid_request"+ assert body["error"]["param"] == "files.0.source"+ assert "https" in body["error"]["message"]++def test_local_parse_server_rejects_callback(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:_stub_api_server_dependency_preflight(monkeypatch)app = create_app(upload_dir=str(tmp_path))@@ -1181,6 +1372,9 @@ def test_create_app_does_not_read_runtime_settings_from_env(tmp_path: Path, monkassert app.state.backend == "hybrid-engine"assert app.state.concurrency == 1assert app.state.url_timeout == 60+ assert app.state.allow_local_source is False+ assert app.state.max_inline_bytes == 1024 * 1024+ assert app.state.allow_http_source is Falseassert app.state.language == "ch"assert app.state.ocr_mode == "auto"assert app.state.effort == "high"@@ -1309,6 +1503,7 @@ def test_api_server_rendered_outputs_do_not_return_image_sidecars(ocr_mode="auto",image_analysis=True,effort="medium",+ allow_local_source=True,))@@ -1365,6 +1560,7 @@ def test_api_server_middle_json_preserves_backend_for_client_rendering(ocr_mode="auto",image_analysis=True,effort="medium",+ allow_local_source=True,))@@ -1415,6 +1611,7 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(ocr_mode="auto",image_analysis=True,effort="medium",+ allow_local_source=True,))@@ -1477,6 +1674,7 @@ def test_api_server_zip_is_self_contained_when_only_zip_requested(ocr_mode="auto",image_analysis=True,effort="medium",+ allow_local_source=True,))@@ -1533,6 +1731,7 @@ def test_api_server_zip_rejects_unsafe_image_sidecar_path(ocr_mode="auto",image_analysis=True,effort="medium",+ allow_local_source=True,))@@ -1577,6 +1776,7 @@ def test_api_server_zip_skips_model_output_when_parse_result_has_none(ocr_mode="auto",image_analysis=True,effort="medium",+ allow_local_source=True,))@@ -1639,6 +1839,7 @@ def test_api_server_sanitizes_surrogates_in_text_outputs(ocr_mode="auto",image_analysis=True,effort="medium",+ allow_local_source=True,))@@ -1692,6 +1893,7 @@ def test_api_server_logs_traceback_when_job_file_fails(ocr_mode="auto",image_analysis=True,effort="medium",+ allow_local_source=True,))@@ -1727,7 +1929,11 @@ def test_api_contract_uses_parser_version_not_backend_version() -> None:"status": "ok","version": "3.2.1","parser_version": "3.2.1",- "features": {"webhook": False},+ "features": {+ "webhook": False,+ "output_formats": ["markdown", "middle_json", "content_list", "structured_content", "zip"],+ "sources": ["file_id", "url", "inline"],+ },}with pytest.raises(ValidationError):@@ -1853,7 +2059,7 @@ def test_api_server_multi_tier_jobs_use_requested_tier_runtime(tmp_path: Path, mmonkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)source = tmp_path / "demo.pdf"source.write_bytes(b"%PDF-1.7\n")- app = create_app(upload_dir=str(tmp_path / "api"), tier=["medium", "high"])+ app = create_app(upload_dir=str(tmp_path / "api"), tier=["medium", "high"], allow_local_source=True)file_store = FileStore(tmp_path / "api-files")job_store = api_server.JobStore()@@ -1871,6 +2077,9 @@ def test_api_server_multi_tier_jobs_use_requested_tier_runtime(tmp_path: Path, mocr_mode=app.state.ocr_mode,effort=runtime.effort,image_analysis=app.state.image_analysis,+ allow_local_source=app.state.allow_local_source,+ max_inline_bytes=app.state.max_inline_bytes,+ allow_http_source=app.state.allow_http_source,)return job_store.build_response(rec).model_dump(by_alias=True)@@ -2259,6 +2468,9 @@ def test_api_server_cli_exposes_parser_runtime_options() -> None:assert "--backend" not in option_namesassert "--language" in option_namesassert "--ocr-mode" in option_names+ assert "--allow-local-source" in option_names+ assert "--max-inline-bytes" in option_names+ assert "--allow-http-source" in option_namesassert "--effort" not in option_namesassert "--disable-image-analysis" in option_namesassert _REMOVED_DISABLE_TABLE_OPTION not in option_names