Skip to content

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

feat: add API protocol version and default processing window size to client

myhloli40a52da3cfa4
diff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.md
index 0b9ef302..545d944c 100644
--- a/docs/en/usage/cli_tools.md
+++ b/docs/en/usage/cli_tools.md
@@ -10,20 +10,17 @@ Options:
-v, --version Show version and exit
-p, --path PATH Input file path or directory (required)
-o, --output PATH Output directory (required)
+ --api-url TEXT MinerU FastAPI base URL; if omitted, `mineru` starts a temporary local `mineru-api`
-m, --method [auto|txt|ocr] Parsing method: auto (default), txt, ocr (pipeline and hybrid* backend only)
-b, --backend [pipeline|hybrid-auto-engine|hybrid-http-client|vlm-auto-engine|vlm-http-client]
Parsing backend (default: hybrid-auto-engine)
-l, --lang [ch|ch_server|ch_lite|en|korean|japan|chinese_cht|ta|te|ka|th|el|latin|arabic|east_slavic|cyrillic|devanagari]
Specify document language (improves OCR accuracy, pipeline and hybrid* backend only)
- -u, --url TEXT Service address when using http-client
+ -u, --url TEXT OpenAI-compatible backend URL passed through to the server when using http-client
-s, --start INTEGER Starting page number for parsing (0-based)
-e, --end INTEGER Ending page number for parsing (0-based)
-f, --formula BOOLEAN Enable formula parsing (default: enabled)
-t, --table BOOLEAN Enable table parsing (default: enabled)
- -d, --device TEXT Inference device (e.g., cpu/cuda/cuda:0/npu/mps, pipeline and vlm-transformers backend only)
- --vram INTEGER Maximum GPU VRAM usage per process (GB) (pipeline backend only)
- --source [huggingface|modelscope|local]
- Model source, default: huggingface
--help Show help information
```
```bash
@@ -62,23 +59,14 @@ Options:
## Environment Variables Description
+> [!NOTE]
+> Starting from this version, `mineru` is an orchestration client built on top of `mineru-api`:
+> - Without `--api-url`, the CLI launches a temporary local `mineru-api`
+> - With `--api-url`, the CLI connects to that FastAPI service directly
+> - `--url` is no longer the MinerU API address; it is the OpenAI-compatible backend URL used by server-side `vlm/hybrid-http-client`
+
Some parameters of MinerU command line tools have equivalent environment variable configurations. Generally, environment variable configurations have higher priority than command line parameters and take effect across all command line tools.
Here are the environment variables and their descriptions:
-
-- `MINERU_DEVICE_MODE`:
- * Used to specify inference device
- * supports device types like `cpu/cuda/cuda:0/npu/mps`
- * only effective for `pipeline` and `vlm-transformers` backends.
-
-- `MINERU_VIRTUAL_VRAM_SIZE`:
- * Used to specify maximum GPU VRAM usage per process (GB)
- * only effective for `pipeline` backend.
-
-- `MINERU_MODEL_SOURCE`:
- * Used to specify model source
- * supports `huggingface/modelscope/local`
- * Default is `huggingface`; you can switch via an environment variable to `modelscope` to use a domestic acceleration mirror, or switch to `local` to use a local model.
-
- `MINERU_TOOLS_CONFIG_JSON`:
* Used to specify configuration file path
diff --git a/docs/en/usage/quick_usage.md b/docs/en/usage/quick_usage.md
index f5e08426..b17f3dd0 100644
--- a/docs/en/usage/quick_usage.md
+++ b/docs/en/usage/quick_usage.md
@@ -15,6 +15,8 @@ mineru -p <input_path> -o <output_path>
> [!TIP]
>- `<input_path>`: Local PDF/image file or directory
>- `<output_path>`: Output directory
+>- Without `--api-url`, the CLI launches a temporary local `mineru-api`
+>- With `--api-url`, the CLI connects to an existing local or remote FastAPI service directly
>
> For more information about output files, please refer to [Output File Documentation](../reference/output_files.md).
@@ -35,6 +37,7 @@ If you need to adjust parsing options through custom parameters, you can also ch
>Access `http://127.0.0.1:8000/docs` in your browser to view the API documentation.
>
>- Health endpoint: `GET /health`
+ > Returns `protocol_version`, `processing_window_size`, `max_concurrent_requests`, and task stats
>- Asynchronous task submission endpoint: `POST /tasks`
>- Synchronous parsing endpoint: `POST /file_parse`
>- Task query endpoints: `GET /tasks/{task_id}`, `GET /tasks/{task_id}/result`
@@ -56,7 +59,9 @@ If you need to adjust parsing options through custom parameters, you can also ch
>```bash
>curl -X POST http://127.0.0.1:8000/file_parse \
> -F "files=@demo/pdfs/demo1.pdf" \
- > -F "return_md=true"
+ > -F "return_md=true" \
+ > -F "response_format_zip=true" \
+ > -F "return_original_file=true"
>```
>
>Poll task status and fetch results:
diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.md
index 0b386d44..be8e6af6 100644
--- a/docs/zh/usage/cli_tools.md
+++ b/docs/zh/usage/cli_tools.md
@@ -10,20 +10,17 @@ Options:
-v, --version 显示版本并退出
-p, --path PATH 输入文件路径或目录(必填)
-o, --output PATH 输出目录(必填)
+ --api-url TEXT MinerU FastAPI 服务地址;不传时自动拉起本地临时 mineru-api
-m, --method [auto|txt|ocr] 解析方法:auto(默认)、txt、ocr(仅用于 pipeline 与 hybrid* 后端)
-b, --backend [pipeline|hybrid-auto-engine|hybrid-http-client|vlm-auto-engine|vlm-http-client]
解析后端(默认为 hybrid-auto-engine)
-l, --lang [ch|ch_server|ch_lite|en|korean|japan|chinese_cht|ta|te|ka|th|el|latin|arabic|east_slavic|cyrillic|devanagari]
指定文档语言(可提升 OCR 准确率,仅用于 pipeline 与 hybrid* 后端)
- -u, --url TEXT 当使用 http-client 时,需指定服务地址
+ -u, --url TEXT 当使用 http-client 时,传给服务端后端的 OpenAI 兼容地址
-s, --start INTEGER 开始解析的页码(从 0 开始)
-e, --end INTEGER 结束解析的页码(从 0 开始)
-f, --formula BOOLEAN 是否启用公式解析(默认开启)
-t, --table BOOLEAN 是否启用表格解析(默认开启)
- -d, --device TEXT 推理设备(如 cpu/cuda/cuda:0/npu/mps,仅 pipeline 后端)
- --vram INTEGER 单进程最大 GPU 显存占用(GB)(仅 pipeline 后端)
- --source [huggingface|modelscope|local]
- 模型来源,默认 huggingface
--help 显示帮助信息
```
```bash
@@ -57,23 +54,15 @@ Options:
## 环境变量说明
+> [!NOTE]
+> 从当前版本开始,`mineru` 是基于 `mineru-api` 的编排客户端:
+> - 未传 `--api-url` 时,CLI 会自动拉起本地临时 `mineru-api`
+> - 传入 `--api-url` 时,CLI 会直连该 FastAPI 服务
+> - `--url` 不再表示 MinerU API 地址,而是服务端 `vlm/hybrid-http-client` 所需的 OpenAI 兼容地址
+
MinerU命令行工具的某些参数存在相同功能的环境变量配置,通常环境变量配置的优先级高于命令行参数,且在所有命令行工具中都生效。
以下是常用的环境变量及其说明:
-- `MINERU_DEVICE_MODE`:
- * 用于指定推理设备
- * 支持`cpu/cuda/cuda:0/npu/mps`等设备类型
- * 仅对`pipeline`后端生效。
-
-- `MINERU_VIRTUAL_VRAM_SIZE`:
- * 用于指定单进程最大 GPU 显存占用(GB)
- * 仅对`pipeline`后端生效。
-
-- `MINERU_MODEL_SOURCE`:
- * 用于指定模型来源
- * 支持`huggingface/modelscope/local`
- * 默认为`huggingface`可通过环境变量切换为`modelscope`使用国内加速源或切换至`local`以使用本地模型。
-
- `MINERU_TOOLS_CONFIG_JSON`:
* 用于指定配置文件路径
* 默认为用户目录下的`mineru.json`,可通过环境变量指定其他配置文件路径。
@@ -131,4 +120,4 @@ MinerU命令行工具的某些参数存在相同功能的环境变量配置,
* 用于指定 vlm/hybrid 后端使用的模型名称,这将允许您在同时存在多个模型的远程openai-server中指定 MinerU 运行所需的模型。
- `MINERU_VL_API_KEY`:
- * 用于指定 vlm/hybrid 后端使用的API Key,这将允许您在远程openai-server中进行身份验证。
\ No newline at end of file
+ * 用于指定 vlm/hybrid 后端使用的API Key,这将允许您在远程openai-server中进行身份验证。
diff --git a/docs/zh/usage/quick_usage.md b/docs/zh/usage/quick_usage.md
index e883d1b6..845fbadf 100644
--- a/docs/zh/usage/quick_usage.md
+++ b/docs/zh/usage/quick_usage.md
@@ -15,6 +15,8 @@ mineru -p <input_path> -o <output_path>
> [!TIP]
> - `<input_path>`:本地 PDF/图片 文件或目录
> - `<output_path>`:输出目录
+> - 未传 `--api-url` 时,CLI 会自动拉起本地临时 `mineru-api`
+> - 传入 `--api-url` 时,CLI 会直连远端或已有本地 FastAPI 服务
>
> 更多关于输出文件的信息,请参考[输出文件说明](../reference/output_files.md)。
@@ -35,6 +37,7 @@ mineru -p <input_path> -o <output_path>
>在浏览器中访问 `http://127.0.0.1:8000/docs` 查看API文档。
>
>- 健康检查接口:`GET /health`
+ > 返回 `protocol_version`、`processing_window_size`、`max_concurrent_requests` 等服务信息
>- 异步任务提交接口:`POST /tasks`
>- 同步解析接口:`POST /file_parse`
>- 任务查询接口:`GET /tasks/{task_id}`、`GET /tasks/{task_id}/result`
@@ -56,7 +59,9 @@ mineru -p <input_path> -o <output_path>
>```bash
>curl -X POST http://127.0.0.1:8000/file_parse \
> -F "files=@demo/pdfs/demo1.pdf" \
- > -F "return_md=true"
+ > -F "return_md=true" \
+ > -F "response_format_zip=true" \
+ > -F "return_original_file=true"
>```
>
>轮询任务状态与结果:
diff --git a/mineru/cli/api_protocol.py b/mineru/cli/api_protocol.py
new file mode 100644
index 00000000..fe7a8846
--- /dev/null
+++ b/mineru/cli/api_protocol.py
@@ -0,0 +1,4 @@
+from mineru.utils.config_reader import get_processing_window_size
+
+API_PROTOCOL_VERSION = 1
+DEFAULT_PROCESSING_WINDOW_SIZE = get_processing_window_size()
diff --git a/mineru/cli/client.py b/mineru/cli/client.py
index fe315170..8658f2c4 100644
--- a/mineru/cli/client.py
+++ b/mineru/cli/client.py
@@ -1,52 +1,796 @@
# Copyright (c) Opendatalab. All rights reserved.
+import asyncio
+import atexit
+import json
+import mimetypes
import os
+import socket
+import subprocess
import sys
+import tempfile
+import zipfile
+from contextlib import ExitStack
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath
+from typing import Awaitable, Callable, Optional
import click
-from pathlib import Path
+import httpx
+import pypdfium2 as pdfium
from loguru import logger
-from tqdm import tqdm
+
+from mineru.cli.api_protocol import (
+ API_PROTOCOL_VERSION,
+ DEFAULT_PROCESSING_WINDOW_SIZE,
+)
+from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
+from mineru.utils.pdf_page_id import get_end_page_id
+from mineru.utils.pdfium_guard import (
+ close_pdfium_document,
+ get_pdfium_document_page_count,
+ open_pdfium_document,
+)
+
+from ..version import __version__
+from .common import image_suffixes, office_suffixes, pdf_suffixes
os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
-logger.remove() # 移除默认handler
-logger.add(sys.stderr, level=log_level) # 添加新handler
+logger.remove()
+logger.add(sys.stderr, level=log_level)
+
+HEALTH_ENDPOINT = "/health"
+TASKS_ENDPOINT = "/tasks"
+TASK_STATUS_POLL_INTERVAL_SECONDS = 1.0
+TASK_RESULT_TIMEOUT_SECONDS = 600
+LOCAL_API_STARTUP_TIMEOUT_SECONDS = 30
+
+
+@dataclass(frozen=True)
+class InputDocument:
+ path: Path
+ suffix: str
+ stem: str
+ effective_pages: int
+ order: int
+
+
+@dataclass
+class PlannedTask:
+ index: int
+ documents: list[InputDocument]
+ total_pages: int
+
+
+@dataclass(frozen=True)
+class ServerHealth:
+ base_url: str
+ max_concurrent_requests: int
+ processing_window_size: int
+
+
+@dataclass(frozen=True)
+class SubmitResponse:
+ task_id: str
+ status_url: str
+ result_url: str
+
+
+@dataclass(frozen=True)
+class TaskFailure:
+ task_index: int
+ document_stems: tuple[str, ...]
+ message: str
+
+
+def build_http_timeout() -> httpx.Timeout:
+ return httpx.Timeout(connect=10, read=60, write=300, pool=30)
+
+
+class LocalAPIServer:
+ def __init__(self):
+ self.temp_dir = tempfile.TemporaryDirectory(prefix="mineru-api-client-")
+ self.temp_root = Path(self.temp_dir.name)
+ self.output_root = self.temp_root / "output"
+ self.log_path = self.temp_root / "mineru-api.log"
+ self.base_url: str | None = None
+ self.process: subprocess.Popen[bytes] | None = None
+ self._log_handle = None
+ self._atexit_registered = False
+ self._cleanup_enabled = True
+
+ def start(self) -> str:
+ if self.process is not None:
+ raise RuntimeError("Local API server is already running")
+
+ port = find_free_port()
+ self.base_url = f"http://127.0.0.1:{port}"
+ env = os.environ.copy()
+ env["MINERU_API_OUTPUT_ROOT"] = str(self.output_root)
+ self.output_root.mkdir(parents=True, exist_ok=True)
+
+ self._log_handle = open(self.log_path, "wb")
+ self.process = subprocess.Popen(
+ [
+ sys.executable,
+ "-m",
+ "mineru.cli.fast_api",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(port),
+ ],
+ stdout=self._log_handle,
+ stderr=subprocess.STDOUT,
+ cwd=os.getcwd(),
+ env=env,
+ )
+
+ if not self._atexit_registered:
+ atexit.register(self.stop)
+ self._atexit_registered = True
+ return self.base_url
+
+ def stop(self, preserve_logs: bool = False) -> None:
+ self._cleanup_enabled = not preserve_logs
+ process = self.process
+ self.process = None
+ try:
+ if process is not None and process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+ finally:
+ if self._log_handle is not None:
+ self._log_handle.close()
+ self._log_handle = None
+ if self._atexit_registered:
+ try:
+ atexit.unregister(self.stop)
+ except Exception:
+ pass
+ self._atexit_registered = False
+ if self._cleanup_enabled:
+ self.temp_dir.cleanup()
+
+ def read_log_tail(self, max_chars: int = 4000) -> str:
+ if not self.log_path.exists():
+ return ""
+ content = self.log_path.read_text(encoding="utf-8", errors="ignore")
+ if len(content) <= max_chars:
+ return content
+ return content[-max_chars:]
+
+
+def find_free_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind(("127.0.0.1", 0))
+ sock.listen(1)
+ return int(sock.getsockname()[1])
+
+
+def normalize_base_url(url: str) -> str:
+ return url.rstrip("/")
+
+
+def format_task_label(task: PlannedTask) -> str:
+ doc_names = ", ".join(doc.stem for doc in task.documents)
+ return f"task#{task.index} [{doc_names}]"
+
+
+def response_detail(response: httpx.Response) -> str:
+ try:
+ payload = response.json()
+ except Exception:
+ text = response.text.strip()
+ return text or response.reason_phrase
+
+ if isinstance(payload, dict):
+ detail = payload.get("detail")
+ if isinstance(detail, str):
+ return detail
+ error = payload.get("error")
+ if isinstance(error, str):
+ return error
+ message = payload.get("message")
+ if isinstance(message, str):
+ return message
+ return json.dumps(payload, ensure_ascii=False)
+
+
+def validate_server_health_payload(payload: dict, base_url: str) -> ServerHealth:
+ status = payload.get("status")
+ if status != "healthy":
+ raise click.ClickException(
+ f"MinerU API at {base_url} is not healthy: {json.dumps(payload, ensure_ascii=False)}"
+ )
+
+ protocol_version = payload.get("protocol_version")
+ if protocol_version != API_PROTOCOL_VERSION:
+ raise click.ClickException(
+ f"MinerU API at {base_url} returned protocol_version={protocol_version}, "
+ f"expected {API_PROTOCOL_VERSION}"
+ )
+
+ max_concurrent_requests = payload.get("max_concurrent_requests")
+ processing_window_size = payload.get("processing_window_size")
+ if not isinstance(max_concurrent_requests, int):
+ raise click.ClickException(
+ f"MinerU API at {base_url} did not return a valid max_concurrent_requests"
+ )
+ if not isinstance(processing_window_size, int):
+ raise click.ClickException(
+ f"MinerU API at {base_url} did not return a valid processing_window_size"
+ )
+
+ return ServerHealth(
+ base_url=base_url,
+ max_concurrent_requests=max_concurrent_requests,
+ processing_window_size=max(1, processing_window_size),
+ )
+
+
+async def fetch_server_health(
+ client: httpx.AsyncClient,
+ base_url: str,
+) -> ServerHealth:
+ response = await client.get(f"{base_url}{HEALTH_ENDPOINT}")
+ if response.status_code != 200:
+ raise click.ClickException(
+ f"Failed to query MinerU API health from {base_url}: "
+ f"{response.status_code} {response_detail(response)}"
+ )
+ return validate_server_health_payload(response.json(), base_url)
+
+
+async def wait_for_local_api_ready(
+ client: httpx.AsyncClient,
+ local_server: LocalAPIServer,
+ timeout_seconds: float = LOCAL_API_STARTUP_TIMEOUT_SECONDS,
+) -> ServerHealth:
+ assert local_server.base_url is not None
+ deadline = asyncio.get_running_loop().time() + timeout_seconds
+ last_error: str | None = None
+
+ while asyncio.get_running_loop().time() < deadline:
+ process = local_server.process
+ if process is not None and process.poll() is not None:
+ log_tail = local_server.read_log_tail()
+ raise click.ClickException(
+ f"Local mineru-api exited before becoming healthy. "
+ f"Log file: {local_server.log_path}\n{log_tail}"
+ )
+ try:
+ return await fetch_server_health(client, local_server.base_url)
+ except click.ClickException as exc:
+ last_error = str(exc)
+ except httpx.HTTPError as exc:
+ last_error = str(exc)
+ await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
+
+ log_tail = local_server.read_log_tail()
+ raise click.ClickException(
+ f"Timed out waiting for local mineru-api to become healthy. "
+ f"Log file: {local_server.log_path}\n{last_error or ''}\n{log_tail}"
+ )
+
+
+def probe_pdf_effective_pages(
+ path: Path,
+ start_page_id: int,
+ end_page_id: Optional[int],
+) -> int:
+ pdf_doc = open_pdfium_document(pdfium.PdfDocument, str(path))
+ try:
+ page_count = get_pdfium_document_page_count(pdf_doc)
+ finally:
+ close_pdfium_document(pdf_doc)
+
+ if page_count <= 0:
+ raise click.ClickException(f"PDF has no pages: {path}")
+
+ effective_end_page_id = get_end_page_id(end_page_id, page_count)
+ if start_page_id > effective_end_page_id:
+ raise click.ClickException(
+ f"Requested page range is empty for PDF {path}: "
+ f"start={start_page_id}, end={end_page_id}"
+ )
+ return effective_end_page_id - start_page_id + 1
+
+
+def collect_input_documents(
+ input_path: Path,
+ start_page_id: int,
+ end_page_id: Optional[int],
+) -> list[InputDocument]:
+ documents: list[Path]
+ if input_path.is_dir():
+ documents = [path for path in sorted(input_path.glob("*")) if path.is_file()]
+ else:
+ documents = [input_path]
+
+ collected: list[InputDocument] = []
+ for order, path in enumerate(documents):
+ suffix = guess_suffix_by_path(path)
+ if suffix not in pdf_suffixes + image_suffixes + office_suffixes:
+ continue
+
+ if suffix in pdf_suffixes:
+ effective_pages = probe_pdf_effective_pages(
+ path,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ )
+ else:
+ effective_pages = 1
+
+ collected.append(
+ InputDocument(
+ path=path,
+ suffix=suffix,
+ stem=path.stem,
+ effective_pages=effective_pages,
+ order=order,
+ )
+ )
+
+ if not collected:
+ raise click.ClickException(f"No supported documents found under {input_path}")
+
+ stem_to_paths: dict[str, list[Path]] = {}
+ for document in collected:
+ stem_to_paths.setdefault(document.stem, []).append(document.path)
+ duplicate_stems = {
+ stem: paths for stem, paths in stem_to_paths.items() if len(paths) > 1
+ }
+ if duplicate_stems:
+ details = "; ".join(
+ f"{stem}: {', '.join(str(path) for path in paths)}"
+ for stem, paths in sorted(duplicate_stems.items())
+ )
+ raise click.ClickException(
+ f"Duplicate output stems detected. Rename inputs to avoid collisions: {details}"
+ )
+
+ return collected
+
+
+def plan_pipeline_tasks(
+ documents: list[InputDocument],
+ processing_window_size: int,
+) -> list[PlannedTask]:
+ bins: list[PlannedTask] = []
+ sorted_docs = sorted(
+ documents,
+ key=lambda doc: (-doc.effective_pages, doc.order),
+ )
+
+ for document in sorted_docs:
+ if document.effective_pages > processing_window_size:
+ bins.append(
+ PlannedTask(
+ index=len(bins) + 1,
+ documents=[document],
+ total_pages=document.effective_pages,
+ )
+ )
+ continue
+
+ candidates = [
+ task
+ for task in bins
+ if task.total_pages + document.effective_pages <= processing_window_size
+ ]
+ if candidates:
+ selected = min(candidates, key=lambda task: (task.total_pages, task.index))
+ selected.documents.append(document)
+ selected.total_pages += document.effective_pages
+ continue
+
+ bins.append(
+ PlannedTask(
+ index=len(bins) + 1,
+ documents=[document],
+ total_pages=document.effective_pages,
+ )
+ )
+
+ for index, task in enumerate(bins, start=1):
+ task.index = index
+ return bins
+
+
+def plan_tasks(
+ documents: list[InputDocument],
+ backend: str,
+ processing_window_size: int,
+) -> list[PlannedTask]:
+ if backend == "pipeline":
+ return plan_pipeline_tasks(documents, processing_window_size)
+ return [
+ PlannedTask(index=index, documents=[document], total_pages=document.effective_pages)
+ for index, document in enumerate(documents, start=1)
+ ]
+
+
+def build_request_form_data(
+ lang: str,
+ backend: str,
+ method: str,
+ formula_enable: bool,
+ table_enable: bool,
+ server_url: Optional[str],
+ start_page_id: int,
+ end_page_id: Optional[int],
+) -> dict[str, str]:
+ data = {
+ "lang_list": lang,
+ "backend": backend,
+ "parse_method": method,
+ "formula_enable": str(formula_enable).lower(),
+ "table_enable": str(table_enable).lower(),
+ "return_md": "true",
+ "return_middle_json": "true",
+ "return_model_output": "true",
+ "return_content_list": "true",
+ "return_images": "true",
+ "response_format_zip": "true",
+ "return_original_file": "true",
+ "start_page_id": str(start_page_id),
+ "end_page_id": str(99999 if end_page_id is None else end_page_id),
+ }
+ if server_url:
+ data["server_url"] = server_url
+ return data
-from mineru.utils.cli_parser import arg_parse
-from mineru.utils.config_reader import get_device
-from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
-from mineru.utils.model_utils import get_vram
-from ..version import __version__
-from .common import do_parse, read_fn, pdf_suffixes, image_suffixes, office_suffixes
+async def submit_task(
+ client: httpx.AsyncClient,
+ base_url: str,
+ planned_task: PlannedTask,
+ form_data: dict[str, str],
+) -> SubmitResponse:
+ return await asyncio.to_thread(
+ submit_task_sync,
+ base_url,
+ planned_task,
+ form_data,
+ )
[email protected](context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
[email protected]_option(__version__,
- '--version',
- '-v',
- help='display the version and exit')
+
+def submit_task_sync(
+ base_url: str,
+ planned_task: PlannedTask,
+ form_data: dict[str, str],
+) -> SubmitResponse:
+ with httpx.Client(timeout=build_http_timeout(), follow_redirects=True) as sync_client:
+ with ExitStack() as stack:
+ files = []
+ for document in planned_task.documents:
+ mime_type = mimetypes.guess_type(document.path.name)[0] or "application/octet-stream"
+ file_handle = stack.enter_context(open(document.path, "rb"))
+ files.append(
+ (
+ "files",
+ (
+ document.path.name,
+ file_handle,
+ mime_type,
+ ),
+ )
+ )
+
+ response = sync_client.post(
+ f"{base_url}{TASKS_ENDPOINT}",
+ data=form_data,
+ files=files,
+ )
+
+ if response.status_code != 202:
+ raise click.ClickException(
+ f"Failed to submit {format_task_label(planned_task)}: "
+ f"{response.status_code} {response_detail(response)}"
+ )
+
+ payload = response.json()
+ task_id = payload.get("task_id")
+ status_url = payload.get("status_url")
+ result_url = payload.get("result_url")
+ if (
+ not isinstance(task_id, str)
+ or not isinstance(status_url, str)
+ or not isinstance(result_url, str)
+ ):
+ raise click.ClickException(
+ f"MinerU API returned an invalid task payload for {format_task_label(planned_task)}"
+ )
+ return SubmitResponse(
+ task_id=task_id,
+ status_url=status_url,
+ result_url=result_url,
+ )
+
+
+async def wait_for_task_result(
+ client: httpx.AsyncClient,
+ submit_response: SubmitResponse,
+ planned_task: PlannedTask,
+ timeout_seconds: float = TASK_RESULT_TIMEOUT_SECONDS,
+) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout_seconds
+ while asyncio.get_running_loop().time() < deadline:
+ response = await client.get(submit_response.status_url)
+ if response.status_code != 200:
+ raise click.ClickException(
+ f"Failed to query task status for {format_task_label(planned_task)}: "
+ f"{response.status_code} {response_detail(response)}"
+ )
+
+ payload = response.json()
+ status = payload.get("status")
+ if status in {"pending", "processing"}:
+ await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
+ continue
+ if status == "completed":
+ return
+ raise click.ClickException(
+ f"Task {submit_response.task_id} failed for {format_task_label(planned_task)}: "
+ f"{json.dumps(payload, ensure_ascii=False)}"
+ )
+
+ raise click.ClickException(
+ f"Timed out waiting for result of task {submit_response.task_id} "
+ f"for {format_task_label(planned_task)}"
+ )
+
+
+async def download_result_zip(
+ client: httpx.AsyncClient,
+ submit_response: SubmitResponse,
+ planned_task: PlannedTask,
+) -> Path:
+ response = await client.get(submit_response.result_url)
+ if response.status_code != 200:
+ raise click.ClickException(
+ f"Failed to download result ZIP for task {submit_response.task_id}: "
+ f"{response.status_code} {response_detail(response)}"
+ )
+ content_type = response.headers.get("content-type", "")
+ if "application/zip" not in content_type:
+ raise click.ClickException(
+ f"Expected a ZIP result for {format_task_label(planned_task)}, "
+ f"got content-type={content_type or 'unknown'}"
+ )
+
+ zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_cli_result_")
+ os.close(zip_fd)
+ Path(zip_path).write_bytes(response.content)
+ return Path(zip_path)
+
+
+def safe_extract_zip(zip_path: Path, output_dir: Path) -> None:
+ output_dir.mkdir(parents=True, exist_ok=True)
+ output_root = output_dir.resolve()
+
+ with zipfile.ZipFile(zip_path, "r") as zip_file:
+ for member in zip_file.infolist():
+ member_path = PurePosixPath(member.filename)
+ if member_path.is_absolute() or ".." in member_path.parts:
+ raise click.ClickException(
+ f"Refusing to extract unsafe ZIP entry: {member.filename}"
+ )
+ target_path = (output_root / Path(*member_path.parts)).resolve()
+ if target_path != output_root and output_root not in target_path.parents:
+ raise click.ClickException(
+ f"Refusing to extract unsafe ZIP entry: {member.filename}"
+ )
+
+ if member.is_dir():
+ target_path.mkdir(parents=True, exist_ok=True)
+ continue
+
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+ with zip_file.open(member, "r") as source, open(target_path, "wb") as handle:
+ handle.write(source.read())
+
+
+def resolve_submit_concurrency(max_concurrent_requests: int, task_count: int) -> int:
+ if max_concurrent_requests <= 0:
+ return max(1, task_count)
+ return max(1, min(max_concurrent_requests, task_count))
+
+
+async def execute_planned_tasks(
+ planned_tasks: list[PlannedTask],
+ concurrency: int,
+ task_runner: Callable[[PlannedTask], Awaitable[None]],
+) -> list[TaskFailure]:
+ queue: asyncio.Queue[PlannedTask | None] = asyncio.Queue()
+ failures: list[TaskFailure] = []
+
+ for task in planned_tasks:
+ await queue.put(task)
+ for _ in range(concurrency):
+ await queue.put(None)
+
+ async def worker() -> None:
+ while True:
+ planned_task = await queue.get()
+ try:
+ if planned_task is None:
+ return
+ await task_runner(planned_task)
+ except Exception as exc:
+ assert planned_task is not None
+ failures.append(
+ TaskFailure(
+ task_index=planned_task.index,
+ document_stems=tuple(doc.stem for doc in planned_task.documents),
+ message=str(exc),
+ )
+ )
+ finally:
+ queue.task_done()
+
+ workers = [asyncio.create_task(worker()) for _ in range(concurrency)]
+ await queue.join()
+ await asyncio.gather(*workers, return_exceptions=True)
+ return failures
+
+
+async def run_planned_task(
+ client: httpx.AsyncClient,
+ server_health: ServerHealth,
+ planned_task: PlannedTask,
+ form_data: dict[str, str],
+ output_dir: Path,
+) -> None:
+ logger.info(
+ f"Submitting {format_task_label(planned_task)} "
+ f"with {len(planned_task.documents)} document(s), {planned_task.total_pages} page(s)"
+ )
+ submit_response = await submit_task(
+ client=client,
+ base_url=server_health.base_url,
+ planned_task=planned_task,
+ form_data=form_data,
+ )
+ await wait_for_task_result(
+ client=client,
+ submit_response=submit_response,
+ planned_task=planned_task,
+ )
+ zip_path = await download_result_zip(
+ client=client,
+ submit_response=submit_response,
+ planned_task=planned_task,
+ )
+ try:
+ safe_extract_zip(zip_path, output_dir)
+ finally:
+ zip_path.unlink(missing_ok=True)
+
+
+async def run_orchestrated_cli(
+ input_path: Path,
+ output_dir: Path,
+ method: str,
+ backend: str,
+ lang: str,
+ server_url: Optional[str],
+ api_url: Optional[str],
+ start_page_id: int,
+ end_page_id: Optional[int],
+ formula_enable: bool,
+ table_enable: bool,
+) -> None:
+ if start_page_id < 0:
+ raise click.ClickException("--start must be greater than or equal to 0")
+ if end_page_id is not None and end_page_id < 0:
+ raise click.ClickException("--end must be greater than or equal to 0")
+
+ output_dir.mkdir(parents=True, exist_ok=True)
+ documents = collect_input_documents(
+ input_path=input_path,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ )
+
+ timeout = build_http_timeout()
+ local_server: LocalAPIServer | None = None
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as http_client:
+ try:
+ if api_url is None:
+ local_server = LocalAPIServer()
+ base_url = local_server.start()
+ logger.info(f"Started local mineru-api at {base_url}")
+ server_health = await wait_for_local_api_ready(http_client, local_server)
+ else:
+ server_health = await fetch_server_health(
+ http_client,
+ normalize_base_url(api_url),
+ )
+
+ planned_tasks = plan_tasks(
+ documents=documents,
+ backend=backend,
+ processing_window_size=server_health.processing_window_size
+ if backend == "pipeline"
+ else DEFAULT_PROCESSING_WINDOW_SIZE,
+ )
+ concurrency = resolve_submit_concurrency(
+ server_health.max_concurrent_requests,
+ len(planned_tasks),
+ )
+ form_data = build_request_form_data(
+ lang=lang,
+ backend=backend,
+ method=method,
+ formula_enable=formula_enable,
+ table_enable=table_enable,
+ server_url=server_url,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ )
+ failures = await execute_planned_tasks(
+ planned_tasks=planned_tasks,
+ concurrency=concurrency,
+ task_runner=lambda planned_task: run_planned_task(
+ client=http_client,
+ server_health=server_health,
+ planned_task=planned_task,
+ form_data=form_data,
+ output_dir=output_dir,
+ ),
+ )
+ if failures:
+ details = "\n".join(
+ f"- task#{failure.task_index} ({', '.join(failure.document_stems)}): {failure.message}"
+ for failure in sorted(failures, key=lambda item: item.task_index)
+ )
+ raise click.ClickException(
+ f"{len(failures)} task(s) failed while processing documents:\n{details}"
+ )
+ finally:
+ if local_server is not None:
+ preserve_logs = sys.exc_info()[0] is not None
+ local_server.stop(preserve_logs=preserve_logs)
+
+
[email protected]_option(__version__, "--version", "-v", help="display the version and exit")
@click.option(
- '-p',
- '--path',
- 'input_path',
- type=click.Path(exists=True),
+ "-p",
+ "--path",
+ "input_path",
+ type=click.Path(exists=True, path_type=Path),
required=True,
- help='local filepath or directory. support pdf, png, jpg, jpeg files',
+ help="local filepath or directory. support pdf, png, jpg, jpeg files",
)
@click.option(
- '-o',
- '--output',
- 'output_dir',
- type=click.Path(),
+ "-o",
+ "--output",
+ "output_dir",
+ type=click.Path(path_type=Path),
required=True,
- help='output local directory',
+ help="output local directory",
+)
+ "--api-url",
+ "api_url",
+ type=str,
+ default=None,
+ help="MinerU FastAPI base URL. If omitted, mineru starts a temporary local mineru-api service.",
)
@click.option(
- '-m',
- '--method',
- 'method',
- type=click.Choice(['auto', 'txt', 'ocr']),
+ "-m",
+ "--method",
+ "method",
+ type=click.Choice(["auto", "txt", "ocr"]),
+ default="auto",
help="""\b
the method for parsing pdf:
auto: Automatically determine the method based on the file type.
@@ -54,13 +798,21 @@ from .common import do_parse, read_fn, pdf_suffixes, image_suffixes, office_suff
ocr: Use OCR method for image-based PDFs.
Without method specified, 'auto' will be used by default.
Adapted only for the case where the backend is set to 'pipeline' and 'hybrid-*'.""",
- default='auto',
)
@click.option(
- '-b',
- '--backend',
- 'backend',
- type=click.Choice(['pipeline', 'vlm-http-client', 'hybrid-http-client', 'vlm-auto-engine', 'hybrid-auto-engine',]),
+ "-b",
+ "--backend",
+ "backend",
+ type=click.Choice(
+ [
+ "pipeline",
+ "vlm-http-client",
+ "hybrid-http-client",
+ "vlm-auto-engine",
+ "hybrid-auto-engine",
+ ]
+ ),
+ default="hybrid-auto-engine",
help="""\b
the backend for parsing pdf:
pipeline: More general.
@@ -69,159 +821,110 @@ from .common import do_parse, read_fn, pdf_suffixes, image_suffixes, office_suff
hybrid-auto-engine: Next-generation high accuracy solution via local computing power.
hybrid-http-client: High accuracy but requires a little local computing power(client suitable for openai-compatible servers).
Without method specified, hybrid-auto-engine will be used by default.""",
- default='hybrid-auto-engine',
)
@click.option(
- '-l',
- '--lang',
- 'lang',
- type=click.Choice(['ch', 'ch_server', 'ch_lite', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka', 'th', 'el',
- 'latin', 'arabic', 'east_slavic', 'cyrillic', 'devanagari']),
+ "-l",
+ "--lang",
+ "lang",
+ type=click.Choice(
+ [
+ "ch",
+ "ch_server",
+ "ch_lite",
+ "en",
+ "korean",
+ "japan",
+ "chinese_cht",
+ "ta",
+ "te",
+ "ka",
+ "th",
+ "el",
+ "latin",
+ "arabic",
+ "east_slavic",
+ "cyrillic",
+ "devanagari",
+ ]
+ ),
+ default="ch",
help="""
Input the languages in the pdf (if known) to improve OCR accuracy.
Without languages specified, 'ch' will be used by default.
Adapted only for the case where the backend is set to 'pipeline' and 'hybrid-*'.
""",
- default='ch',
)
@click.option(
- '-u',
- '--url',
- 'server_url',
+ "-u",
+ "--url",
+ "server_url",
type=str,
+ default=None,
help="""
When the backend is `<vlm/hybrid>-http-client`, you need to specify the server_url, for example:`http://127.0.0.1:30000`
""",
- default=None,
)
@click.option(
- '-s',
- '--start',
- 'start_page_id',
+ "-s",
+ "--start",
+ "start_page_id",
type=int,
- help='The starting page for PDF parsing, beginning from 0.',
default=0,
+ help="The starting page for PDF parsing, beginning from 0.",
)
@click.option(
- '-e',
- '--end',
- 'end_page_id',
+ "-e",
+ "--end",
+ "end_page_id",
type=int,
- help='The ending page for PDF parsing, beginning from 0.',
default=None,
+ help="The ending page for PDF parsing, beginning from 0.",
)
@click.option(
- '-f',
- '--formula',
- 'formula_enable',
+ "-f",
+ "--formula",
+ "formula_enable",
type=bool,
- help='Enable formula parsing. Default is True. ',
default=True,
+ help="Enable formula parsing. Default is True. ",
)
@click.option(
- '-t',
- '--table',
- 'table_enable',
+ "-t",
+ "--table",
+ "table_enable",
type=bool,
- help='Enable table parsing. Default is True. ',
default=True,
+ help="Enable table parsing. Default is True. ",
)
- '-d',
- '--device',
- 'device_mode',
- type=str,
- help="""Device mode for model inference, e.g., "cpu", "cuda", "cuda:0", "npu", "npu:0", "mps".
- Adapted only for the case where the backend is set to "pipeline". """,
- default=None,
-)
- '--vram',
- 'virtual_vram',
- type=int,
- help='Upper limit of GPU memory occupied by a single process. Adapted only for the case where the backend is set to "pipeline". ',
- default=None,
-)
- '--source',
- 'model_source',
- type=click.Choice(['huggingface', 'modelscope', 'local']),
- help="""
- The source of the model repository. Default is 'huggingface'.
- """,
- default='huggingface',
-)
-
-
def main(
- ctx,
- input_path, output_dir, method, backend, lang, server_url,
- start_page_id, end_page_id, formula_enable, table_enable,
- device_mode, virtual_vram, model_source, **kwargs
-):
-
- kwargs.update(arg_parse(ctx))
-
- if not backend.endswith('-client'):
- def get_device_mode() -> str:
- if device_mode is not None:
- return device_mode
- else:
- return get_device()
- if os.getenv('MINERU_DEVICE_MODE', None) is None:
- os.environ['MINERU_DEVICE_MODE'] = get_device_mode()
-
- def get_virtual_vram_size() -> int:
- if virtual_vram is not None:
- return virtual_vram
- else:
- return get_vram(get_device_mode())
- if os.getenv('MINERU_VIRTUAL_VRAM_SIZE', None) is None:
- os.environ['MINERU_VIRTUAL_VRAM_SIZE']= str(get_virtual_vram_size())
-
- if os.getenv('MINERU_MODEL_SOURCE', None) is None:
- os.environ['MINERU_MODEL_SOURCE'] = model_source
+ input_path: Path,
+ output_dir: Path,
+ api_url: Optional[str],
+ method: str,
+ backend: str,
+ lang: str,
+ server_url: Optional[str],
+ start_page_id: int,
+ end_page_id: Optional[int],
+ formula_enable: bool,
+ table_enable: bool,
+) -> None:
+ asyncio.run(
+ run_orchestrated_cli(
+ input_path=input_path,
+ output_dir=output_dir,
+ method=method,
+ backend=backend,
+ lang=lang,
+ server_url=server_url,
+ api_url=api_url,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ formula_enable=formula_enable,
+ table_enable=table_enable,
+ )
+ )
- os.makedirs(output_dir, exist_ok=True)
-
- def parse_doc(path_list: list[tuple[Path, str | None]]):
- try:
- file_name_list = []
- pdf_bytes_list = []
- lang_list = []
- for path, known_suffix in tqdm(path_list, total=len(path_list), desc='Reading documents'):
- file_name = str(Path(path).stem)
- pdf_bytes = read_fn(path, file_suffix=known_suffix)
- file_name_list.append(file_name)
- pdf_bytes_list.append(pdf_bytes)
- lang_list.append(lang)
- do_parse(
- output_dir=output_dir,
- pdf_file_names=file_name_list,
- pdf_bytes_list=pdf_bytes_list,
- p_lang_list=lang_list,
- backend=backend,
- parse_method=method,
- formula_enable=formula_enable,
- table_enable=table_enable,
- server_url=server_url,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- **kwargs,
- )
- except Exception as e:
- logger.exception(e)
-
- if os.path.isdir(input_path):
- doc_path_list = []
- doc_candidates = list(Path(input_path).glob('*'))
- for doc_path in tqdm(doc_candidates, total=len(doc_candidates), desc='Collecting documents'):
- file_suffix = guess_suffix_by_path(doc_path)
- if file_suffix in pdf_suffixes + image_suffixes + office_suffixes:
- doc_path_list.append((doc_path, file_suffix))
- parse_doc(doc_path_list)
- else:
- parse_doc([(Path(input_path), None)])
-if __name__ == '__main__':
+if __name__ == "__main__":
main()
diff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.py
index b3919f86..afb2d7dd 100644
--- a/mineru/cli/fast_api.py
+++ b/mineru/cli/fast_api.py
@@ -40,8 +40,12 @@ from mineru.cli.common import (
pdf_suffixes,
read_fn,
)
+from mineru.cli.api_protocol import (
+ API_PROTOCOL_VERSION,
+ DEFAULT_PROCESSING_WINDOW_SIZE,
+)
from mineru.utils.cli_parser import arg_parse
-from mineru.utils.config_reader import get_device
+from mineru.utils.config_reader import get_device, get_processing_window_size
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
from mineru.version import __version__
@@ -87,6 +91,7 @@ class ParseRequestOptions:
return_content_list: bool
return_images: bool
response_format_zip: bool
+ return_original_file: bool
start_page_id: int
end_page_id: int
@@ -117,6 +122,7 @@ class AsyncParseTask:
return_content_list: bool
return_images: bool
response_format_zip: bool
+ return_original_file: bool
start_page_id: int
end_page_id: int
uploads: list[str]
@@ -389,6 +395,14 @@ def build_result_dict(
return result_dict
+def build_zip_arcname(
+ pdf_name: str,
+ parse_dir: str,
+ relative_path: str,
+) -> str:
+ return os.path.join(pdf_name, os.path.basename(parse_dir), relative_path)
+
+
def create_result_zip(
output_dir: str,
pdf_file_names: list[str],
@@ -399,14 +413,13 @@ def create_result_zip(
return_model_output: bool,
return_content_list: bool,
return_images: bool,
+ return_original_file: bool,
) -> str:
zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_results_")
os.close(zip_fd)
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for pdf_name in pdf_file_names:
- safe_pdf_name = sanitize_filename(pdf_name)
-
try:
parse_dir = get_parse_dir(output_dir, pdf_name, backend, parse_method)
except ValueError:
@@ -421,7 +434,11 @@ def create_result_zip(
if os.path.exists(path):
zf.write(
path,
- arcname=os.path.join(safe_pdf_name, f"{safe_pdf_name}.md"),
+ arcname=build_zip_arcname(
+ pdf_name,
+ parse_dir,
+ f"{pdf_name}.md",
+ ),
)
if return_middle_json:
@@ -429,8 +446,10 @@ def create_result_zip(
if os.path.exists(path):
zf.write(
path,
- arcname=os.path.join(
- safe_pdf_name, f"{safe_pdf_name}_middle.json"
+ arcname=build_zip_arcname(
+ pdf_name,
+ parse_dir,
+ f"{pdf_name}_middle.json",
),
)
@@ -439,8 +458,10 @@ def create_result_zip(
if os.path.exists(path):
zf.write(
path,
- arcname=os.path.join(
- safe_pdf_name, f"{safe_pdf_name}_model.json"
+ arcname=build_zip_arcname(
+ pdf_name,
+ parse_dir,
+ f"{pdf_name}_model.json",
),
)
@@ -449,8 +470,21 @@ def create_result_zip(
if os.path.exists(path):
zf.write(
path,
- arcname=os.path.join(
- safe_pdf_name, f"{safe_pdf_name}_content_list.json"
+ arcname=build_zip_arcname(
+ pdf_name,
+ parse_dir,
+ f"{pdf_name}_content_list.json",
+ ),
+ )
+
+ path = os.path.join(parse_dir, f"{pdf_name}_content_list_v2.json")
+ if os.path.exists(path):
+ zf.write(
+ path,
+ arcname=build_zip_arcname(
+ pdf_name,
+ parse_dir,
+ f"{pdf_name}_content_list_v2.json",
),
)
@@ -460,8 +494,26 @@ def create_result_zip(
for image_path in image_paths:
zf.write(
image_path,
- arcname=os.path.join(
- safe_pdf_name, "images", os.path.basename(image_path)
+ arcname=build_zip_arcname(
+ pdf_name,
+ parse_dir,
+ os.path.join("images", os.path.basename(image_path)),
+ ),
+ )
+
+ if return_original_file:
+ origin_pattern = f"{pdf_name}_origin."
+ for path in sorted(Path(parse_dir).iterdir()):
+ if not path.is_file():
+ continue
+ if not path.name.startswith(origin_pattern):
+ continue
+ zf.write(
+ str(path),
+ arcname=build_zip_arcname(
+ pdf_name,
+ parse_dir,
+ path.name,
),
)
return zip_path
@@ -480,6 +532,7 @@ def build_result_response(
return_content_list: bool,
return_images: bool,
response_format_zip: bool,
+ return_original_file: bool,
) -> Response:
if response_format_zip:
zip_path = create_result_zip(
@@ -492,6 +545,7 @@ def build_result_response(
return_model_output=return_model_output,
return_content_list=return_content_list,
return_images=return_images,
+ return_original_file=return_original_file,
)
background_tasks.add_task(cleanup_file, zip_path)
return FileResponse(
@@ -548,6 +602,7 @@ def build_sync_file_parse_response(
return_content_list=task.return_content_list,
return_images=task.return_images,
response_format_zip=task.response_format_zip,
+ return_original_file=task.return_original_file,
)
response.headers[FILE_PARSE_TASK_ID_HEADER] = task.task_id
response.headers[FILE_PARSE_TASK_STATUS_HEADER] = task.status
@@ -642,6 +697,13 @@ async def parse_request_form(
response_format_zip: bool = Form(
False, description="Return results as a ZIP file instead of JSON"
),
+ return_original_file: bool = Form(
+ False,
+ description=(
+ "Include the processed original input file in the ZIP result; "
+ "ignored unless response_format_zip=true"
+ ),
+ ),
start_page_id: int = Form(
0, description="The starting page for PDF parsing, beginning from 0"
),
@@ -649,6 +711,7 @@ async def parse_request_form(
99999, description="The ending page for PDF parsing, beginning from 0"
),
) -> ParseRequestOptions:
+ effective_return_original_file = return_original_file and response_format_zip
return ParseRequestOptions(
files=files,
lang_list=lang_list,
@@ -663,6 +726,7 @@ async def parse_request_form(
return_content_list=return_content_list,
return_images=return_images,
response_format_zip=response_format_zip,
+ return_original_file=effective_return_original_file,
start_page_id=start_page_id,
end_page_id=end_page_id,
)
@@ -746,7 +810,9 @@ async def run_parse_job(
f_dump_md=request_options.return_md,
f_dump_middle_json=request_options.return_middle_json,
f_dump_model_output=request_options.return_model_output,
- f_dump_orig_pdf=False,
+ f_dump_orig_pdf=(
+ request_options.return_original_file and request_options.response_format_zip
+ ),
f_dump_content_list=request_options.return_content_list,
start_page_id=request_options.start_page_id,
end_page_id=request_options.end_page_id,
@@ -817,6 +883,7 @@ async def create_async_parse_task(
return_content_list=request_options.return_content_list,
return_images=request_options.return_images,
response_format_zip=request_options.response_format_zip,
+ return_original_file=request_options.return_original_file,
start_page_id=request_options.start_page_id,
end_page_id=request_options.end_page_id,
uploads=[upload.path for upload in uploads],
@@ -1213,6 +1280,7 @@ async def get_async_task_result(
return_content_list=task.return_content_list,
return_images=task.return_images,
response_format_zip=task.response_format_zip,
+ return_original_file=task.return_original_file,
)
@@ -1245,11 +1313,15 @@ async def health_check():
return {
"status": "healthy",
"version": __version__,
+ "protocol_version": API_PROTOCOL_VERSION,
"queued_tasks": stats[TASK_PENDING],
"processing_tasks": stats[TASK_PROCESSING],
"completed_tasks": stats[TASK_COMPLETED],
"failed_tasks": stats[TASK_FAILED],
"max_concurrent_requests": get_max_concurrent_requests(),
+ "processing_window_size": get_processing_window_size(
+ default=DEFAULT_PROCESSING_WINDOW_SIZE
+ ),
"task_retention_seconds": task_manager.task_retention_seconds,
"task_cleanup_interval_seconds": task_manager.task_cleanup_interval_seconds,
}