Skip to content

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

feat: refactor mineru-kit structure and introduce gradio command

myhlolida5c6e01fe4c
diff --git a/demo/demo.py b/demo/demo.py
index 3cb1de22..906a63cd 100644
--- a/demo/demo.py
+++ b/demo/demo.py
@@ -1,26 +1,25 @@
# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
import asyncio
-import os
-import tempfile
from pathlib import Path
-import httpx
-
-from mineru.cli_old import api_client as _api_client
-from mineru.cli_old.common import image_suffixes, office_suffixes, pdf_suffixes
+from mineru.filetypes import PAGE_RANGE_PARSE_EXTENSIONS, PARSEABLE_EXTENSIONS, batch_effective_parse_tier
+from mineru.parser.api_client import MinerUApiParser
from mineru.parser.file_type import guess_suffix_by_path
-
-SUPPORTED_INPUT_SUFFIXES = set(pdf_suffixes + image_suffixes + office_suffixes)
+from mineru.parser.writer import FileBasedDataWriter
+from mineru.types import Tier
def collect_input_files(input_path: str | Path) -> list[Path]:
+ """收集单个输入文件或目录中的当前 V1 API 支持文件。"""
path = Path(input_path).expanduser().resolve()
if not path.exists():
raise FileNotFoundError(f"Input path does not exist: {path}")
if path.is_file():
file_suffix = guess_suffix_by_path(path)
- if file_suffix not in SUPPORTED_INPUT_SUFFIXES:
+ if file_suffix not in PARSEABLE_EXTENSIONS:
raise ValueError(f"Unsupported input file type: {path.name}")
return [path]
@@ -31,8 +30,7 @@ def collect_input_files(input_path: str | Path) -> list[Path]:
(
candidate.resolve()
for candidate in path.iterdir()
- if candidate.is_file()
- and guess_suffix_by_path(candidate) in SUPPORTED_INPUT_SUFFIXES
+ if candidate.is_file() and guess_suffix_by_path(candidate) in PARSEABLE_EXTENSIONS
),
key=lambda item: item.name,
)
@@ -41,225 +39,62 @@ def collect_input_files(input_path: str | Path) -> list[Path]:
return input_files
-def build_form_data(
- language: str,
- backend: str,
- parse_method: str,
- formula_enable: bool,
- table_enable: bool,
- server_url: str | None,
- start_page_id: int,
- end_page_id: int | None,
- image_analysis: bool = True,
- effort: str = "medium",
-) -> dict[str, str | list[str]]:
- return _api_client.build_parse_request_form_data(
- lang_list=[language],
- backend=backend,
- effort=effort,
- parse_method=parse_method,
- formula_enable=formula_enable,
- table_enable=table_enable,
- image_analysis=image_analysis,
- server_url=server_url,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- return_md=True,
- return_middle_json=False,
- return_model_output=False,
- return_content_list=False,
- return_images=True,
- response_format_zip=True,
- return_original_file=False,
- )
-
-
-def format_status_message(status_snapshot: _api_client.TaskStatusSnapshot) -> str:
- if status_snapshot.queued_ahead is None:
- return status_snapshot.status
- return f"{status_snapshot.status} (queued_ahead={status_snapshot.queued_ahead})"
-
-
-def prepare_local_api_temp_dir() -> None:
- current_temp_dir = Path(tempfile.gettempdir())
- if os.name == "nt" or not Path("/tmp").exists():
- return
- if not str(current_temp_dir).startswith("/mnt/"):
- return
-
- # vLLM/ZeroMQ IPC sockets fail on drvfs-backed temp directories under WSL.
- os.environ["TMPDIR"] = "/tmp"
- tempfile.tempdir = None
-
-
async def run_demo(
input_path: str | Path,
output_dir: str | Path,
*,
- api_url: str | None = None,
- backend: str = "hybrid-engine",
- parse_method: str = "auto",
- language: str = "ch",
- formula_enable: bool = True,
- table_enable: bool = True,
- image_analysis: bool = True,
- effort: str = "medium",
- server_url: str | None = None,
- start_page_id: int = 0,
- end_page_id: int | None = None,
+ api_url: str,
+ api_key: str | None = None,
+ tier: Tier = "standard",
+ page_range: str = "",
) -> None:
- api_url = api_url or None
- server_url = server_url or None
- if backend.endswith("http-client") and not server_url:
- raise ValueError(f"backend={backend} requires server_url")
-
+ """通过公开 V1 API 异步解析文件并保存标准 ParseResult 产物。"""
input_files = collect_input_files(input_path)
- output_path = Path(output_dir).expanduser().resolve()
- output_path.mkdir(parents=True, exist_ok=True)
+ output_root = Path(output_dir).expanduser().resolve()
- form_data = build_form_data(
- language=language,
- backend=backend,
- parse_method=parse_method,
- formula_enable=formula_enable,
- table_enable=table_enable,
- image_analysis=image_analysis,
- effort=effort,
- server_url=server_url,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- )
- upload_assets = [
- _api_client.UploadAsset(path=file_path, upload_name=file_path.name)
- for file_path in input_files
- ]
-
- local_server: _api_client.LocalAPIServer | None = None
- result_zip_path: Path | None = None
- task_label = f"{len(input_files)} file(s)"
-
- async with httpx.AsyncClient(
- timeout=_api_client.build_http_timeout(),
- follow_redirects=True,
- ) as http_client:
- try:
- if api_url is None:
- prepare_local_api_temp_dir()
- local_server = _api_client.LocalAPIServer()
- base_url = local_server.start()
- print(f"Started local mineru-api: {base_url}")
- server_health = await _api_client.wait_for_local_api_ready(
- http_client,
- local_server,
- )
- else:
- server_health = await _api_client.fetch_server_health(
- http_client,
- _api_client.normalize_base_url(api_url),
- )
-
- print(f"Using API: {server_health.base_url}")
- print(f"Submitting {len(upload_assets)} file(s)")
- submit_response = await _api_client.submit_parse_task(
- base_url=server_health.base_url,
- upload_assets=upload_assets,
- form_data=form_data,
- )
- print(f"task_id: {submit_response.task_id}")
- if submit_response.queued_ahead is not None:
- print(f"status: pending (queued_ahead={submit_response.queued_ahead})")
-
- last_status_message = None
-
- def on_status_update(status_snapshot: _api_client.TaskStatusSnapshot) -> None:
- nonlocal last_status_message
- message = format_status_message(status_snapshot)
- if message == last_status_message:
- return
- last_status_message = message
- print(f"status: {message}")
-
- await _api_client.wait_for_task_result(
- client=http_client,
- submit_response=submit_response,
- task_label=task_label,
- status_snapshot_callback=on_status_update,
- )
- print("status: completed")
- result_zip_path = await _api_client.download_result_zip(
- client=http_client,
- submit_response=submit_response,
- task_label=task_label,
- )
- finally:
- if local_server is not None:
- local_server.stop()
-
- assert result_zip_path is not None
- try:
- _api_client.safe_extract_zip(result_zip_path, output_path)
- finally:
- result_zip_path.unlink(missing_ok=True)
- print(f"Extracted result to: {output_path}")
+ for input_file in input_files:
+ file_suffix = guess_suffix_by_path(input_file)
+ effective_page_range = page_range if file_suffix in PAGE_RANGE_PARSE_EXTENSIONS else ""
+ effective_tier = batch_effective_parse_tier(tier, input_file)
+ parser = MinerUApiParser(
+ api_url=api_url,
+ api_key=api_key,
+ tier=effective_tier,
+ include_images=True,
+ include_model_output=True,
+ )
+ print(f"Parsing {input_file.name} with tier={effective_tier}")
+ result = await parser.parse_async(input_file, page_range=effective_page_range)
+
+ document_output = output_root / input_file.stem
+ result.save(FileBasedDataWriter(str(document_output)))
+ result.middle_json.export(
+ document_output,
+ json_name="middle_json_without_base64.json",
+ overwrite=True,
+ )
+ print(f"Saved result to: {document_output}")
def main() -> None:
+ """运行仓库内置的 V1 API 异步解析示例。"""
demo_dir = Path(__file__).resolve().parent
- # Input can be a single supported file or a directory containing supported files.
+ # 先运行 `mineru-kit api-server --host 127.0.0.1 --port 8000`。
+ api_url = "http://127.0.0.1:8000"
+ # 可改为单个文件;目录模式只读取当前层的支持格式文件。
input_path = demo_dir / "pdfs"
- # Parsed outputs will be extracted into this directory.
output_dir = demo_dir / "api_output"
- # Set this to an existing MinerU FastAPI base URL, for example:
- # "http://127.0.0.1:8000"
- # Leave it as None to start a temporary local mineru-api automatically.
- api_url = None
-
- # Available examples:
- # "hybrid-engine" -> local hybrid parsing, recommended default
- # "pipeline" -> more general OCR/text pipeline
- # "hybrid-http-client" -> remote OpenAI-compatible hybrid server
- backend = "hybrid-engine"
- # Hybrid parsing effort. "medium" is faster; "high" keeps the high-effort hybrid behavior.
- effort = "medium"
- # Available options:
- # "auto" -> let MinerU choose between text extraction and OCR
- # "txt" -> force text extraction
- # "ocr" -> force OCR
- parse_method = "auto"
- # Pipeline OCR language hint; hybrid backends ignore this value.
- language = "ch"
- # Enable formula parsing in the output.
- formula_enable = True
- # Enable table parsing in the output.
- table_enable = True
- # Enable image/chart analysis for hybrid backends.
- image_analysis = True
- # Required only for "*-http-client" backends, for example:
- # "http://127.0.0.1:30000"
- server_url = None
- # Zero-based page range. Set end_page_id to None to parse to the last page.
- start_page_id = 0
- end_page_id = None
-
- """如果您由于网络问题无法下载模型,可以设置环境变量MINERU_MODEL_SOURCE为modelscope使用免代理仓库下载模型"""
- # os.environ['MINERU_MODEL_SOURCE'] = "modelscope"
+ # V1 页码范围从 1 开始,仅对 PDF 生效;空字符串表示整份文档。
+ page_range = ""
asyncio.run(
run_demo(
input_path=input_path,
output_dir=output_dir,
api_url=api_url,
- backend=backend,
- effort=effort,
- parse_method=parse_method,
- language=language,
- formula_enable=formula_enable,
- table_enable=table_enable,
- image_analysis=image_analysis,
- server_url=server_url,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
+ tier="standard",
+ page_range=page_range,
)
)
diff --git a/docker/compose.yaml b/docker/compose.yaml
index 42b72a3b..fe39b38f 100644
--- a/docker/compose.yaml
+++ b/docker/compose.yaml
@@ -110,14 +110,15 @@ services:
- 7860:7860
environment:
MINERU_MODEL_SOURCE: local
- entrypoint: mineru-gradio
+ entrypoint: ["mineru-kit"]
command:
- --server-name 0.0.0.0
- --server-port 7860
- # --enable-api false # If you want to disable the API, set this to false
- # --max-convert-pages 20 # If you want to limit the number of pages for conversion, set this to a specific number
- # parameters for vllm-engine
- # --gpu-memory-utilization 0.5 # If encountering VRAM shortage, reduce the KV cache size by this parameter; if VRAM issues persist, try lowering it further to `0.4` or below.
+ - gradio
+ - --server-name
+ - 0.0.0.0
+ - --server-port
+ - "7860"
+ # --no-enable-api # Disable the Gradio event API.
+ # --api-server-tier standard # Configure the managed V1 API server capability tier.
ulimits:
memlock: -1
stack: 67108864
diff --git a/docs/en/usage/advanced_cli_parameters.md b/docs/en/usage/advanced_cli_parameters.md
index 5211e10c..0c3d6a60 100644
--- a/docs/en/usage/advanced_cli_parameters.md
+++ b/docs/en/usage/advanced_cli_parameters.md
@@ -37,20 +37,20 @@
> - If you have multiple GPUs and need to start two `openai-server` services on GPU 0 and GPU 1, each listening on a different port, you can use the following commands:
> ```bash
> # In terminal 1
-> CUDA_VISIBLE_DEVICES=0 mineru-openai-server --engine vllm --port 30000
+> CUDA_VISIBLE_DEVICES=0 mineru-kit vlm-server --engine vllm --port 30000
> # In terminal 2
-> CUDA_VISIBLE_DEVICES=1 mineru-openai-server --engine vllm --port 30001
+> CUDA_VISIBLE_DEVICES=1 mineru-kit vlm-server --engine vllm --port 30001
> ```
>
> - If you have multiple GPUs and need to start two `fastapi` services on GPU 0 and GPU 1, each listening on a different port, you can use the following commands:
> ```bash
> # In terminal 1
-> CUDA_VISIBLE_DEVICES=0 mineru-api --host 127.0.0.1 --port 8000
+> CUDA_VISIBLE_DEVICES=0 mineru-kit api-server --host 127.0.0.1 --port 8000
> # In terminal 2
-> CUDA_VISIBLE_DEVICES=1 mineru-api --host 127.0.0.1 --port 8001
+> CUDA_VISIBLE_DEVICES=1 mineru-kit api-server --host 127.0.0.1 --port 8001
> ```
>
> - If you have multiple GPUs and want to use `router` to launch and manage `fastapi` services across four GPUs, you can use the following command:
> ```bash
-> CUDA_VISIBLE_DEVICES=0,1,2,3 mineru-router --host 127.0.0.1 --port 8002
+> CUDA_VISIBLE_DEVICES=0,1,2,3 mineru-kit router --host 127.0.0.1 --port 8002
> ```
diff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.md
index 9e705e77..39af2a9a 100644
--- a/docs/en/usage/cli_tools.md
+++ b/docs/en/usage/cli_tools.md
@@ -1,191 +1,75 @@
-# Command Line Tools Usage Instructions
+# Command Line Tools
+
+MinerU exposes two primary command trees. `mineru` is the document-library client for interactive and agent workflows; `mineru-kit` contains stateless parsing, service, model, router, and WebUI tools.
+
+## Document-library CLI
+
+Use `mineru --help` to list all document-library commands. The most common parsing flow is:
+
+```bash
+mineru parse report.pdf --pages all -o report.md
+```
+
+When `-o/--output` is omitted, rendered content is written to stdout. PDF input defaults to the first 10 pages; pass `--pages all` for the complete document. The document library manages ingestion, caching, background parsing, reading, search, and cleanup.
+
+Manage the local document-library service with:
+
+```bash
+mineru server start
+mineru server status
+mineru server stop
+```
+
+Run `mineru <command> --help` for the authoritative options of each command.
+
+## Stateless and service tools
+
+Use `mineru-kit --help` to list the available tools.
+
+### Batch parsing
-## View Help Information
-To view help information for MinerU command line tools, you can use the `--help` parameter. Here are help information examples for various command line tools:
```bash
-mineru --help
-Usage: mineru [OPTIONS]
-
-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 (hybrid* backend only)
- -b, --backend [hybrid-engine|hybrid-http-client]
- Parsing backend (default: hybrid-engine)
- --effort [medium|high|xhigh] Hybrid parsing effort (default: high)
- -l, --lang [ch|ch_server|korean|ta|te|ka|th|el|arabic|east_slavic|cyrillic|devanagari]
- Specify document language (improves OCR accuracy, hybrid* backend only)
- -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)
- --image-analysis BOOLEAN Enable image/chart analysis for hybrid
- backend. Hybrid medium and high efforts
- automatically disable image/chart analysis
- (default: enabled)
- --client-side-output-generation BOOLEAN
- Generate Markdown and content lists locally
- from server-returned middle JSON, images, and
- original files (default: disabled)
- --help Show help information
+mineru-kit parse report.pdf -o report.md --tier standard
+mineru-kit parse ./documents -o ./output --format zip
```
-> [!TIP]
-> `mineru` currently supports local `PDF`, `OFD`, `EPUB`, static `HTML`, image, `CSV`, `RTF`, `DOC`/`DOCX`, `PPT`/`PPTX`, `XLS`/`XLSX`, `ODT`/`ODS`/`ODP` file or directory inputs. Only PDF accepts page ranges; every non-PDF input is parsed and cached as one complete file, while format-native boundaries remain logical pages in structured output. EPUB pages follow OPF spine order and preserve resolvable authored internal links.
+
+`mineru-kit parse` does not use the document-library database or cache. It supports local parsing and explicit V1 remote parsing; see `mineru-kit parse --help` for tier, backend, page-range, and output options.
+
+### V1 API server
```bash
-mineru-api --help
-Usage: mineru-api [OPTIONS]
-
-Options:
- --host TEXT Server host (default: 127.0.0.1)
- --port INTEGER Server port (default: 8000)
- --reload Enable auto-reload (development mode)
- --enable-vlm-preload BOOLEAN
- Preload the local VLM model during mineru-api startup.
- --help Show this message and exit.
+mineru-kit api-server --host 127.0.0.1 --port 8000 --tier standard
```
+
+Open `http://127.0.0.1:8000/docs` for the generated OpenAPI documentation. The supported API is `/v1/*`; the removed legacy `/file_parse` and `/tasks` routes are not available.
+
+### Gradio WebUI
+
```bash
-mineru-gradio --help
-Usage: mineru-gradio [OPTIONS]
-
-Options:
- --enable-example BOOLEAN Enable example files for input. The example
- files to be input need to be placed in the
- `examples` folder within the directory where
- the command is currently executed.
- --enable-http-client BOOLEAN Enable http-client backend to link openai-
- compatible servers.
- --enable-api BOOLEAN Enable gradio API for serving the
- application.
- --max-convert-pages INTEGER Set the maximum number of pages to convert
- from PDF to Markdown.
- --server-name TEXT Set the server name for the Gradio app.
- --server-port INTEGER Set the server port for the Gradio app.
- --api-url TEXT MinerU FastAPI base URL. If omitted, gradio
- starts a reusable local mineru-api service.
- --enable-vlm-preload BOOLEAN Preload the local VLM model when gradio
- starts a local mineru-api service.
- --client-side-output-generation BOOLEAN
- Generate Markdown and content lists locally
- from server-returned middle JSON.
- --latex-delimiters-type [a|b|all]
- Set the type of LaTeX delimiters to use in
- Markdown rendering: 'a' for type '$', 'b' for
- type '()[]', 'all' for both types.
- --help Show this message and exit.
+mineru-kit gradio --server-name 127.0.0.1 --server-port 7860
```
+
+Without `--api-url`, Gradio manages a loopback `mineru-kit api-server`. With `--api-url`, it connects only to that V1 service. `mineru-gradio` is retained as a command-name alias and accepts the same modern options; it does not restore legacy Gradio options or HTTP routes.
+
+### Router and VLM server
+
```bash
-mineru-router --help
-Usage: mineru-router [OPTIONS]
-
-Options:
- --host TEXT Server host (default: 127.0.0.1)
- --port INTEGER Server port (default: 8002)
- --reload Enable auto-reload (development mode)
- --upstream-url TEXT Existing MinerU FastAPI base URL; repeat to add more
- --local-gpus TEXT Local GPU workers to launch: auto, none, or CSV such
- as 0,1,2
- --worker-host TEXT Host for router-managed workers (default: 127.0.0.1)
- --worker-tier TEXT Managed worker tier: flash, basic, standard
- --worker-concurrency INTEGER
- Concurrency per managed worker
- --preload-models Preload models in managed workers
- --help Show this message and exit.
+mineru-kit router --host 127.0.0.1 --port 8002 --local-gpus auto
+mineru-kit vlm-server --engine auto --port 30000
```
-`mineru-router` is a transition alias of `mineru-kit router`. Both commands expose only the MinerU V1 API and do not forward unknown worker arguments.
-
-## 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_TOOLS_CONFIG_JSON`:
- * Used to specify configuration file path
- * defaults to `mineru.json` in user directory, can specify other configuration file paths through environment variables.
-
-- `MINERU_FORMULA_CH_SUPPORT`:
- * Used to enable Chinese formula parsing optimization (experimental feature)
- * Default is `false`, can be set to `true` via environment variable to enable Chinese formula parsing optimization.
- * Only effective for local Hybrid model execution.
-
-- `MINERU_PDF_RENDER_TIMEOUT`:
- * Used to set the timeout (in seconds) for rendering PDFs to images.
- * Default is `300` seconds; you can set a different value via an environment variable to adjust the rendering timeout.
- * Effective on Linux, macOS, and Windows.
-
-- `MINERU_PDF_RENDER_THREADS`:
- * Used to set the render worker concurrency used when rendering PDFs to images.
- * Default is `4`; you can set a different value via an environment variable to adjust render worker concurrency.
- * Effective on Linux, macOS, and Windows.
-
-- `MINERU_PROCESSING_WINDOW_SIZE`:
- * Used to control the processing window size, which affects memory use and throughput on large-document workloads.
- * Default is `64`; set it to another positive integer when needed.
-
-- `MINERU_API_MAX_CONCURRENT_REQUESTS`:
- * Used to control the maximum concurrent requests handled by `mineru-api` or router-managed workers.
- * Default is `3`, and it must be a positive integer.
-
-- `MINERU_API_ENABLE_FASTAPI_DOCS`:
- * Used to control whether FastAPI documentation endpoints such as `/docs`, `/openapi.json`, and `/redoc` are enabled.
- * Default is `true`.
-
-- `MINERU_API_OUTPUT_ROOT`:
- * Used to configure the root output directory for `mineru-api`.
- * Default is `./output` under the current working directory.
-
-- `MINERU_LOCAL_API_STARTUP_TIMEOUT_SECONDS`:
- * Used to control how long CLI tools wait for a locally started `mineru-api` to become healthy.
- * Default is `300` seconds.
- * Applies to temporary local API startup in `mineru`, preload startup in `mineru-gradio`, and router-managed local workers.
-
-- `MINERU_TASK_RESULT_TIMEOUT_SECONDS`:
- * Used to control how long clients wait for a task to complete and reach a terminal state.
- * Default is `3600` seconds, and the value must be greater than or equal to `1`.
- * Applies to task-status polling in `mineru`, `mineru-gradio`, `mineru-router`, and other API-client scenarios.
-
-- `MINERU_TASK_RESULT_DOWNLOAD_TIMEOUT_SECONDS`:
- * Used to control the read timeout when retrieving completed task results, including waiting for server-side ZIP generation and downloading the result ZIP.
- * Default is `600` seconds, and the value must be greater than or equal to `1`.
- * This is not a hard limit for total download duration; if the server keeps returning data, the total download time may exceed this value.
-
-- `MINERU_API_TASK_RETENTION_SECONDS`:
- * Used to set how long completed or failed tasks are retained, in seconds.
- * Default is `86400` seconds (24 hours).
-
-- `MINERU_API_TASK_CLEANUP_INTERVAL_SECONDS`:
- * Used to set the cleanup polling interval for expired tasks, in seconds.
- * Default is `300` seconds (5 minutes).
-
-- `MINERU_INTRA_OP_NUM_THREADS`:
- * Used to set the intra_op thread count for ONNX models, affects the computation speed of individual operators
- * Default is `-1` (auto-select), can be set to other values via environment variable to adjust the thread count.
-
-- `MINERU_INTER_OP_NUM_THREADS`:
- * Used to set the inter_op thread count for ONNX models, affects the parallel execution of multiple operators
- * Default is `-1` (auto-select), can be set to other values via environment variable to adjust the thread count.
-
-- `MINERU_HYBRID_BATCH_RATIO`:
- * Used to set the batch ratio for small model processing in `hybrid-*` backends.
- * Commonly used in `hybrid-http-client`, it allows adjusting the VRAM usage of a single client by controlling the batch ratio of small models.
- * Single Client VRAM Size | MINERU_HYBRID_BATCH_RATIO
- ------------------------|--------------------------
- <= 6 GB | 8
- <= 4 GB | 4
- <= 3 GB | 2
- <= 2 GB | 1
-
-- `MINERU_VL_MODEL_NAME`:
- * Used to specify the model name for the vlm/hybrid backend, allowing you to designate the model required for MinerU to run when multiple models exist on a remote openai-server.
-
-- `MINERU_VL_API_KEY`:
- * Used to specify the API Key for the vlm/hybrid backend, enabling authentication on the remote openai-server.
+`mineru-router` remains a command-name alias for `mineru-kit router`. Router exposes only the V1 API and accepts only its documented worker options.
+
+## Environment variables
+
+- `MINERU_HOME`: root for MinerU configuration, cache, and document-library state.
+- `MINERU_CONFIG`: explicit `config.yaml` path.
+- `MINERU_MODEL_SOURCE`: model source, such as `huggingface`, `modelscope`, or `local`.
+- `MINERU_API_URL` / `MINERU_API_KEY`: default V1 API URL and bearer key for API clients.
+- `MINERU_LOCAL_API_STARTUP_TIMEOUT_SECONDS`: startup timeout for the Gradio-managed local V1 server; default `300` seconds.
+- `MINERU_API_ENABLE_FASTAPI_DOCS`: enable `/docs`, `/openapi.json`, and `/redoc` on the V1 API server; default `true`.
+- `MINERU_PDF_RENDER_TIMEOUT` / `MINERU_PDF_RENDER_THREADS`: PDF rendering timeout and worker count.
+- `MINERU_PROCESSING_WINDOW_SIZE`: processing window size used for large documents.
+- `MINERU_INTRA_OP_NUM_THREADS` / `MINERU_INTER_OP_NUM_THREADS`: ONNX operator thread settings.
+
+Prefer each command's `--help` output and [model source documentation](./model_source.md) for current defaults.
diff --git a/docs/en/usage/index.md b/docs/en/usage/index.md
index c79cef60..526e6977 100644
--- a/docs/en/usage/index.md
+++ b/docs/en/usage/index.md
@@ -11,7 +11,7 @@ This section provides comprehensive usage instructions for the project. We will
## Getting Started
-Starting with 3.0, `mineru` runs as an orchestration client on top of `mineru-api`; advanced `mineru-router` usage for multi-service and multi-GPU deployments is also covered in this section.
+`mineru` is the document-library CLI for interactive and agent workflows. Use `mineru-kit` for stateless batch parsing, the V1 API server, Gradio, model management, and multi-service routing.
We recommend reading the documentation in the order listed above, which will help you better understand and use the project features.
diff --git a/docs/en/usage/quick_usage.md b/docs/en/usage/quick_usage.md
index b6b215bf..c7375be3 100644
--- a/docs/en/usage/quick_usage.md
+++ b/docs/en/usage/quick_usage.md
@@ -10,13 +10,12 @@ For more information about model source configuration and custom local model pat
## Quick Usage via Command Line
MinerU has built-in command line tools that allow users to quickly use MinerU for document parsing through the command line:
```bash
-mineru -p <input_path> -o <output_path>
+mineru parse <input_path> --pages all -o <output_path>
```
> [!TIP]
->- `<input_path>`: Local `PDF` / `OFD` / `EPUB` / static `HTML` / image / `CSV` / `RTF` / `DOC`/`DOCX` / `PPT`/`PPTX` / `XLS`/`XLSX` / `ODT`/`ODS`/`ODP` 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
+>- `<input_path>`: One local `PDF` / `OFD` / `EPUB` / static `HTML` / image / `CSV` / `RTF` / `DOC`/`DOCX` / `PPT`/`PPTX` / `XLS`/`XLSX` / `ODT`/`ODS`/`ODP` file
+>- `<output_path>`: Optional output file; without it, Markdown is written to stdout
+>- PDF parsing defaults to the first 10 pages; use `--pages all` for the full document
>
> For more information about output files, please refer to [Output File Documentation](../reference/output_files.md).
@@ -26,65 +25,27 @@ mineru -p <input_path> -o <output_path>
If you need to adjust parsing options through custom parameters, you can also check the more detailed [Command Line Tools Usage Instructions](./cli_tools.md) in the documentation.
-## Advanced Usage via API, WebUI, http-client/server
+## Advanced Usage via API, WebUI, and Services
-- FastAPI calls:
+- Start the self-hosted V1 API:
```bash
- mineru-api --host 0.0.0.0 --port 8000
+ mineru-kit api-server --host 0.0.0.0 --port 8000 --tier standard
```
>[!TIP]
- >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`
- >- API outputs are controlled by the server and written to `./output` by default
- >- Uploads currently support `PDF`, `OFD`, `EPUB`, `HTML`, image, `CSV`, `RTF`, `DOC`/`DOCX`, `PPT`/`PPTX`, `XLS`/`XLSX`, `ODT`/`ODS`/`ODP` files
- >
- >- `POST /tasks` returns immediately with a `task_id`. `POST /file_parse` uses the same task manager internally, waits for the task to finish, and then returns the final result synchronously.
- >- When a task is waiting in the queue, both the submission response and task-status response may include `queued_ahead` to indicate how many tasks are ahead of it.
- >- Tasks are tracked only in-process for a single `mineru-api` instance. Task status is not preserved across service restarts, `--reload`, or multi-process deployments.
- >- Completed or failed tasks are retained for 24 hours by default, then their task state and output directory are cleaned automatically. After cleanup, task status and result endpoints return `404`.
- >- Use `MINERU_API_TASK_RETENTION_SECONDS` and `MINERU_API_TASK_CLEANUP_INTERVAL_SECONDS` to adjust retention and cleanup polling intervals.
- >- Use `--enable-vlm-preload true` to warm up the local VLM model during service startup instead of waiting for the first VLM or hybrid request.
- >
- >Asynchronous task submission example:
- >```bash
- >curl -X POST http://127.0.0.1:8000/tasks \
- > -F "files=@demo/pdfs/demo1.pdf" \
- > -F "return_md=true"
- >```
- >
- >Synchronous parsing example:
- >```bash
- >curl -X POST http://127.0.0.1:8000/file_parse \
- > -F "files=@demo/pdfs/demo1.pdf" \
- > -F "return_md=true" \
- > -F "response_format_zip=true" \
- > -F "return_original_file=true"
- >```
- >
- >Poll task status and fetch results:
- >```bash
- >curl http://127.0.0.1:8000/tasks/<task_id>
- >curl http://127.0.0.1:8000/tasks/<task_id>/result
- >curl http://127.0.0.1:8000/health
- >```
+ >Access `http://127.0.0.1:8000/docs` for the OpenAPI documentation. The supported service surface is `/v1/*`, including health, capability discovery, uploads, files, parse jobs, and usage.
>
>HTTP asynchronous call code example: [Python version](https://github.com/opendatalab/MinerU/blob/master/demo/demo.py)
- Start Gradio WebUI visual frontend:
```bash
- mineru-gradio --server-name 0.0.0.0 --server-port 7860
+ mineru-kit gradio --server-name 0.0.0.0 --server-port 7860
```
>[!TIP]
>
>- Access `http://127.0.0.1:7860` in your browser to use the Gradio WebUI.
- >- Without `--api-url`, Gradio starts a reusable local `mineru-api`; with `--api-url`, it reuses an existing local or remote service.
- >- `--enable-vlm-preload true` makes Gradio start its local `mineru-api` during WebUI startup and wait for VLM preload to finish. It is ignored when `--api-url` points to an existing service.
- >- The WebUI currently accepts `PDF`, image, `DOCX`, `PPTX`, and `XLSX` uploads.
+ >- Without `--api-url`, Gradio manages a loopback `mineru-kit api-server`; with `--api-url`, it connects only to that existing V1 service.
+ >- Use `--api-server-preload-models` to preload models for the managed local server.
+ >- `mineru-gradio` remains available as a command-name alias with the same modern options.
- Use `mineru-router` for multi-service / multi-GPU orchestration:
```bash
@@ -92,24 +53,16 @@ If you need to adjust parsing options through custom parameters, you can also ch
```
>[!TIP]
>
- >- `mineru-router` and `mineru-kit router` expose the complete `/v1/*` API and no longer expose `/tasks` or `/file_parse`.
+ >- `mineru-router` and `mineru-kit router` expose the complete `/v1/*` API.
>- Repeat `--upstream-url` to aggregate multiple existing V1 api-server services, or use `--local-gpus` to launch `mineru-kit api-server` workers automatically.
>- Use `--preload-models` for router-managed workers; remote upstreams keep their own startup configuration.
>- Unknown model-engine arguments are not forwarded by Router.
>- It is intended for advanced multi-service, multi-GPU, and unified-entry deployments.
-- Using `http-client/server` method:
+- Start an OpenAI-compatible VLM server:
```bash
- # Start openai compatible server (requires vllm or lmdeploy environment)
- mineru-openai-server --port 30000
- ```
- >[!TIP]
- >In another terminal, connect to openai server via http client
- > ```bash
- > mineru -p <input_path> -o <output_path> -b hybrid-http-client -u http://127.0.0.1:30000
- > ```
- >`hybrid-http-client` requires local pipeline dependencies such as `mineru[pipeline]` and `torch`.
- >Legacy `vlm-http-client` input is accepted for compatibility and maps to `hybrid-http-client` with `--effort high`.
+ mineru-kit vlm-server --engine auto --port 30000
+ ```
> [!NOTE]
> Model-engine parameters apply only to commands that explicitly declare them. `mineru-router` accepts documented Router/worker options and does not forward unknown arguments.
@@ -141,11 +94,15 @@ llm_aided:
## Extending MinerU Functionality with Configuration Files
-MinerU is now ready to use out of the box, but also supports extending functionality through configuration files. Legacy tool options such as LaTeX delimiters and LLM-aided title hierarchy still use `mineru.json` in your user directory. Model storage and model source settings use `config.yaml`; see [Model Source Documentation](./model_source.md).
+MinerU works out of the box and reads current settings from `$MINERU_HOME/config.yaml`; set `MINERU_CONFIG` to use another file. Legacy `mineru.json` CLI settings are no longer supported. Gradio's LaTeX delimiters are selected with `--latex-delimiters-type`.
+
+Model storage and source settings use the `model` section:
-Here are some available configuration options:
+```yaml
+model:
+ base_dir: ~/.mineru/models
+ source: auto
+ stack: auto
+```
-- `models-dir`:
- * Used to specify local model storage directory
- * Please specify model directories for the local lightweight model bundle (`models-dir.pipeline`) and the VLM bundle (`models-dir.vlm`) separately.
- * After specifying the directory, you can use local models by configuring the environment variable `export MINERU_MODEL_SOURCE=local`.
+See [Model Source Documentation](./model_source.md) for model download and local-source details.
diff --git a/docs/next/cli.md b/docs/next/cli.md
index d674a1c2..2d7775c1 100644
--- a/docs/next/cli.md
+++ b/docs/next/cli.md
@@ -20,6 +20,7 @@ CLI 文档已拆分到 [cli/README.md](cli/README.md)。
8. [mineru-kit](cli/mineru-kit.md)
9. [mineru-kit models](cli/mineru-kit-models.md)
10. [mineru-kit parse](cli/mineru-kit-parse.md)
-11. [mineru-kit api-server](cli/mineru-kit-api-server.md)
-12. [mineru-kit vlm-server](cli/mineru-kit-vlm-server.md)
-13. `mineru-kit router`: 当前见 [mineru-kit](cli/mineru-kit.md)
+11. [mineru-kit gradio](cli/mineru-kit-gradio.md)
+12. [mineru-kit api-server](cli/mineru-kit-api-server.md)
+13. [mineru-kit vlm-server](cli/mineru-kit-vlm-server.md)
+14. `mineru-kit router`: 当前见 [mineru-kit](cli/mineru-kit.md)
diff --git a/docs/next/cli/README.md b/docs/next/cli/README.md
index e3bda1c3..33cf622f 100644
--- a/docs/next/cli/README.md
+++ b/docs/next/cli/README.md
@@ -43,8 +43,9 @@ MinerU 仓库提供两款命令行工具:
7. [mineru-kit](mineru-kit.md): 理解无状态工具定位。
8. [mineru-kit models](mineru-kit-models.md): 理解模型下载、当前模型配置查看和轻量校验。
9. [mineru-kit parse](mineru-kit-parse.md): 理解批处理解析、目录输入、local/remote 规则和输出命名。
-10. [mineru-kit api-server](mineru-kit-api-server.md): 理解本地/自部署 parse-server。
-11. [mineru-kit vlm-server](mineru-kit-vlm-server.md): 理解本地 VLM 服务与 api-server backend 的边界。
+10. [mineru-kit gradio](mineru-kit-gradio.md): 理解基于 V1 API 的文档解析 Web UI。
+11. [mineru-kit api-server](mineru-kit-api-server.md): 理解本地/自部署 parse-server。
+12. [mineru-kit vlm-server](mineru-kit-vlm-server.md): 理解本地 VLM 服务与 api-server backend 的边界。
## 4. 共享约束
diff --git a/docs/next/cli/mineru-kit-gradio.md b/docs/next/cli/mineru-kit-gradio.md
new file mode 100644
index 00000000..f65b39c6
--- /dev/null
+++ b/docs/next/cli/mineru-kit-gradio.md
@@ -0,0 +1,74 @@
+# mineru-kit gradio
+
+状态: Implemented
+
+`mineru-kit gradio` 提供一个基于 MinerU V1 API 的文档解析界面。它不直接调用旧 `/file_parse` 或 `/tasks` 接口,也不使用 `doclib` 缓存。
+
+## 启动
+
+安装 Gradio 可选依赖:
+
+```bash
+pip install 'mineru[gradio]'
+```
+
+自动启动本地 V1 API server:
+
+```bash
+mineru-kit gradio
+```
+
+连接已有 self-hosted 或 remote V1 API server:
+
+```bash
+mineru-kit gradio \
+ --api-url http://127.0.0.1:16580 \
+ --api-key "$MINERU_API_KEY"
+```
+
+未指定 `--api-url` 时,Gradio 会启动一个 loopback `mineru-kit api-server`。本地 server 默认使用 Standard 能力上限、开启 Flash、关闭 `local` source,文件通过 V1 Uploads API 提交。
+
+## 主要参数
+
+| 参数 | 说明 |
+|------|------|
+| `--api-url` | 已有 V1 API base URL;不传则自动启动本地 server。 |
+| `--api-key` | Bearer API Key;省略时读取 `MINERU_API_KEY`。 |
+| `--server-name` / `--server-port` | Gradio UI 的监听地址和端口。 |
+| `--output-dir` | 本地 UI 产物根目录,默认 `./output`。 |
+| `--api-server-tier` | 自动启动 server 的能力档位:`flash`、`basic`、`standard`。 |
+| `--api-server-concurrency` | 自动启动 server 的最大并发任务数。 |
+| `--api-server-language` | 自动启动 server 的 OCR 语言提示。 |
+| `--api-server-ocr-mode` | 自动启动 server 的 OCR 模式:`auto`、`txt`、`ocr`。 |
+| `--api-server-preload-models` | 在自动启动阶段预加载模型。 |
+| `--api-server-no-flash` | 自动启动 server 时关闭 Flash。 |
+| `--api-server-disable-image-analysis` | 自动启动 server 时关闭图片分析。 |
+| `--enable-example` | 显示当前工作目录 `examples/` 中的示例文件。 |
+| `--enable-api` | 暴露 Gradio 转换事件 API。 |
+| `--latex-delimiters-type` | Markdown 预览公式分隔符:`a`、`b` 或 `all`。 |
+
+## 解析流程
+
+界面一次提交一个文件,支持 `filetypes.PARSEABLE_EXTENSIONS` 中的 PDF、图片、Office/ODF、RTF、HTML、CSV/TSV、EPUB 和 OFD。
+
+页码输入使用 V1 `page_range` 语法,例如 `1~5,8,-1`;留空表示全部页面。只有原始 PDF 支持显式页码范围,其他格式会自动清空并禁用页码控件。
+
+Gradio 首先发现 `/v1/health` 和 `/v1/tiers`,然后通过 `MinerUApiParser` 上传文件、创建 `/v1/parse/jobs`、轮询任务并下载 ZIP 结果。解析结果保存为严格 Middle JSON 2.0。
+
+## 结果与下载
+
+页面只展示:
+
+- Markdown 渲染;
+- Markdown 源码;
+- Structured Content 源码。
+
+下载菜单包含 ZIP、HTML、DOCX、LaTeX bundle、EPUB 和 PDF。HTML、DOCX、EPUB、PDF 和 LaTeX 不作为 API job 输出请求,而是在用户点击菜单后从本次保存的 Middle JSON 按需渲染。LaTeX 下载包包含 `.tex` 与 `images/`,可交给 XeLaTeX 使用;Gradio 不自动执行 TeX 编译。
+
+每次解析的文件保存在独立的 `output-dir/gradio/<run-id>/` 目录,包含源文件、Middle JSON、基础文本产物以及可选的 `origin.pdf`、`layout.pdf` 和图片资源。路径只向 Gradio 暴露在配置的 output root 内。
+
+## 预览与兼容边界
+
+PDF 和图片会生成与解析范围一致的 `origin.pdf`;布局预览使用 schema 2.0 顶层 block/bbox 生成语义 overlay。无法生成 overlay 时仍保留 origin PDF 预览。
+
+`mineru-gradio` 保留为 `mineru-kit gradio` 的兼容命令名,参数与行为完全相同;旧 HTTP 协议和旧 Gradio 专属参数不再提供。
diff --git a/docs/next/cli/mineru-kit.md b/docs/next/cli/mineru-kit.md
index de700770..0a4d74a3 100644
--- a/docs/next/cli/mineru-kit.md
+++ b/docs/next/cli/mineru-kit.md
@@ -23,10 +23,29 @@
|--------|------|------|
| `mineru-kit models` | 下载、查看和校验本地模型配置 | [mineru-kit models](mineru-kit-models.md) |
| `mineru-kit parse` | 无状态文件/目录批处理解析 | [mineru-kit parse](mineru-kit-parse.md) |
+| `mineru-kit gradio` | 基于 V1 API 的本地文档解析 Web UI | [mineru-kit gradio](mineru-kit-gradio.md) |
| `mineru-kit api-server` | 启动兼容统一 API 的本地解析服务 | [mineru-kit api-server](mineru-kit-api-server.md) |
| `mineru-kit vlm-server` | 本地 VLM 服务,兼容 OpenAI Chat Completions 协议 | [mineru-kit vlm-server](mineru-kit-vlm-server.md) |
| `mineru-kit router` | 启动 V1 路由服务,转发到已有 upstream 或管理本地 worker | 仅暴露 `/v1/*` |
+### 独立命令别名
+
+以下独立命令直接复用新版 kit 的参数、默认值、校验和行为,仅保留命令名,不恢复旧 CLI 参数或协议:
+
+| 独立命令 | 等价命令 |
+|----------|----------|
+| `mineru-openai-server` | `mineru-kit vlm-server` |
+| `mineru-models-download` | `mineru-kit models download` |
+| `mineru-api` | `mineru-kit api-server` |
+
+```bash
+mineru-openai-server --engine vllm --host 127.0.0.1 --port 30000
+mineru-models-download --tier standard --source modelscope
+mineru-api --host 127.0.0.1 --port 8000 --tier standard
+```
+
+`mineru-openai-server` 保留向底层引擎透传额外参数的能力。`mineru-models-download` 后直接填写模型仓库名或 `--tier` 等下载参数,不需要再输入 `download`。
+
## 3. 与 mineru 的边界
| 能力 | `mineru` | `mineru-kit` |
@@ -45,6 +64,8 @@
`mineru-kit` 参数暂不划分 `stable` / `experimental` 等稳定性等级。第一阶段保持参数体系简单,后续只有在兼容性压力明确出现时再引入分级。
+`mineru-kit gradio` 是无状态的 V1 API 客户端界面。未指定 `--api-url` 时,它会自动托管一个 loopback `mineru-kit api-server`;指定 URL 时只连接已有的 V1 服务,不会静默改连官方远程服务。`mineru-gradio` 保留为同一新版命令的兼容别名,不再提供旧 HTTP 协议或旧参数。
+
当前 `mineru-kit parse` 已确定:
- 只支持文件和目录输入,不支持 stdin、路径列表、URL 输入和递归目录。
diff --git a/docs/next/code-map.md b/docs/next/code-map.md
index fbd58541..ec283800 100644
--- a/docs/next/code-map.md
+++ b/docs/next/code-map.md
@@ -16,7 +16,7 @@
| `mineru` | `mineru.cli.main:main` |
| `mineru-kit` | `mineru.kit.main:main` |
| `mineru-router` | `mineru.kit.router.cli:main` |
-| `mineru-gradio` | `mineru.cli_old.gradio_app:main` |
+| `mineru-gradio` | `mineru.kit.commands.gradio:main`(`mineru-kit gradio` 兼容别名) |
## 2. 模块职责表
@@ -29,8 +29,7 @@
| `mineru/backend/` | 解析引擎:`analyze.py`(`doc_analyze` 统一门面)→ `analysis/`(按格式分派:`pdf/`、`csv.py`、`epub.py`、`html.py`、`ofd.py`、`office.py`)→ `postprocess/`(Middle JSON 组装、段落/标题/列表/表格合并、`llm_aided.py`、`legacy_schema_adapter.py`) | `backend/analyze.py`、`backend/analysis/pdf/pipeline.py` |
| `mineru/model/` | 模型层:`flash/`(纯 CPU 本地结构化解析器族:pdf / office / epub / html / ofd / csv);`runtime/`(`device.py` 设备与 light/full 栈、`hybrid.py` 原子模型分派、`onnx.py`);`layout/ mfr/ ocr/ table/ vlm/`(ML 模型实现);`_internal/pytorchocr` | `model/runtime/device.py:48`、`model/runtime/hybrid.py` |
| `mineru/render/` | 输出渲染:markdown / content_list(v2) / structured_content / docx / epub / html / pdf | `render/api.py`(唯一渲染入口)、`render/contracts.py` |
-| `mineru/kit/` | 服务端工具 CLI:`parse` / `api-server` / `vlm-server` / `router` / `models`,面向自部署/多卡部署 | `kit/main.py`、`kit/commands/*.py` |
-| `mineru/cli_old/` | 3.x CLI 原样迁入的兼容层(client / fast_api / gradio_app / router 等),仅改导入路径与裁剪 | 仅 `mineru-gradio` 入口引用 |
+| `mineru/kit/` | 服务端与 Web 工具 CLI:`parse` / `gradio` / `api-server` / `vlm-server` / `router` / `models`,面向无状态批处理、自部署和多卡部署 | `kit/main.py`、`kit/commands/*.py`、`kit/gradio/` |
| 顶层类型/配置 | `types.py`(1317 行,Tier / locator / 各 Response 模型)、`errors.py`(错误协议)、`config.py`(MINERU_HOME、UDS/TCP、model stack)、`filetypes.py`(扩展名→tier 语义) | `config.py`(`Config`)、`errors.py:20` |
| `docs/next/` | 4.x 全套设计文档:architecture / tiers / errors / middle-json + 33 篇 ADR(`decisions/0001-0033`)+ 实施计划 `docs/plans/` | `docs/next/README.md` |
| `tests/unittest/` | 约 2372 个测试函数 | — |
diff --git a/docs/zh/usage/acceleration_cards/AMD.md b/docs/zh/usage/acceleration_cards/AMD.md
index 4ab62168..6ab58978 100644
--- a/docs/zh/usage/acceleration_cards/AMD.md
+++ b/docs/zh/usage/acceleration_cards/AMD.md
@@ -9,7 +9,7 @@
Two Step Extraction: 100%|████████████████████████████████████████| 200/200 [01:40<00:00, 1.99it/s]
**下面为之前14学术论文测试结果:**
-7900xtx mineru-gradio --server-name 0.0.0.0 --server-port 7860 --enable-vllm-engine true 速度大概为**1.6-1.8s/it**,没有仔细测试,简单试了两个文档。第二种矩阵乘法代替原来的dots点乘可以进一步提速到1.3s/it,优化后的主要算子耗时在hipblast(这个没法提升了)和vllm triton后端,各占25%耗时吧,vllm tirion后端这个这个只能等官方优化了。。。。
+7900xtx 使用 `mineru-kit gradio --server-name 0.0.0.0 --server-port 7860 --api-server-tier standard` 时速度大概为**1.6-1.8s/it**,没有仔细测试,简单试了两个文档。第二种矩阵乘法代替原来的dots点乘可以进一步提速到1.3s/it,优化后的主要算子耗时在hipblast(这个没法提升了)和vllm triton后端,各占25%耗时吧,vllm tirion后端这个这个只能等官方优化了。。。。
doclayout-yolo的layout速度从原来的1.6it/s提高到15it/s,注意需要缓存一下输入的pdf尺寸后,triton必须要缓存尺寸没办法。主要是为了保留模型输入输出接口,最小代码改动。
采用-b vlm-vllm-engine模式举个例子
@@ -21,7 +21,7 @@ Processed prompts: 100%|██████████████████
Adding requests: 100%|█████████████████████████████████████████████████████████████████████████████| 278/278 [00:00<00:00, 323.03it/s]
Processed prompts: 100%|██████████████████| 278/278 [00:07<00:00, 37.63it/s, est. speed input: 5264.66 toks/s, output: 2733.31 toks/s]
-mineru-gradio --server-name 0.0.0.0 --server-port 7860 --enable-vllm-engine true测试:
+`mineru-kit gradio --server-name 0.0.0.0 --server-port 7860 --api-server-tier standard` 测试:
2025-10-05 15:46:55.953 | WARNING | mineru.cli_old.common:convert_pdf_bytes_to_bytes_by_pypdfium2:54 - end_page_id is out of range, use pdf_docs length
Two Step Extraction: 100%|████████████████████████████████████████████████████████████████████████████| 14/14 [00:18<00:00, 1.30s/it]
@@ -335,7 +335,7 @@ def triton_conv3d_patchify(x_5d: torch.Tensor, weight_5d: torch.Tensor) -> torch
return C
```
---
-**4.关闭终端后再次使用mineru-gradio会报一个Lora错误,修改代码跳过它**
+**4.关闭终端后再次使用 `mineru-kit gradio` 会报一个 Lora 错误,修改代码跳过它**
```
pip show mineru_vl_utils
```
@@ -362,4 +362,3 @@ export TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1
```
pip show doclayout-yolo
```
-
diff --git a/docs/zh/usage/acceleration_cards/Ascend.md b/docs/zh/usage/acceleration_cards/Ascend.md
index ccfd25a0..f27e7143 100644
--- a/docs/zh/usage/acceleration_cards/Ascend.md
+++ b/docs/zh/usage/acceleration_cards/Ascend.md
@@ -126,7 +126,7 @@ docker run -u root --name mineru_docker --privileged=true \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
<td>🟢</td>
@@ -142,7 +142,7 @@ docker run -u root --name mineru_docker --privileged=true \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
<td>🟢</td>
diff --git a/docs/zh/usage/acceleration_cards/Biren.md b/docs/zh/usage/acceleration_cards/Biren.md
index 154d2d94..329686d2 100644
--- a/docs/zh/usage/acceleration_cards/Biren.md
+++ b/docs/zh/usage/acceleration_cards/Biren.md
@@ -65,7 +65,7 @@ docker run -it --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -78,7 +78,7 @@ docker run -it --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -105,4 +105,4 @@ docker run -it --name mineru_docker \
>[!TIP]
> - Biren加速卡指定可用加速卡的方式与NVIDIA GPU类似,请参考[使用指定GPU设备](https://opendatalab.github.io/MinerU/zh/usage/advanced_cli_parameters/#cuda_visible_devices)章节说明,
>将环境变量`CUDA_VISIBLE_DEVICES`替换为`SUPA_VISIBLE_DEVICES`即可。
-> - 在壁仞平台可以通过`brsmi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在壁仞平台可以通过`brsmi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/Cambricon.md b/docs/zh/usage/acceleration_cards/Cambricon.md
index 83943a03..3586a2ad 100644
--- a/docs/zh/usage/acceleration_cards/Cambricon.md
+++ b/docs/zh/usage/acceleration_cards/Cambricon.md
@@ -105,7 +105,7 @@ docker run --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
<td>🟢</td>
@@ -121,7 +121,7 @@ docker run --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
<td>🟢</td>
@@ -152,4 +152,4 @@ docker run --name mineru_docker \
>[!TIP]
> - Cambricon加速卡指定可用加速卡的方式与NVIDIA GPU类似,请参考[使用指定GPU设备](https://opendatalab.github.io/MinerU/zh/usage/advanced_cli_parameters/#cuda_visible_devices)章节说明,
>将环境变量`CUDA_VISIBLE_DEVICES`替换为`MLU_VISIBLE_DEVICES`即可。
-> - 在Cambricon平台可以通过`cnmon`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在Cambricon平台可以通过`cnmon`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/Enflame.md b/docs/zh/usage/acceleration_cards/Enflame.md
index 0ee1cbaa..751c48ee 100644
--- a/docs/zh/usage/acceleration_cards/Enflame.md
+++ b/docs/zh/usage/acceleration_cards/Enflame.md
@@ -63,7 +63,7 @@ docker run -u root --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -76,7 +76,7 @@ docker run -u root --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -103,4 +103,4 @@ docker run -u root --name mineru_docker \
>[!TIP]
> - GCU加速卡指定可用加速卡的方式与NVIDIA GPU类似,请参考[使用指定GPU设备](https://opendatalab.github.io/MinerU/zh/usage/advanced_cli_parameters/#cuda_visible_devices)章节说明,
>将环境变量`CUDA_VISIBLE_DEVICES`替换为`TOPS_VISIBLE_DEVICES`即可。
-> - 在Enflame平台可以通过`efsmi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在Enflame平台可以通过`efsmi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/Hygon.md b/docs/zh/usage/acceleration_cards/Hygon.md
index d6ad7947..5b33986f 100644
--- a/docs/zh/usage/acceleration_cards/Hygon.md
+++ b/docs/zh/usage/acceleration_cards/Hygon.md
@@ -70,7 +70,7 @@ docker run -u root --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -83,7 +83,7 @@ docker run -u root --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -109,4 +109,4 @@ docker run -u root --name mineru_docker \
>[!TIP]
> - DCU加速卡指定可用加速卡的方式与AMD GPU类似,请参考[GPU isolation techniques](https://rocm.docs.amd.com/en/docs-6.2.4/conceptual/gpu-isolation.html)
-> - 在Hygon平台可以通过`hy-smi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在Hygon平台可以通过`hy-smi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/IluvatarCorex.md b/docs/zh/usage/acceleration_cards/IluvatarCorex.md
index 8022461d..fb6aa46f 100644
--- a/docs/zh/usage/acceleration_cards/IluvatarCorex.md
+++ b/docs/zh/usage/acceleration_cards/IluvatarCorex.md
@@ -77,7 +77,7 @@ docker run --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -90,7 +90,7 @@ docker run --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -116,4 +116,4 @@ docker run --name mineru_docker \
>[!TIP]
> - Iluvatar加速卡指定可用加速卡的方式与NVIDIA GPU类似,请参考[使用指定GPU设备](https://opendatalab.github.io/MinerU/zh/usage/advanced_cli_parameters/#cuda_visible_devices)章节说明
-> - 在Iluvatar平台可以通过`ixsmi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在Iluvatar平台可以通过`ixsmi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/Kunlunxin.md b/docs/zh/usage/acceleration_cards/Kunlunxin.md
index 59670766..4fa0ae40 100644
--- a/docs/zh/usage/acceleration_cards/Kunlunxin.md
+++ b/docs/zh/usage/acceleration_cards/Kunlunxin.md
@@ -76,7 +76,7 @@ docker run -u root --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -89,7 +89,7 @@ docker run -u root --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
diff --git a/docs/zh/usage/acceleration_cards/METAX.md b/docs/zh/usage/acceleration_cards/METAX.md
index ceef098a..73c54ce3 100644
--- a/docs/zh/usage/acceleration_cards/METAX.md
+++ b/docs/zh/usage/acceleration_cards/METAX.md
@@ -98,7 +98,7 @@ docker run --ipc host \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
<td>🟢</td>
@@ -114,7 +114,7 @@ docker run --ipc host \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
<td>🟢</td>
@@ -144,4 +144,4 @@ docker run --ipc host \
>[!TIP]
> - MACA加速卡指定可用加速卡的方式与NVIDIA GPU类似,请参考[使用指定GPU设备](https://opendatalab.github.io/MinerU/zh/usage/advanced_cli_parameters/#cuda_visible_devices)章节说明。
-> - 在METAX平台可以通过`mx-smi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在METAX平台可以通过`mx-smi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/MooreThreads.md b/docs/zh/usage/acceleration_cards/MooreThreads.md
index 31dbc8e8..f629c3a4 100644
--- a/docs/zh/usage/acceleration_cards/MooreThreads.md
+++ b/docs/zh/usage/acceleration_cards/MooreThreads.md
@@ -71,7 +71,7 @@ docker run -u root --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -84,7 +84,7 @@ docker run -u root --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -110,4 +110,4 @@ docker run -u root --name mineru_docker \
>[!TIP]
> - MooreThreads加速卡指定可用加速卡的方式与NVIDIA GPU类似,请参考[GPU 枚举](https://docs.mthreads.com/cloud-native/cloud-native-doc-online/install_guide/#gpu-%E6%9E%9A%E4%B8%BE)
-> - 在MooreThreads平台可以通过`mthreads-gmi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在MooreThreads平台可以通过`mthreads-gmi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/THead.md b/docs/zh/usage/acceleration_cards/THead.md
index 677dde27..7acacf09 100644
--- a/docs/zh/usage/acceleration_cards/THead.md
+++ b/docs/zh/usage/acceleration_cards/THead.md
@@ -89,7 +89,7 @@ docker run --privileged=true \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
<td>🟢</td>
@@ -105,7 +105,7 @@ docker run --privileged=true \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
<td>🟢</td>
@@ -135,4 +135,4 @@ docker run --privileged=true \
>[!TIP]
> - PPU加速卡指定可用加速卡的方式与NVIDIA GPU类似,请参考[使用指定GPU设备](https://opendatalab.github.io/MinerU/zh/usage/advanced_cli_parameters/#cuda_visible_devices)章节说明。
-> - 在T-Head平台可以通过`ppu-smi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在T-Head平台可以通过`ppu-smi`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/Tecorigin.md b/docs/zh/usage/acceleration_cards/Tecorigin.md
index 3c44409e..af0e2591 100644
--- a/docs/zh/usage/acceleration_cards/Tecorigin.md
+++ b/docs/zh/usage/acceleration_cards/Tecorigin.md
@@ -73,7 +73,7 @@ docker run -dit --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">fastapi服务(mineru-api)</td>
+ <td rowspan="3">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -86,7 +86,7 @@ docker run -dit --name mineru_docker \
<td>🟢</td>
</tr>
<tr>
- <td rowspan="3">gradio界面(mineru-gradio)</td>
+ <td rowspan="3">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🟢</td>
</tr>
@@ -113,4 +113,4 @@ docker run -dit --name mineru_docker \
>[!TIP]
> - Tecorigin加速卡指定可用加速卡的方式与NVIDIA GPU类似,请参考[使用指定GPU设备](https://opendatalab.github.io/MinerU/zh/usage/advanced_cli_parameters/#cuda_visible_devices)章节说明,
>将环境变量`CUDA_VISIBLE_DEVICES`替换为`SDAA_VISIBLE_DEVICES`即可。
-> - 在太初平台可以通过`teco-smi -c`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
\ No newline at end of file
+> - 在太初平台可以通过`teco-smi -c`命令查看加速卡的使用情况,并根据需要指定空闲的加速卡ID以避免资源冲突。
diff --git a/docs/zh/usage/acceleration_cards/VastAI.md b/docs/zh/usage/acceleration_cards/VastAI.md
index c5f54435..a2f2aa7e 100644
--- a/docs/zh/usage/acceleration_cards/VastAI.md
+++ b/docs/zh/usage/acceleration_cards/VastAI.md
@@ -159,7 +159,7 @@
<td>🟢</td>
</tr>
<tr>
- <td rowspan="5">fastapi服务(mineru-api)</td>
+ <td rowspan="5">FastAPI 服务(mineru-kit api-server)</td>
<td>pipeline</td>
<td>🔴</td>
</tr>
@@ -180,7 +180,7 @@
<td>🟢</td>
</tr>
<tr>
- <td rowspan="5">gradio界面(mineru-gradio)</td>
+ <td rowspan="5">gradio界面(mineru-kit gradio)</td>
<td>pipeline</td>
<td>🔴</td>
</tr>
diff --git a/docs/zh/usage/advanced_cli_parameters.md b/docs/zh/usage/advanced_cli_parameters.md
index e1364918..7730bd1a 100644
--- a/docs/zh/usage/advanced_cli_parameters.md
+++ b/docs/zh/usage/advanced_cli_parameters.md
@@ -38,20 +38,20 @@
> - 如果您有多张显卡,需要在卡0和卡1上启动两个`openai-server`服务,并分别监听不同的端口,可以使用以下命令:
> ```bash
> # 在终端1中
-> CUDA_VISIBLE_DEVICES=0 mineru-openai-server --engine vllm --port 30000
+> CUDA_VISIBLE_DEVICES=0 mineru-kit vlm-server --engine vllm --port 30000
> # 在终端2中
-> CUDA_VISIBLE_DEVICES=1 mineru-openai-server --engine vllm --port 30001
+> CUDA_VISIBLE_DEVICES=1 mineru-kit vlm-server --engine vllm --port 30001
> ```
>
> - 如果您有多张显卡,需要在卡0和卡1上启动两个`fastapi`服务,并分别监听不同的端口,可以使用以下命令:
> ```bash
> # 在终端1中
-> CUDA_VISIBLE_DEVICES=0 mineru-api --host 127.0.0.1 --port 8000
+> CUDA_VISIBLE_DEVICES=0 mineru-kit api-server --host 127.0.0.1 --port 8000
> # 在终端2中
-> CUDA_VISIBLE_DEVICES=1 mineru-api --host 127.0.0.1 --port 8001
+> CUDA_VISIBLE_DEVICES=1 mineru-kit api-server --host 127.0.0.1 --port 8001
> ```
>
> - 如果您有多张显卡,需要通过`router`在其中4张卡上启动`fastapi`服务并统一管理,可以使用以下命令:
> ```bash
-> CUDA_VISIBLE_DEVICES=0,1,2,3 mineru-router --host 127.0.0.1 --port 8002
+> CUDA_VISIBLE_DEVICES=0,1,2,3 mineru-kit router --host 127.0.0.1 --port 8002
> ```
diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.md
index ba7d24b6..52d7d11e 100644
--- a/docs/zh/usage/cli_tools.md
+++ b/docs/zh/usage/cli_tools.md
@@ -1,182 +1,75 @@
-# 命令行工具使用说明
+# 命令行工具
+
+MinerU 提供两个主要命令树:`mineru` 是面向交互和 Agent 工作流的文档库客户端,`mineru-kit` 提供无状态解析、服务、模型、Router 和 WebUI 工具。
+
+## 文档库 CLI
+
+使用 `mineru --help` 查看全部文档库命令。最常见的解析方式是:
+
+```bash
+mineru parse report.pdf --pages all -o report.md
+```
+
+未指定 `-o/--output` 时,渲染结果写入标准输出。PDF 默认解析前 10 页;使用 `--pages all` 解析整份文档。文档库负责入库、缓存、后台解析、阅读、搜索和清理。
+
+使用以下命令管理本地文档库服务:
+
+```bash
+mineru server start
+mineru server status
+mineru server stop
+```
+
+各命令的权威参数以 `mineru <command> --help` 为准。
+
+## 无状态与服务工具
+
+使用 `mineru-kit --help` 查看所有工具。
+
+### 批量解析
-## 查看帮助信息
-要查看 MinerU 命令行工具的帮助信息,可以使用 `--help` 参数。以下是各个命令行工具的帮助信息示例:
```bash
-mineru --help
-Usage: mineru [OPTIONS]
-
-Options:
- -v, --version 显示版本并退出
- -p, --path PATH 输入文件路径或目录(必填)
- -o, --output PATH 输出目录(必填)
- --api-url TEXT MinerU FastAPI 服务地址;不传时自动拉起本地临时 mineru-api
- -m, --method [auto|txt|ocr] 解析方法:auto(默认)、txt、ocr(仅用于 hybrid* 后端)
- -b, --backend [hybrid-engine|hybrid-http-client]
- 解析后端(默认为 hybrid-engine)
- --effort [medium|high|xhigh] Hybrid 解析强度(默认:high)
- -l, --lang [ch|ch_server|korean|ta|te|ka|th|el|arabic|east_slavic|cyrillic|devanagari]
- 指定文档语言(可提升 OCR 准确率,仅用于 hybrid* 后端)
- -u, --url TEXT 当使用 http-client 时,传给服务端后端的 OpenAI 兼容地址
- -s, --start INTEGER 开始解析的页码(从 0 开始)
- -e, --end INTEGER 结束解析的页码(从 0 开始)
- --image-analysis BOOLEAN 是否启用 hybrid 的图片/图表分析;Hybrid
- medium 和 high effort 会自动关闭图片/图表分析(默认开启)
- --client-side-output-generation BOOLEAN
- 在客户端基于服务端返回的 middle JSON、图片与原文件
- 生成 Markdown 和 content list(默认关闭)
- --help 显示帮助信息
+mineru-kit parse report.pdf -o report.md --tier standard
+mineru-kit parse ./documents -o ./output --format zip
```
-> [!TIP]
-> `mineru` 当前支持本地 `PDF`、`OFD`、`EPUB`、静态 `HTML`、图片、`CSV`、`RTF`、`DOC`/`DOCX`、`PPT`/`PPTX`、`XLS`/`XLSX`、`ODT`/`ODS`/`ODP` 文件或目录输入。只有 PDF 接受页范围;其他输入均按一个完整文件解析和缓存,但各格式自身的边界仍作为结构化输出中的逻辑页保留。EPUB 页面严格遵循 OPF spine 顺序,并保留作者目录中可解析的内部跳转。
+
+`mineru-kit parse` 不使用文档库数据库或缓存,支持本地解析和显式 V1 远程解析。tier、backend、页范围和输出参数以 `mineru-kit parse --help` 为准。
+
+### V1 API Server
```bash
-mineru-api --help
-Usage: mineru-api [OPTIONS]
-
-Options:
- --host TEXT 服务器主机地址(默认:127.0.0.1)
- --port INTEGER 服务器端口(默认:8000)
- --reload 启用自动重载(开发模式)
- --enable-vlm-preload BOOLEAN
- 在 mineru-api 启动阶段预加载本地 VLM 模型
- --help 显示此帮助信息并退出
+mineru-kit api-server --host 127.0.0.1 --port 8000 --tier standard
```
+
+在浏览器打开 `http://127.0.0.1:8000/docs` 查看自动生成的 OpenAPI 文档。当前服务接口统一位于 `/v1/*`;已删除的 `/file_parse` 和 `/tasks` 不再提供。
+
+### Gradio WebUI
+
```bash
-mineru-gradio --help
-Usage: mineru-gradio [OPTIONS]
-
-Options:
- --enable-example BOOLEAN 启用示例文件输入(需要将示例文件放置在当前
- 执行命令目录下的 `examples` 文件夹中)
- --enable-http-client BOOLEAN 在后端选项中启用 HTTP 客户端选项
- --enable-api BOOLEAN 启用 Gradio API 以提供应用程序服务
- --max-convert-pages INTEGER 设置从 PDF 转换为 Markdown 的最大页数
- --server-name TEXT 设置 Gradio 应用程序的服务器主机名
- --server-port INTEGER 设置 Gradio 应用程序的服务器端口
- --api-url TEXT MinerU FastAPI 服务地址;不传时自动拉起可复用的本地
- mineru-api
- --enable-vlm-preload BOOLEAN 在 Gradio 拉起本地 mineru-api 时预加载本地
- VLM 模型
- --client-side-output-generation BOOLEAN
- 在客户端基于服务端返回的 middle JSON 生成 Markdown
- 和 content list
- --latex-delimiters-type [a|b|all]
- 设置在 Markdown 渲染中使用的 LaTeX 分隔符类型
- ('a' 表示 '$' 类型,'b' 表示 '()[]' 类型,
- 'all' 表示两种类型都使用)
- --help 显示此帮助信息并退出
+mineru-kit gradio --server-name 127.0.0.1 --server-port 7860
```
+
+未传 `--api-url` 时,Gradio 会托管 loopback `mineru-kit api-server`;传入后只连接指定的 V1 服务。`mineru-gradio` 保留为命令名兼容别名,接受相同的新版参数,不恢复旧 Gradio 参数或 HTTP 路由。
+
+### Router 与 VLM Server
+
```bash
-mineru-router --help
-Usage: mineru-router [OPTIONS]
-
-Options:
- --host TEXT 路由服务主机地址(默认:127.0.0.1)
- --port INTEGER 路由服务端口(默认:8002)
- --reload 启用自动重载(开发模式)
- --upstream-url TEXT 现有 MinerU FastAPI 服务地址;可重复传入多个
- --local-gpus TEXT 本地 GPU worker 配置:auto、none 或 0,1,2 形式
- --worker-host TEXT 路由托管 worker 的监听地址(默认:127.0.0.1)
- --worker-tier TEXT 托管 worker 档位:flash、basic、standard
- --worker-concurrency INTEGER
- 每个托管 worker 的并发数
- --preload-models 在托管 worker 中预加载模型
- --help 显示此帮助信息并退出
+mineru-kit router --host 127.0.0.1 --port 8002 --local-gpus auto
+mineru-kit vlm-server --engine auto --port 30000
```
-`mineru-router` 是 `mineru-kit router` 的过渡别名。两个命令都只暴露 MinerU V1 API,并拒绝未知 worker 参数透传。
-
-## 环境变量说明
-
-> [!NOTE]
-> 从当前版本开始,`mineru` 是基于 `mineru-api` 的编排客户端:
->
->- 未传 `--api-url` 时,CLI 会自动拉起本地临时 `mineru-api`
->- 传入 `--api-url` 时,CLI 会直连该 FastAPI 服务
->- `--url` 不再表示 MinerU API 地址,而是服务端 `vlm/hybrid-http-client` 所需的 OpenAI 兼容地址
-
-MinerU命令行工具的某些参数存在相同功能的环境变量配置,通常环境变量配置的优先级高于命令行参数,且在所有命令行工具中都生效。
-以下是常用的环境变量及其说明:
-
-- `MINERU_TOOLS_CONFIG_JSON`:
- * 用于指定配置文件路径
- * 默认为用户目录下的`mineru.json`,可通过环境变量指定其他配置文件路径。
-
-- `MINERU_FORMULA_CH_SUPPORT`:
- * 用于启用中文公式解析优化(实验性功能)
- * 默认为`false`,可通过环境变量设置为`true`来启用中文公式解析优化。
- * 仅对本地 Hybrid 模型执行生效。
-
-- `MINERU_PDF_RENDER_TIMEOUT`:
- * 用于设置将PDF渲染为图片的超时时间(秒)
- * 默认为`300`秒,可通过环境变量设置为其他值以调整渲染图片的超时时间。
- * 在 Linux、macOS 和 Windows 系统中生效。
-
-- `MINERU_PDF_RENDER_THREADS`:
- * 用于设置将PDF渲染为图片时使用的渲染 worker 并发数
- * 默认为`4`,可通过环境变量设置为其他值以调整渲染 worker 并发数。
- * 在 Linux、macOS 和 Windows 系统中生效。
-
-- `MINERU_PROCESSING_WINDOW_SIZE`:
- * 用于设置单次处理窗口大小,影响大文档处理时的内存占用和吞吐表现
- * 默认为`64`,可通过环境变量设置为其他正整数。
-
-- `MINERU_API_MAX_CONCURRENT_REQUESTS`:
- * 用于设置 `mineru-api` 或 `mineru-router` 管理的 worker 最大并发请求数
- * 默认为`3`,需设置为正整数。
-
-- `MINERU_API_ENABLE_FASTAPI_DOCS`:
- * 用于控制是否启用 FastAPI 自动生成的 `/docs`、`/openapi.json`、`/redoc`
- * 默认为`true`。
-
-- `MINERU_API_OUTPUT_ROOT`:
- * 用于指定 `mineru-api` 输出目录根路径
- * 默认为当前工作目录下的 `./output`。
-
-- `MINERU_LOCAL_API_STARTUP_TIMEOUT_SECONDS`:
- * 用于控制各命令行工具等待本地拉起的 `mineru-api` 进入健康状态的最长时间
- * 默认为 `300` 秒。
- * 适用于 `mineru` 的临时本地 API、`mineru-gradio` 的 preload 启动,以及 `mineru-router` 托管的本地 worker。
-
-- `MINERU_TASK_RESULT_TIMEOUT_SECONDS`:
- * 用于控制客户端等待任务完成并进入终态的最长时间。
- * 默认为 `3600` 秒,需设置为大于等于 `1` 的数值。
- * 适用于 `mineru`、`mineru-gradio` 和 `mineru-router` 等通过 API 客户端轮询任务状态的场景。
-
-- `MINERU_TASK_RESULT_DOWNLOAD_TIMEOUT_SECONDS`:
- * 用于控制任务完成后获取结果的读取超时时间,包括服务端生成 ZIP 的等待和结果 ZIP 下载。
- * 默认为 `600` 秒,需设置为大于等于 `1` 的数值。
- * 该配置不代表整个下载过程的总耗时硬上限;如果服务端持续返回数据,整体下载时间可能超过该值。
-
-- `MINERU_API_TASK_RETENTION_SECONDS`:
- * 用于设置任务完成或失败后的保留时长(秒)
- * 默认为 `86400` 秒(24 小时)。
-
-- `MINERU_API_TASK_CLEANUP_INTERVAL_SECONDS`:
- * 用于设置任务清理轮询间隔(秒)
- * 默认为 `300` 秒(5 分钟)。
-
-- `MINERU_INTRA_OP_NUM_THREADS`:
- * 用于设置onnx模型的intra_op线程数,影响单个算子的计算速度
- * 默认为`-1`(自动选择),可通过环境变量设置为其他值以调整线程数。
-
-- `MINERU_INTER_OP_NUM_THREADS`:
- * 用于设置onnx模型的inter_op线程数,影响多个算子的并行执行
- * 默认为`-1`(自动选择),可通过环境变量设置为其他值以调整线程数。
-
-- `MINERU_HYBRID_BATCH_RATIO`:
- * 用于设置 hybrid-* 后端中 小模型处理的batch倍率
- * 在hybrid-http-client中较为常用,可以通过控制小模型的batch倍率来调整单个客户端的显存占用量
- * 单个client端显存大小 | MINERU_HYBRID_BATCH_RATIO
- ------------------|------------------------
- <= 6 GB | 8
- <= 4 GB | 4
- <= 3 GB | 2
- <= 2 GB | 1
-
-- `MINERU_VL_MODEL_NAME`:
- * 用于指定 vlm/hybrid 后端使用的模型名称,这将允许您在同时存在多个模型的远程openai-server中指定 MinerU 运行所需的模型。
-
-- `MINERU_VL_API_KEY`:
- * 用于指定 vlm/hybrid 后端使用的API Key,这将允许您在远程openai-server中进行身份验证。
+`mineru-router` 保留为 `mineru-kit router` 的命令名别名。Router 只暴露 V1 API,并且只接受文档中声明的 worker 参数。
+
+## 环境变量
+
+- `MINERU_HOME`:MinerU 配置、缓存和文档库状态的根目录。
+- `MINERU_CONFIG`:显式指定 `config.yaml` 路径。
+- `MINERU_MODEL_SOURCE`:模型源,例如 `huggingface`、`modelscope` 或 `local`。
+- `MINERU_API_URL` / `MINERU_API_KEY`:API 客户端默认使用的 V1 地址和 Bearer Key。
+- `MINERU_LOCAL_API_STARTUP_TIMEOUT_SECONDS`:Gradio 托管本地 V1 服务的启动超时,默认 `300` 秒。
+- `MINERU_API_ENABLE_FASTAPI_DOCS`:是否为 V1 API Server 启用 `/docs`、`/openapi.json` 和 `/redoc`,默认 `true`。
+- `MINERU_PDF_RENDER_TIMEOUT` / `MINERU_PDF_RENDER_THREADS`:PDF 渲染超时和 worker 数量。
+- `MINERU_PROCESSING_WINDOW_SIZE`:大文档处理窗口大小。
+- `MINERU_INTRA_OP_NUM_THREADS` / `MINERU_INTER_OP_NUM_THREADS`:ONNX 算子线程配置。
+
+当前默认值以各命令的 `--help` 和[模型源说明](./model_source.md)为准。
diff --git a/docs/zh/usage/index.md b/docs/zh/usage/index.md
index d5b2f313..a4db9749 100644
--- a/docs/zh/usage/index.md
+++ b/docs/zh/usage/index.md
@@ -37,7 +37,7 @@
## 开始使用
-自 3.0 起,`mineru` 默认作为基于 `mineru-api` 的编排客户端运行;`mineru-router` 的多服务、多 GPU 用法也会在本章的基础使用与命令行工具章节中说明。
+`mineru` 是面向交互和 Agent 工作流的文档库 CLI;无状态批处理、V1 API Server、Gradio、模型管理和多服务 Router 使用 `mineru-kit`。
建议按照上述顺序阅读文档,这样可以帮助您更好地理解和使用项目功能。
diff --git a/docs/zh/usage/plugin/Cherry_Studio.md b/docs/zh/usage/plugin/Cherry_Studio.md
index 5359856e..99cd8b58 100644
--- a/docs/zh/usage/plugin/Cherry_Studio.md
+++ b/docs/zh/usage/plugin/Cherry_Studio.md
@@ -191,7 +191,7 @@ https://example.com/doc3.pdf
### 无法启动 MCP 服务
-**问题**:运行 *`uv run -m mineru.cli_old`*` `时报错。
+**问题**:运行 *`uvx mineru-mcp`* 时无法启动 MCP 服务。
**解决方案**:
@@ -199,7 +199,7 @@ https://example.com/doc3.pdf
● 检查是否已安装所有依赖
-● 尝试使用 *`python -m mineru.cli_old`*` `命令替代
+● 重新运行 *`uvx mineru-mcp`* 并检查终端中的依赖安装与启动日志
### 文件转换失败
@@ -235,4 +235,4 @@ https://example.com/doc3.pdf
● 对于超时后无法再次调用的问题,需要重启 MCP 客户端
-● 如果反复出现超时,请检查网络连接或考虑使用本地 API 模式
\ No newline at end of file
+● 如果反复出现超时,请检查网络连接或考虑使用本地 API 模式
diff --git a/docs/zh/usage/quick_usage.md b/docs/zh/usage/quick_usage.md
index 198b3e08..e2a22d2c 100644
--- a/docs/zh/usage/quick_usage.md
+++ b/docs/zh/usage/quick_usage.md
@@ -10,13 +10,12 @@ export MINERU_MODEL_SOURCE=modelscope
## 通过命令行快速使用
MinerU内置了命令行工具,用户可以通过命令行快速使用MinerU进行文档解析:
```bash
-mineru -p <input_path> -o <output_path>
+mineru parse <input_path> --pages all -o <output_path>
```
> [!TIP]
-> - `<input_path>`:本地 `PDF` / `OFD` / `EPUB` / 静态 `HTML` / 图片 / `CSV` / `RTF` / `DOC`/`DOCX` / `PPT`/`PPTX` / `XLS`/`XLSX` / `ODT`/`ODS`/`ODP` 文件或目录
-> - `<output_path>`:输出目录
-> - 未传 `--api-url` 时,CLI 会自动拉起本地临时 `mineru-api`
-> - 传入 `--api-url` 时,CLI 会直连远端或已有本地 FastAPI 服务
+> - `<input_path>`:单个本地 `PDF` / `OFD` / `EPUB` / 静态 `HTML` / 图片 / `CSV` / `RTF` / `DOC`/`DOCX` / `PPT`/`PPTX` / `XLS`/`XLSX` / `ODT`/`ODS`/`ODP` 文件
+> - `<output_path>`:可选输出文件;未指定时 Markdown 写入标准输出
+> - PDF 默认解析前 10 页;使用 `--pages all` 解析整份文档
>
> 更多关于输出文件的信息,请参考[输出文件说明](../reference/output_files.md)。
@@ -26,65 +25,27 @@ mineru -p <input_path> -o <output_path>
如果需要通过自定义参数调整解析选项,您也可以在文档中查看更详细的[命令行工具使用说明](./cli_tools.md)。
-## 通过api、webui、http-client/server进阶使用
+## 通过 API、WebUI 和服务进阶使用
-- 通过fast api方式调用:
+- 启动自部署 V1 API:
```bash
- mineru-api --host 0.0.0.0 --port 8000
+ mineru-kit api-server --host 0.0.0.0 --port 8000 --tier standard
```
>[!TIP]
- >在浏览器中访问 `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`
- >- API 输出目录由服务端固定控制,默认写入 `./output`
- >- 上传文件当前支持 `PDF`、`OFD`、`EPUB`、`HTML`、图片、`CSV`、`RTF`、`DOC`/`DOCX`、`PPT`/`PPTX`、`XLS`/`XLSX`、`ODT`/`ODS`/`ODP`
- >
- >- `POST /tasks` 会立即返回 `task_id`;`POST /file_parse` 会在内部提交到同一个任务管理器,等待任务完成后同步返回最终结果。
- >- 当任务处于排队状态时,任务提交结果和状态查询结果中可能会返回 `queued_ahead` 字段,用于表示前方排队任务数。
- >- 任务为单进程、进程内状态实现,服务重启、`--reload` 热重载或多进程部署后不保证仍可查询历史任务状态。
- >- 默认任务完成或失败后保留 24 小时,随后自动清理任务状态和输出目录;清理后访问任务状态或结果会返回 `404`。
- >- 可通过环境变量 `MINERU_API_TASK_RETENTION_SECONDS` 和 `MINERU_API_TASK_CLEANUP_INTERVAL_SECONDS` 调整保留时长与清理轮询间隔。
- >- 可通过 `--enable-vlm-preload true` 在服务启动阶段预热本地 VLM 模型,避免首次 VLM 或 hybrid 请求时再初始化。
- >
- >异步任务提交示例:
- >```bash
- >curl -X POST http://127.0.0.1:8000/tasks \
- > -F "files=@demo/pdfs/demo1.pdf" \
- > -F "return_md=true"
- >```
- >
- >同步解析示例:
- >```bash
- >curl -X POST http://127.0.0.1:8000/file_parse \
- > -F "files=@demo/pdfs/demo1.pdf" \
- > -F "return_md=true" \
- > -F "response_format_zip=true" \
- > -F "return_original_file=true"
- >```
- >
- >轮询任务状态与结果:
- >```bash
- >curl http://127.0.0.1:8000/tasks/<task_id>
- >curl http://127.0.0.1:8000/tasks/<task_id>/result
- >curl http://127.0.0.1:8000/health
- >```
+ >在浏览器中访问 `http://127.0.0.1:8000/docs` 查看 OpenAPI 文档。服务只提供 `/v1/*` 接口,包括健康检查、能力发现、上传、文件、解析任务和用量查询。
>
>http异步调用代码示例:[Python版本](https://github.com/opendatalab/MinerU/blob/master/demo/demo.py)
- 启动gradio webui 可视化前端:
```bash
- mineru-gradio --server-name 0.0.0.0 --server-port 7860
+ mineru-kit gradio --server-name 0.0.0.0 --server-port 7860
```
>[!TIP]
>
>- 在浏览器中访问 `http://127.0.0.1:7860` 使用 Gradio WebUI。
- >- 未传 `--api-url` 时,Gradio 会自动拉起可复用的本地 `mineru-api`;传入 `--api-url` 时则会复用已有本地或远端服务。
- >- `--enable-vlm-preload true` 会让 Gradio 在 WebUI 启动阶段主动拉起本地 `mineru-api` 并等待 VLM 预加载完成;传入 `--api-url` 时会被忽略。
- >- WebUI 当前支持上传 `PDF`、图片与 `DOCX`、`PPTX`、`XLSX` 文件。
+ >- 未传 `--api-url` 时,Gradio 会托管 loopback `mineru-kit api-server`;传入后只连接指定的 V1 服务。
+ >- 使用 `--api-server-preload-models` 为托管的本地服务预加载模型。
+ >- `mineru-gradio` 仍作为命令名兼容别名,使用相同的新版参数。
- 通过 `mineru-router` 进行多服务 / 多 GPU 编排:
```bash
@@ -92,24 +53,16 @@ mineru -p <input_path> -o <output_path>
```
>[!TIP]
>
- >- `mineru-router` 与 `mineru-kit router` 都只暴露完整 `/v1/*` API,不再提供 `/tasks` 或 `/file_parse`。
+ >- `mineru-router` 与 `mineru-kit router` 都只暴露完整 `/v1/*` API。
>- 可重复使用 `--upstream-url` 聚合多个 V1 api-server,也可通过 `--local-gpus` 自动拉起 `mineru-kit api-server` worker。
>- `--preload-models` 只作用于 Router 托管的本地 worker,远端 upstream 保持自己的启动配置。
>- Router 不再透传未知模型引擎参数。
>- 适用于多服务、多 GPU 和统一入口部署场景。
-- 使用`http-client/server`方式调用:
+- 启动 OpenAI 兼容 VLM 服务:
```bash
- # 启动openai兼容服务器(需要安装vllm或lmdeploy环境)
- mineru-openai-server --port 30000
- ```
- >[!TIP]
- >在另一个终端中通过http client连接openai server
- > ```bash
- > mineru -p <input_path> -o <output_path> -b hybrid-http-client -u http://127.0.0.1:30000
- > ```
- >`hybrid-http-client` 需要本地具备 `mineru[pipeline]` 及 `torch` 等 pipeline 依赖。
- >兼容旧输入 `vlm-http-client`,但会映射为 `hybrid-http-client` 且使用 `--effort high`。
+ mineru-kit vlm-server --engine auto --port 30000
+ ```
> [!NOTE]
> 模型引擎参数只适用于显式声明它们的命令;`mineru-router` 仅接受文档列出的 Router/worker 参数,不透传未知参数。
@@ -141,10 +94,15 @@ llm_aided:
## 基于配置文件扩展 MinerU 功能
-MinerU 现已实现开箱即用,但也支持通过配置文件扩展功能。LaTeX 分隔符、LLM 辅助标题分级等旧工具配置仍使用用户目录下的 `mineru.json`。模型存储目录和模型源配置使用 `config.yaml`,详见[模型源说明](./model_source.md)。
+MinerU 可开箱即用,并从 `$MINERU_HOME/config.yaml` 读取当前配置;可通过 `MINERU_CONFIG` 指定其他配置文件。旧 `mineru.json` CLI 配置不再支持,Gradio 的 LaTeX 分隔符通过 `--latex-delimiters-type` 选择。
+
+模型目录和模型源使用 `model` 配置段:
-以下是一些可用的配置选项:
+```yaml
+model:
+ base_dir: ~/.mineru/models
+ source: auto
+ stack: auto
+```
-- `models-dir`:
- * 用于指定本地模型存储目录,请分别指定本地小模型 bundle(`models-dir.pipeline`)和 VLM bundle(`models-dir.vlm`)的模型目录,
- * 指定目录后您可通过配置环境变量`export MINERU_MODEL_SOURCE=local`来使用本地模型。
+模型下载和本地模型源的详细说明见[模型源说明](./model_source.md)。
diff --git a/mineru/cli_old/__init__.py b/mineru/cli_old/__init__.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/cli_old/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/cli_old/api_client.py b/mineru/cli_old/api_client.py
deleted file mode 100644
index 5132ea51..00000000
--- a/mineru/cli_old/api_client.py
+++ /dev/null
@@ -1,1021 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import asyncio
-import atexit
-import json
-import mimetypes
-import multiprocessing
-import os
-import platform
-import signal
-import socket
-import subprocess
-import sys
-import tempfile
-import threading
-import time
-import zipfile
-from contextlib import ExitStack
-from dataclasses import dataclass
-from pathlib import Path, PurePosixPath
-from typing import Any, Callable, Optional, Sequence
-
-import click
-import httpx
-from loguru import logger
-
-from mineru.utils.backend_options import DEFAULT_HYBRID_EFFORT
-
-from mineru.cli_old.api_protocol import (
- API_PROTOCOL_VERSION,
- DEFAULT_MAX_CONCURRENT_REQUESTS,
-)
-from mineru.utils.check_sys_env import is_linux_environment
-from mineru.utils.config_reader import (
- get_max_concurrent_requests as read_max_concurrent_requests,
-)
-
-HEALTH_ENDPOINT = "/health"
-TASKS_ENDPOINT = "/tasks"
-TASK_STATUS_POLL_INTERVAL_SECONDS = 1.0
-LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS = 10
-LOCAL_API_CLEANUP_RETRIES = 8
-LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS = 0.25
-PROCESS_TREE_CLEANUP_GRACE_SECONDS = 0.1
-MINERU_LOCAL_API_LAUNCH_MODE_ENV = "MINERU_LOCAL_API_LAUNCH_MODE"
-MINERU_LMDEPLOY_DEVICE_ENV = "MINERU_LMDEPLOY_DEVICE"
-LOCAL_API_LAUNCH_MODE_SUBPROCESS = "subprocess"
-LOCAL_API_LAUNCH_MODE_SPAWN = "spawn"
-MINERU_SPAWN_DEVICE_LIST = ["ascend"]
-
-ManagedProcess = subprocess.Popen[bytes] | multiprocessing.process.BaseProcess
-
-
-def get_float_env(name: str, default: float, minimum: float = 0.0) -> float:
- value = os.getenv(name)
- if value is None:
- return default
- try:
- resolved = float(value)
- except ValueError:
- logger.warning(
- "Invalid {} value: {}. Expected a number, using default {}.",
- name,
- value,
- default,
- )
- return default
- if resolved < minimum:
- logger.warning(
- "Invalid {} value: {}. Expected a number >= {}, using default {}.",
- name,
- value,
- minimum,
- default,
- )
- return default
- return resolved
-
-
-def get_local_api_startup_timeout_seconds(default: float = 300.0) -> float:
- return get_float_env(
- "MINERU_LOCAL_API_STARTUP_TIMEOUT_SECONDS",
- default,
- minimum=1.0,
- )
-
-
-LOCAL_API_STARTUP_TIMEOUT_SECONDS = get_local_api_startup_timeout_seconds()
-
-
-def get_task_result_timeout_seconds(default: float = 3600.0) -> float:
- return get_float_env(
- "MINERU_TASK_RESULT_TIMEOUT_SECONDS",
- default,
- minimum=1.0,
- )
-
-
-TASK_RESULT_TIMEOUT_SECONDS = get_task_result_timeout_seconds()
-
-
-def get_task_result_download_timeout_seconds(default: float = 600.0) -> float:
- """读取任务结果下载超时时间,避免和任务处理等待超时混用。"""
- return get_float_env(
- "MINERU_TASK_RESULT_DOWNLOAD_TIMEOUT_SECONDS",
- default,
- minimum=1.0,
- )
-
-
-TASK_RESULT_DOWNLOAD_TIMEOUT_SECONDS = get_task_result_download_timeout_seconds()
-
-
-def get_local_api_launch_mode(default: str = LOCAL_API_LAUNCH_MODE_SUBPROCESS) -> str:
- value = os.getenv(MINERU_LOCAL_API_LAUNCH_MODE_ENV)
- if value is None:
- return default
-
- normalized = value.strip().lower()
- if normalized in {
- LOCAL_API_LAUNCH_MODE_SUBPROCESS,
- LOCAL_API_LAUNCH_MODE_SPAWN,
- }:
- return normalized
-
- logger.warning(
- "Invalid {} value: {}. Expected one of ({}, {}), using default {}.",
- MINERU_LOCAL_API_LAUNCH_MODE_ENV,
- value,
- LOCAL_API_LAUNCH_MODE_SUBPROCESS,
- LOCAL_API_LAUNCH_MODE_SPAWN,
- default,
- )
- return default
-
-
-def get_effective_local_api_launch_mode(
- default: str = LOCAL_API_LAUNCH_MODE_SUBPROCESS,
-) -> str:
- if os.getenv(MINERU_LOCAL_API_LAUNCH_MODE_ENV) is not None:
- return get_local_api_launch_mode(default=default)
-
- device_type = os.getenv(MINERU_LMDEPLOY_DEVICE_ENV, "")
- if device_type.strip().lower() in MINERU_SPAWN_DEVICE_LIST:
- return LOCAL_API_LAUNCH_MODE_SPAWN
-
- return default
-
-
-def build_managed_process_popen_kwargs() -> dict[str, Any]:
- if os.name == "nt":
- creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
- if creationflags:
- return {"creationflags": creationflags}
- return {}
- return {"start_new_session": True}
-
-
-def _signal_process_tree_pid(process_group_id: int, *, force: bool) -> None:
- if process_group_id <= 0:
- return
-
- if os.name == "nt":
- command = ["taskkill", "/PID", str(process_group_id), "/T"]
- if force:
- command.append("/F")
- try:
- subprocess.run(
- command,
- check=False,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- )
- except Exception as exc:
- logger.debug(
- "Failed to signal managed MinerU process tree {} on Windows: {}",
- process_group_id,
- exc,
- )
- return
-
- sig = signal.SIGKILL if force else signal.SIGTERM
- try:
- os.killpg(process_group_id, sig)
- except ProcessLookupError:
- return
- except OSError as exc:
- logger.debug(
- "Failed to signal managed MinerU process group {}: {}",
- process_group_id,
- exc,
- )
-
-
-def _signal_process_tree(process: subprocess.Popen[bytes], *, force: bool) -> None:
- _signal_process_tree_pid(process.pid, force=force)
-
-
-def cleanup_process_tree_descendants_by_pid(
- process_group_id: int | None,
- *,
- grace_seconds: float = PROCESS_TREE_CLEANUP_GRACE_SECONDS,
-) -> None:
- if os.name == "nt" or process_group_id is None:
- return
-
- _signal_process_tree_pid(process_group_id, force=False)
- if grace_seconds > 0:
- time.sleep(grace_seconds)
- _signal_process_tree_pid(process_group_id, force=True)
-
-
-def cleanup_process_tree_descendants(
- process: subprocess.Popen[bytes],
- *,
- grace_seconds: float = PROCESS_TREE_CLEANUP_GRACE_SECONDS,
-) -> None:
- cleanup_process_tree_descendants_by_pid(
- process.pid,
- grace_seconds=grace_seconds,
- )
-
-
-def stop_managed_process(
- process: subprocess.Popen[bytes] | None,
- *,
- process_group_id: int | None = None,
- shutdown_timeout_seconds: float,
- use_stdin_shutdown_watcher: bool,
-) -> None:
- if process is None and process_group_id is None:
- return
-
- if process is None:
- cleanup_process_tree_descendants_by_pid(process_group_id)
- return
-
- resolved_process_group_id = process_group_id if process_group_id is not None else process.pid
- was_running_at_entry = process.poll() is None
- exited_via_stdin_eof = False
- tree_signaled = False
-
- if not was_running_at_entry:
- cleanup_process_tree_descendants_by_pid(process_group_id)
- return
-
- if use_stdin_shutdown_watcher:
- if process.stdin is not None and not process.stdin.closed:
- process.stdin.close()
- try:
- process.wait(timeout=shutdown_timeout_seconds)
- exited_via_stdin_eof = True
- except subprocess.TimeoutExpired:
- logger.debug(
- "Managed MinerU process did not stop after stdin EOF within {}s. Falling back to process-tree termination.",
- shutdown_timeout_seconds,
- )
-
- if process.poll() is None:
- _signal_process_tree_pid(resolved_process_group_id, force=False)
- tree_signaled = True
- try:
- process.wait(timeout=shutdown_timeout_seconds)
- except subprocess.TimeoutExpired:
- pass
-
- if process.poll() is None:
- _signal_process_tree_pid(resolved_process_group_id, force=True)
- tree_signaled = True
- try:
- process.wait(timeout=shutdown_timeout_seconds)
- except subprocess.TimeoutExpired:
- logger.warning(
- "Managed MinerU process {} did not exit after forceful stop.",
- process.pid,
- )
-
- if exited_via_stdin_eof and not tree_signaled:
- cleanup_process_tree_descendants_by_pid(resolved_process_group_id)
-
-
-def _managed_process_exit_code(process: ManagedProcess | None) -> int | None:
- if process is None:
- return None
- if isinstance(process, subprocess.Popen):
- return process.poll()
- return process.exitcode
-
-
-def _managed_process_pid(process: ManagedProcess | None) -> int | None:
- if process is None:
- return None
- return process.pid
-
-
-def _managed_process_is_running(process: ManagedProcess | None) -> bool:
- return process is not None and _managed_process_exit_code(process) is None
-
-
-def _validate_local_api_launch_mode_platform(launch_mode: str) -> None:
- if launch_mode != LOCAL_API_LAUNCH_MODE_SPAWN or is_linux_environment():
- return
-
- current_platform = platform.system() or os.name
- raise click.ClickException(
- f"{MINERU_LOCAL_API_LAUNCH_MODE_ENV}=spawn is supported only on Linux. "
- f"Current platform: {current_platform}. Unset "
- f"{MINERU_LOCAL_API_LAUNCH_MODE_ENV} or set "
- f"{MINERU_LOCAL_API_LAUNCH_MODE_ENV}={LOCAL_API_LAUNCH_MODE_SUBPROCESS}."
- )
-
-
-def _stop_spawn_managed_process(
- process: multiprocessing.process.BaseProcess | None,
- *,
- process_group_id: int | None,
- shutdown_timeout_seconds: float,
-) -> None:
- if process is None and process_group_id is None:
- return
-
- if process_group_id is None:
- if process is None or process.exitcode is not None:
- return
-
- process.terminate()
- process.join(timeout=shutdown_timeout_seconds)
-
- if process.exitcode is not None:
- return
-
- process.kill()
- process.join(timeout=shutdown_timeout_seconds)
-
- if process.exitcode is None:
- logger.warning(
- "Managed MinerU spawn process {} did not exit after forceful stop.",
- process.pid,
- )
- return
-
- if process is not None and process.exitcode is None:
- process.terminate()
- process.join(timeout=shutdown_timeout_seconds)
-
- cleanup_process_tree_descendants_by_pid(process_group_id)
-
- if process is not None:
- process.join(timeout=shutdown_timeout_seconds)
- if process.exitcode is None:
- logger.warning(
- "Managed MinerU spawn process {} did not exit after forceful stop.",
- process.pid,
- )
-
-
-def _build_local_api_server_cli_args(
- resolved_port: int,
- extra_cli_args: Sequence[str],
-) -> tuple[str, ...]:
- remaining_cli_args = strip_local_api_network_args(extra_cli_args)
- return (
- "--host",
- "127.0.0.1",
- "--port",
- str(resolved_port),
- *remaining_cli_args,
- )
-
-
-def _cli_args_include_flag(cli_args: Sequence[str], flag: str) -> bool:
- return flag in cli_args or any(arg.startswith(f"{flag}=") for arg in cli_args)
-
-
-def _validate_local_api_launch_mode_cli_args(
- launch_mode: str,
- cli_args: Sequence[str],
-) -> None:
- if launch_mode == LOCAL_API_LAUNCH_MODE_SPAWN and _cli_args_include_flag(cli_args, "--reload"):
- raise click.ClickException(
- "Local mineru-api spawn launch mode does not support --reload. "
- "Remove --reload or set MINERU_LOCAL_API_LAUNCH_MODE=subprocess."
- )
-
-
-def _build_local_api_server_env(
- output_root: Path,
- *,
- use_stdin_shutdown_watcher: bool,
-) -> tuple[dict[str, str], tuple[str, ...]]:
- env = os.environ.copy()
- env["MINERU_API_OUTPUT_ROOT"] = str(output_root)
- env["MINERU_API_MAX_CONCURRENT_REQUESTS"] = str(read_max_concurrent_requests(default=DEFAULT_MAX_CONCURRENT_REQUESTS))
- env["MINERU_API_DISABLE_ACCESS_LOG"] = "1"
-
- unset_env_names: list[str] = []
- if use_stdin_shutdown_watcher:
- env["MINERU_API_SHUTDOWN_ON_STDIN_EOF"] = "1"
- else:
- env.pop("MINERU_API_SHUTDOWN_ON_STDIN_EOF", None)
- unset_env_names.append("MINERU_API_SHUTDOWN_ON_STDIN_EOF")
-
- return env, tuple(unset_env_names)
-
-
-def _run_local_api_via_spawn(
- *,
- cwd: str,
- env_overrides: dict[str, str],
- unset_env_names: Sequence[str],
- cli_args: Sequence[str],
-) -> None:
- for name in unset_env_names:
- os.environ.pop(name, None)
- os.environ.update(env_overrides)
- os.chdir(cwd)
- sys.argv = ["mineru-api", *cli_args]
-
- try:
- os.setsid()
- except OSError as exc:
- logger.warning(
- "Failed to create a dedicated process group for spawned mineru-api: {}",
- exc,
- )
-
- from mineru.cli_old.fast_api import main as fast_api_main
-
- fast_api_main.main(
- args=list(cli_args),
- prog_name="mineru-api",
- standalone_mode=False,
- )
-
-
-@dataclass(frozen=True)
-class UploadAsset:
- path: Path
- upload_name: str
-
-
-@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
- file_names: tuple[str, ...] = ()
- queued_ahead: int | None = None
-
-
-@dataclass(frozen=True)
-class TaskStatusSnapshot:
- status: str
- queued_ahead: int | None = None
-
-
-class LocalAPIServer:
- def __init__(self, extra_cli_args: Sequence[str] = ()):
- 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.base_url: str | None = None
- self.process: ManagedProcess | None = None
- self._atexit_registered = False
- self.extra_cli_args = tuple(extra_cli_args)
- self._launch_mode = LOCAL_API_LAUNCH_MODE_SUBPROCESS
- self._managed_process_group_id: int | None = None
- self._use_stdin_shutdown_watcher = False
-
- def start(self) -> str:
- if self.process is not None:
- raise RuntimeError("Local API server is already running")
-
- resolved_port = find_free_port()
- self.base_url = f"http://127.0.0.1:{resolved_port}"
- self._launch_mode = get_effective_local_api_launch_mode()
- _validate_local_api_launch_mode_platform(self._launch_mode)
- # On Windows, the temporary FastAPI child process can stall during
- # parsing startup when launched with stdin=PIPE and an EOF-based
- # shutdown watcher, so we only enable that path on non-Windows
- # subprocess launches.
- self._use_stdin_shutdown_watcher = self._launch_mode == LOCAL_API_LAUNCH_MODE_SUBPROCESS and os.name != "nt"
- env, unset_env_names = _build_local_api_server_env(
- self.output_root,
- use_stdin_shutdown_watcher=self._use_stdin_shutdown_watcher,
- )
- if self._launch_mode == LOCAL_API_LAUNCH_MODE_SUBPROCESS:
- stdin_target = subprocess.PIPE
- else:
- stdin_target = subprocess.DEVNULL
- self.output_root.mkdir(parents=True, exist_ok=True)
-
- cli_args = _build_local_api_server_cli_args(
- resolved_port,
- self.extra_cli_args,
- )
- _validate_local_api_launch_mode_cli_args(self._launch_mode, cli_args)
- if self._launch_mode == LOCAL_API_LAUNCH_MODE_SUBPROCESS:
- command = [
- sys.executable,
- "-m",
- "mineru.cli_old.fast_api",
- *cli_args,
- ]
- self.process = subprocess.Popen(
- command,
- cwd=os.getcwd(),
- env=env,
- stdin=stdin_target,
- **build_managed_process_popen_kwargs(),
- )
- self._managed_process_group_id = _managed_process_pid(self.process)
- else:
- spawn_context = multiprocessing.get_context("spawn")
- process = spawn_context.Process(
- target=_run_local_api_via_spawn,
- kwargs={
- "cwd": os.getcwd(),
- "env_overrides": env,
- "unset_env_names": unset_env_names,
- "cli_args": cli_args,
- },
- )
- process.start()
- self.process = process
- # `start_new_session=True` makes the managed subprocess pid usable as
- # the process-group id. The spawn runner establishes the same shape
- # via `setsid()`, so we retain the initial child pid as the stable
- # process-group id for later tree cleanup even if the leader exits.
- self._managed_process_group_id = _managed_process_pid(process)
-
- if not self._atexit_registered:
- atexit.register(self.stop)
- self._atexit_registered = True
- return self.base_url
-
- def stop(self) -> None:
- process = self.process
- managed_process_group_id = self._managed_process_group_id
- self.process = None
- self._managed_process_group_id = None
- try:
- if self._launch_mode == LOCAL_API_LAUNCH_MODE_SUBPROCESS:
- stop_managed_process(
- process,
- process_group_id=managed_process_group_id,
- shutdown_timeout_seconds=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS,
- use_stdin_shutdown_watcher=self._use_stdin_shutdown_watcher,
- )
- else:
- _stop_spawn_managed_process(
- process if process is not None else None,
- process_group_id=managed_process_group_id,
- shutdown_timeout_seconds=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS,
- )
- finally:
- if self._atexit_registered:
- try:
- atexit.unregister(self.stop)
- except Exception:
- pass
- self._atexit_registered = False
- self._cleanup_temp_dir()
-
- def _cleanup_temp_dir(self) -> None:
- last_error: Exception | None = None
- for attempt in range(LOCAL_API_CLEANUP_RETRIES):
- try:
- self.temp_dir.cleanup()
- return
- except FileNotFoundError:
- return
- except Exception as exc:
- last_error = exc
- if attempt + 1 < LOCAL_API_CLEANUP_RETRIES:
- time.sleep(LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS)
-
- if last_error is not None:
- logger.warning(
- "Failed to clean up temporary MinerU API directory {}: {}. "
- "You can remove it manually after processes release any open handles.",
- self.temp_root,
- last_error,
- )
-
-
-class ReusableLocalAPIServer:
- def __init__(self, extra_cli_args: Sequence[str] = ()):
- self._lock = threading.Lock()
- self._server: LocalAPIServer | None = None
- self._extra_cli_args = tuple(extra_cli_args)
-
- def configure(self, extra_cli_args: Sequence[str]) -> None:
- with self._lock:
- self._extra_cli_args = tuple(extra_cli_args)
- server = self._server
- if server is None:
- return
- if _managed_process_is_running(server.process):
- return
- server.stop()
- self._server = None
-
- def ensure_started(self) -> tuple[LocalAPIServer, bool]:
- with self._lock:
- server = self._server
- if server is not None and _managed_process_is_running(server.process):
- return server, False
-
- if server is not None:
- server.stop()
-
- server = LocalAPIServer(extra_cli_args=self._extra_cli_args)
- server.start()
- self._server = server
- return server, True
-
- def stop(self) -> None:
- with self._lock:
- server = self._server
- self._server = None
- if server is not None:
- server.stop()
-
-
-def build_http_timeout() -> httpx.Timeout:
- return httpx.Timeout(connect=10, read=60, write=300, pool=30)
-
-
-def build_result_download_timeout() -> httpx.Timeout:
- return httpx.Timeout(
- connect=10,
- read=TASK_RESULT_DOWNLOAD_TIMEOUT_SECONDS,
- write=300,
- pool=30,
- )
-
-
-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 strip_local_api_network_args(extra_cli_args: Sequence[str]) -> tuple[str, ...]:
- remaining_args: list[str] = []
- i = 0
-
- while i < len(extra_cli_args):
- arg = extra_cli_args[i]
- if arg == "--host":
- next_index = i + 1
- if next_index < len(extra_cli_args) and not extra_cli_args[next_index].startswith("--"):
- i += 2
- else:
- i += 1
- continue
-
- if arg == "--port":
- next_index = i + 1
- if next_index < len(extra_cli_args) and not extra_cli_args[next_index].startswith("--"):
- i += 2
- else:
- i += 1
- continue
-
- if arg.startswith("--host="):
- i += 1
- continue
-
- if arg.startswith("--port="):
- i += 1
- continue
-
- remaining_args.append(arg)
- i += 1
-
- return tuple(remaining_args)
-
-
-def normalize_base_url(url: str) -> str:
- return url.rstrip("/")
-
-
-def resolve_effective_max_concurrent_requests(
- local_max: int,
- server_max: int,
-) -> int:
- if local_max <= 0 or server_max <= 0:
- raise ValueError("local_max and server_max must both be positive integers")
- return min(local_max, server_max)
-
-
-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}, 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) or max_concurrent_requests <= 0:
- raise click.ClickException(f"MinerU API at {base_url} did not return a valid positive 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}: {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 _managed_process_exit_code(process) is not None:
- if local_server._launch_mode == LOCAL_API_LAUNCH_MODE_SPAWN:
- local_server.stop()
- raise click.ClickException("Local mineru-api exited before becoming healthy.")
- 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)
-
- message = "Timed out waiting for local mineru-api to become healthy."
- if last_error:
- message = f"{message} {last_error}"
- raise click.ClickException(message)
-
-
-def build_parse_request_form_data(
- lang_list: Sequence[str],
- backend: str,
- parse_method: str,
- server_url: Optional[str],
- start_page_id: int,
- end_page_id: Optional[int],
- *,
- image_analysis: bool = True,
- effort: str = DEFAULT_HYBRID_EFFORT,
- return_md: bool,
- return_middle_json: bool,
- return_model_output: bool,
- return_content_list: bool,
- return_images: bool,
- response_format_zip: bool,
- return_original_file: bool,
- client_side_output_generation: bool = False,
-) -> dict[str, str | list[str]]:
- effective_lang_list = list(lang_list) or ["ch"]
- data: dict[str, str | list[str]] = {
- "lang_list": effective_lang_list,
- "backend": backend,
- "parse_method": parse_method,
- "effort": effort,
- "image_analysis": str(image_analysis).lower(),
- "return_md": str(return_md).lower(),
- "return_middle_json": str(return_middle_json).lower(),
- "return_model_output": str(return_model_output).lower(),
- "return_content_list": str(return_content_list).lower(),
- "return_images": str(return_images).lower(),
- "response_format_zip": str(response_format_zip).lower(),
- "return_original_file": str(return_original_file).lower(),
- "client_side_output_generation": str(client_side_output_generation).lower(),
- "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
-
-
-async def submit_parse_task(
- base_url: str,
- upload_assets: Sequence[UploadAsset],
- form_data: dict[str, str | list[str]],
-) -> SubmitResponse:
- return await asyncio.to_thread(
- submit_parse_task_sync,
- base_url,
- upload_assets,
- form_data,
- )
-
-
-def submit_parse_task_sync(
- base_url: str,
- upload_assets: Sequence[UploadAsset],
- form_data: dict[str, str | list[str]],
-) -> SubmitResponse:
- task_url = f"{base_url}{TASKS_ENDPOINT}"
- try:
- with httpx.Client(timeout=build_http_timeout(), follow_redirects=True) as sync_client:
- with ExitStack() as stack:
- files = []
- for upload_asset in upload_assets:
- mime_type = mimetypes.guess_type(upload_asset.upload_name)[0] or "application/octet-stream"
- file_handle = stack.enter_context(open(upload_asset.path, "rb"))
- files.append(
- (
- "files",
- (
- upload_asset.upload_name,
- file_handle,
- mime_type,
- ),
- )
- )
-
- response = sync_client.post(
- task_url,
- data=form_data,
- files=files,
- )
- except httpx.TimeoutException as exc:
- raise click.ClickException(
- f"Timed out submitting parsing task to {task_url}. The server may still be starting up or initializing the model."
- ) from exc
-
- if response.status_code != 202:
- raise click.ClickException(f"Failed to submit parsing task: {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")
- file_names = payload.get("file_names")
- queued_ahead = payload.get("queued_ahead")
- if not isinstance(task_id, str) or not isinstance(status_url, str) or not isinstance(result_url, str):
- raise click.ClickException("MinerU API returned an invalid task payload")
-
- normalized_file_names: tuple[str, ...] = ()
- if isinstance(file_names, list) and all(isinstance(name, str) for name in file_names):
- normalized_file_names = tuple(file_names)
- if not isinstance(queued_ahead, int):
- queued_ahead = None
-
- return SubmitResponse(
- task_id=task_id,
- status_url=status_url,
- result_url=result_url,
- file_names=normalized_file_names,
- queued_ahead=queued_ahead,
- )
-
-
-async def wait_for_task_result(
- client: httpx.AsyncClient,
- submit_response: SubmitResponse,
- task_label: str,
- *,
- status_callback: Optional[Callable[[str], None]] = None,
- status_snapshot_callback: Optional[Callable[[TaskStatusSnapshot], None]] = None,
- timeout_seconds: float = TASK_RESULT_TIMEOUT_SECONDS,
-) -> None:
- deadline = asyncio.get_running_loop().time() + timeout_seconds
- while asyncio.get_running_loop().time() < deadline:
- try:
- response = await client.get(submit_response.status_url)
- except httpx.ReadTimeout:
- logger.warning(
- "Timed out while polling task status for {} (task_id={}). "
- "This can happen during cold start; retrying until the task deadline.",
- task_label,
- submit_response.task_id,
- )
- await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
- continue
- if response.status_code != 200:
- raise click.ClickException(
- f"Failed to query task status for {task_label}: {response.status_code} {response_detail(response)}"
- )
-
- payload = response.json()
- status = payload.get("status")
- if status in {"pending", "processing"}:
- queued_ahead = payload.get("queued_ahead")
- if not isinstance(queued_ahead, int):
- queued_ahead = None
- if status_snapshot_callback is not None:
- status_snapshot_callback(
- TaskStatusSnapshot(
- status=status,
- queued_ahead=queued_ahead,
- )
- )
- if status_callback is not None:
- status_callback(status)
- await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
- continue
- if status == "completed":
- return
- raise click.ClickException(
- f"Task {submit_response.task_id} failed for {task_label}: {json.dumps(payload, ensure_ascii=False)}"
- )
-
- raise click.ClickException(f"Timed out waiting for result of task {submit_response.task_id} for {task_label}")
-
-
-async def download_result_zip(
- client: httpx.AsyncClient,
- submit_response: SubmitResponse,
- task_label: str,
-) -> Path:
- zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_cli_result_")
- os.close(zip_fd)
- zip_file_path = Path(zip_path)
- try:
- async with client.stream(
- "GET",
- submit_response.result_url,
- timeout=build_result_download_timeout(),
- ) as response:
- if response.status_code != 200:
- await response.aread()
- 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 {task_label}, got content-type={content_type or 'unknown'}"
- )
-
- with open(zip_file_path, "wb") as handle:
- async for chunk in response.aiter_bytes():
- handle.write(chunk)
- except click.ClickException:
- zip_file_path.unlink(missing_ok=True)
- raise
- except httpx.TimeoutException as exc:
- zip_file_path.unlink(missing_ok=True)
- raise click.ClickException(
- f"Timed out downloading result ZIP for task {submit_response.task_id} for {task_label}"
- ) from exc
- except asyncio.CancelledError:
- zip_file_path.unlink(missing_ok=True)
- raise
- except Exception:
- zip_file_path.unlink(missing_ok=True)
- raise
- return zip_file_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())
diff --git a/mineru/cli_old/api_protocol.py b/mineru/cli_old/api_protocol.py
deleted file mode 100644
index 25f2e57d..00000000
--- a/mineru/cli_old/api_protocol.py
+++ /dev/null
@@ -1,4 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-API_PROTOCOL_VERSION = 2
-DEFAULT_MAX_CONCURRENT_REQUESTS = 3
-DEFAULT_PROCESSING_WINDOW_SIZE = 64
diff --git a/mineru/cli_old/api_request.py b/mineru/cli_old/api_request.py
deleted file mode 100644
index 9b223000..00000000
--- a/mineru/cli_old/api_request.py
+++ /dev/null
@@ -1,263 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from dataclasses import dataclass
-from typing import Annotated, Optional
-
-from fastapi import File, Form, HTTPException, Request, UploadFile
-
-from mineru.cli_old.public_http_client_policy import validate_public_http_client_request
-from mineru.utils.backend_options import (
- BACKEND_SCHEMA_EXTRA,
- DEFAULT_BACKEND,
- DEFAULT_HYBRID_EFFORT,
- HYBRID_EFFORT_SCHEMA_EXTRA,
- LEGACY_PIPELINE_BACKEND_ALIASES,
- LEGACY_VLM_BACKEND_ALIASES,
- normalize_public_backend,
- resolve_backend_and_effort,
- validate_effort,
-)
-from mineru.utils.ocr_language import (
- PUBLIC_OCR_LANGUAGE_SCHEMA_EXTRA,
- format_public_ocr_lang_description,
- validate_public_ocr_lang_list,
-)
-
-ALLOWED_PARSE_METHODS = {"auto", "txt", "ocr"}
-SWAGGER_UI_FILE_ARRAY_SCHEMA_EXTRA = {
- # Swagger UI 5 currently fails to render a usable multi-file picker when
- # FastAPI emits OpenAPI 3.1 byte arrays with contentMediaType.
- "items": {"type": "string", "format": "binary"}
-}
-
-
-@dataclass
-class ParseRequestOptions:
- """保存公开解析接口共用的表单参数,供 API 与 Router 复用。"""
-
- files: list[UploadFile]
- lang_list: list[str]
- backend: str
- effort: str
- parse_method: str
- image_analysis: bool
- server_url: Optional[str]
- return_md: bool
- return_middle_json: bool
- return_model_output: bool
- return_content_list: bool
- return_images: bool
- response_format_zip: bool
- return_original_file: bool
- client_side_output_generation: bool
- start_page_id: int
- end_page_id: int
-
-
-def validate_parse_method(parse_method: str) -> str:
- """校验公开 API 允许的 PDF 解析方式,避免各入口维护不同规则。"""
- if parse_method not in ALLOWED_PARSE_METHODS:
- raise HTTPException(
- status_code=400,
- detail=(
- "Invalid parse_method. Allowed values: "
- + ", ".join(sorted(ALLOWED_PARSE_METHODS))
- ),
- )
- return parse_method
-
-
-def validate_parse_backend(backend: str) -> str:
- """校验公开 API 允许的解析后端,保留 hidden alias 供联合解析决定 effort。"""
- try:
- normalized_backend = normalize_public_backend(backend)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
- raw_backend = (backend or "").strip()
- if raw_backend in LEGACY_PIPELINE_BACKEND_ALIASES or raw_backend in LEGACY_VLM_BACKEND_ALIASES:
- return raw_backend
- return normalized_backend
-
-
-def validate_parse_effort(effort: str) -> str:
- """校验公开 API 允许的 hybrid effort,避免非法值进入解析链路。"""
- try:
- return validate_effort(effort)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
-
-
-def resolve_parse_backend_and_effort(backend: str, effort: str) -> tuple[str, str]:
- """联合校验公开解析后端和 effort,确保旧 pipeline/VLM 值落到对应 Hybrid effort。"""
- try:
- return resolve_backend_and_effort(backend, effort)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
-
-
-def validate_parse_lang_list(lang_list: list[str]) -> list[str]:
- """校验公开 API 允许的 OCR 语言列表,并归一隐藏兼容别名。"""
- try:
- return validate_public_ocr_lang_list(lang_list)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
-
-
-async def parse_request_form(
- request: Request,
- files: Annotated[
- list[UploadFile],
- File(
- description="Upload PDF, image, DOCX, PPTX, or XLSX files for parsing",
- json_schema_extra=SWAGGER_UI_FILE_ARRAY_SCHEMA_EXTRA,
- ),
- ],
- lang_list: Annotated[
- list[str],
- Form(
- description=format_public_ocr_lang_description(),
- json_schema_extra=PUBLIC_OCR_LANGUAGE_SCHEMA_EXTRA,
- ),
- ] = ["ch"],
- backend: Annotated[
- str,
- Form(
- description=(
- "The backend for parsing:\n"
- "- hybrid-engine: Hybrid parsing via local computing power. Hybrid medium supports language-aware local OCR; "
- "use effort to switch medium/high/xhigh behavior.\n"
- "- hybrid-http-client: Hybrid parsing via remote computing power but requires a little local computing power"
- "(client suitable for openai-compatible servers). Hybrid medium supports language-aware local OCR; "
- "use effort to switch medium/high/xhigh behavior."
- ),
- json_schema_extra=BACKEND_SCHEMA_EXTRA,
- ),
- ] = DEFAULT_BACKEND,
- effort: Annotated[
- str,
- Form(
- description=(
- "(Adapted only for hybrid backend) Hybrid parsing effort:\n"
- "- medium: Local Hybrid processing without VLM calls. Supports language-aware local OCR and table OCR. "
- "Image/chart analysis is disabled.\n"
- "- high: Faster VLM parsing for most documents, balancing accuracy and efficiency. "
- "Image/chart analysis is disabled.\n"
- "- xhigh: Higher-accuracy parsing with image/chart analysis support, which may take longer."
- ),
- json_schema_extra=HYBRID_EFFORT_SCHEMA_EXTRA,
- ),
- ] = DEFAULT_HYBRID_EFFORT,
- parse_method: Annotated[
- str,
- Form(
- description="""(Adapted only for hybrid backend)The method for parsing PDF:
-- auto: Automatically determine the method based on the file type
-- txt: Use text extraction method
-- ocr: Use OCR method for image-based PDFs
-""",
- ),
- ] = "auto",
- image_analysis: Annotated[
- bool,
- Form(
- description=(
- "Enable image/chart analysis for hybrid backends. "
- "Hybrid medium and high efforts automatically disable image/chart analysis."
- ),
- ),
- ] = True,
- server_url: Annotated[
- Optional[str],
- Form(
- description="(Adapted only for hybrid-http-client backend)openai compatible server url, e.g., http://127.0.0.1:30000",
- ),
- ] = None,
- return_md: Annotated[
- bool,
- Form(description="Return markdown content in response"),
- ] = True,
- return_middle_json: Annotated[
- bool,
- Form(description="Return middle JSON in response"),
- ] = False,
- return_model_output: Annotated[
- bool,
- Form(description="Return model output JSON in response"),
- ] = False,
- return_content_list: Annotated[
- bool,
- Form(description="Return content list JSON in response"),
- ] = False,
- return_images: Annotated[
- bool,
- Form(description="Return extracted images in response"),
- ] = False,
- response_format_zip: Annotated[
- bool,
- Form(description="Return results as a ZIP file instead of JSON"),
- ] = False,
- return_original_file: Annotated[
- bool,
- Form(
- description=(
- "Include the processed original input file in the ZIP result; "
- "ignored unless response_format_zip=true"
- ),
- ),
- ] = False,
- client_side_output_generation: Annotated[
- bool,
- Form(
- description=(
- "Defer final markdown/content-list generation to the client. "
- "When enabled, the server returns staged middle JSON, model output, and images."
- ),
- ),
- ] = False,
- start_page_id: Annotated[
- int,
- Form(description="The starting page for PDF parsing, beginning from 0"),
- ] = 0,
- end_page_id: Annotated[
- int,
- Form(description="The ending page for PDF parsing, beginning from 0"),
- ] = 99999,
-) -> ParseRequestOptions:
- """解析 API/Router 共用的 multipart 表单,并保持 Swagger 参数同源。"""
- backend, effort = resolve_parse_backend_and_effort(backend, effort)
- validate_public_http_client_request(
- public_bind_exposed=bool(
- getattr(request.app.state, "public_bind_exposed", False)
- ),
- allow_public_http_client=bool(
- getattr(request.app.state, "allow_public_http_client", False)
- ),
- backend=backend,
- server_url=server_url,
- )
- if client_side_output_generation:
- return_md = False
- return_middle_json = True
- return_model_output = True
- return_content_list = False
- return_images = True
-
- effective_return_original_file = return_original_file and response_format_zip
- return ParseRequestOptions(
- files=files,
- lang_list=validate_parse_lang_list(lang_list),
- backend=backend,
- effort=effort,
- parse_method=validate_parse_method(parse_method),
- image_analysis=image_analysis,
- server_url=server_url,
- return_md=return_md,
- return_middle_json=return_middle_json,
- return_model_output=return_model_output,
- return_content_list=return_content_list,
- return_images=return_images,
- response_format_zip=response_format_zip,
- return_original_file=effective_return_original_file,
- client_side_output_generation=client_side_output_generation,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- )
diff --git a/mineru/cli_old/client.py b/mineru/cli_old/client.py
deleted file mode 100644
index cb8ad7b3..00000000
--- a/mineru/cli_old/client.py
+++ /dev/null
@@ -1,1116 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import asyncio
-import multiprocessing
-import os
-import sys
-import threading
-from concurrent.futures import Future, ProcessPoolExecutor
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Awaitable, Callable, Optional, TextIO
-
-import click
-import httpx
-from loguru import logger
-
-from mineru.cli_old import api_client as _api_client
-from mineru.cli_old.api_protocol import (
- DEFAULT_MAX_CONCURRENT_REQUESTS,
- DEFAULT_PROCESSING_WINDOW_SIZE,
-)
-from mineru.cli_old.client_side_output import regenerate_client_side_outputs
-from mineru.cli_old.common import (
- HybridDependencyError,
- ensure_backend_dependencies,
- image_suffixes,
- office_suffixes,
- pdf_suffixes,
- uniquify_task_stems,
-)
-from mineru.cli_old.output_paths import resolve_parse_dir
-from mineru.cli_old.visualization import (
- VisualizationJob,
- run_visualization_job,
-)
-from mineru.utils.config_reader import (
- get_max_concurrent_requests as read_max_concurrent_requests,
-)
-from mineru.utils.backend_options import (
- DEFAULT_BACKEND,
- DEFAULT_HYBRID_EFFORT,
- HYBRID_EFFORT_CHOICES,
- LEGACY_PIPELINE_BACKEND_ALIASES,
- LEGACY_VLM_BACKEND_ALIASES,
- PUBLIC_BACKEND_CHOICES,
- normalize_public_backend,
- resolve_backend_and_effort,
- validate_effort,
-)
-from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
-from mineru.utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
-from mineru.utils.pdf_document import PDFDocument
-from mineru.utils.pdf_page_id import get_end_page_id
-from mineru.version import __version__
-
-os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
-log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
-
-
-@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
-class TaskExecutionProgress:
- total_tasks: int
- total_pages: int
- completed_tasks: int
- completed_pages: int
- lock: asyncio.Lock
-
-
-@dataclass
-class VisualizationContext:
- executor: ProcessPoolExecutor
- futures: list[Future]
-
-
-ServerHealth = _api_client.ServerHealth
-SubmitResponse = _api_client.SubmitResponse
-LocalAPIServer = _api_client.LocalAPIServer
-
-
-def normalize_backend_option(
- ctx: Optional[click.Context],
- param: Optional[click.Parameter],
- value: str,
-) -> str:
- """校验 CLI backend,legacy pipeline/VLM 值保留到后续 backend+effort 联合解析。"""
- normalized_value = (value or "").strip()
- try:
- normalized_backend = normalize_public_backend(normalized_value)
- except ValueError as exc:
- raise click.BadParameter(str(exc), ctx=ctx, param=param) from exc
- if normalized_value in LEGACY_PIPELINE_BACKEND_ALIASES or normalized_value in LEGACY_VLM_BACKEND_ALIASES:
- return normalized_value
- return normalized_backend
-
-
-def normalize_effort_option(
- ctx: Optional[click.Context],
- param: Optional[click.Parameter],
- value: str,
-) -> str:
- """将 CLI 输入的 hybrid effort 参数规范为当前公开 effort 名称。"""
- try:
- return validate_effort(value)
- except ValueError as exc:
- raise click.BadParameter(str(exc), ctx=ctx, param=param) from exc
-
-
-def normalize_ocr_lang_option(
- ctx: Optional[click.Context],
- param: Optional[click.Parameter],
- value: str,
-) -> str:
- """将 CLI OCR 语言参数归一为公开下游可消费的语言 key。"""
- try:
- return validate_public_ocr_lang(value)
- except ValueError as exc:
- raise click.BadParameter(str(exc), ctx=ctx, param=param) from exc
-
-
-@dataclass(frozen=True)
-class TaskFailure:
- task_index: int
- document_stems: tuple[str, ...]
- message: str
-
-
-@dataclass
-class LiveTaskStatusState:
- task_index: int
- task_id: str
- status: str
- queued_ahead: int | None = None
- frame_step: int = 0
-
-
-class LiveAwareStderrSink:
- def __init__(self, stream: TextIO):
- self.stream = stream
- self.lock = threading.RLock()
- self.renderer: LiveTaskStatusRenderer | None = None
-
- def set_renderer(self, renderer: "LiveTaskStatusRenderer | None") -> None:
- with self.lock:
- self.renderer = renderer
-
- def isatty(self) -> bool:
- return bool(getattr(self.stream, "isatty", lambda: False)())
-
- def write(self, message: str) -> None:
- with self.lock:
- renderer = self.renderer
- if renderer is not None:
- renderer.clear_locked()
- self.stream.write(message)
- self.stream.flush()
- if renderer is not None:
- renderer.render_locked()
-
- def flush(self) -> None:
- self.stream.flush()
-
- def stop(self) -> None:
- self.flush()
-
-
-class LiveTaskStatusRenderer:
- BAR_WIDTH = 12
- RUNNER_WIDTH = 4
- ACTIVE_STATUSES = {"pending", "processing"}
-
- def __init__(self, sink: LiveAwareStderrSink):
- self.sink = sink
- self._rendered_line_count = 0
- self._task_states: dict[str, LiveTaskStatusState] = {}
-
- def register_task(
- self,
- task: PlannedTask,
- task_id: str,
- queued_ahead: int | None = None,
- ) -> None:
- with self.sink.lock:
- self._task_states[task_id] = LiveTaskStatusState(
- task_index=task.index,
- task_id=task_id,
- status="pending",
- queued_ahead=queued_ahead,
- )
- self.render_locked()
-
- def update_status(
- self,
- task_id: str,
- status_update: _api_client.TaskStatusSnapshot | str,
- ) -> None:
- with self.sink.lock:
- state = self._task_states.get(task_id)
- if state is None:
- return
- if isinstance(status_update, _api_client.TaskStatusSnapshot):
- status = status_update.status
- queued_ahead = status_update.queued_ahead if status == "pending" else None
- else:
- status = status_update
- queued_ahead = None
-
- state.status = status
- state.queued_ahead = queued_ahead
- if status in self.ACTIVE_STATUSES:
- state.frame_step += 1
- self.render_locked()
-
- def remove_task(self, task_id: str) -> None:
- with self.sink.lock:
- if self._task_states.pop(task_id, None) is None:
- return
- self.render_locked()
-
- def close(self) -> None:
- with self.sink.lock:
- self._task_states.clear()
- self.clear_locked()
-
- def clear_locked(self) -> None:
- if self._rendered_line_count <= 0:
- return
-
- self.sink.stream.write(f"\x1b[{self._rendered_line_count}A\r")
- for index in range(self._rendered_line_count):
- self.sink.stream.write("\x1b[2K")
- if index + 1 < self._rendered_line_count:
- self.sink.stream.write("\x1b[1B\r")
- if self._rendered_line_count > 1:
- self.sink.stream.write(f"\x1b[{self._rendered_line_count - 1}A\r")
- self.sink.stream.flush()
- self._rendered_line_count = 0
-
- def render_locked(self) -> None:
- self.clear_locked()
- lines = self._build_render_lines_locked()
- if lines:
- self.sink.stream.write("\n".join(lines))
- self.sink.stream.write("\n")
- self.sink.stream.flush()
- self._rendered_line_count = len(lines)
-
- def _build_render_lines_locked(self) -> list[str]:
- states = sorted(
- self._task_states.values(),
- key=lambda state: (state.task_index, state.task_id),
- )
- return [self._build_render_line_locked(state) for state in states]
-
- @staticmethod
- def _build_render_line_locked(state: LiveTaskStatusState) -> str:
- parts = [f"status={state.status}"]
- if state.status == "pending" and state.queued_ahead is not None:
- parts.append(f"ahead={state.queued_ahead}")
- parts.append(f"task_id={state.task_id}")
- return f"{LiveTaskStatusRenderer._build_bar(state.frame_step)} {' | '.join(parts)}"
-
- @classmethod
- def _build_bar(cls, frame_step: int) -> str:
- cells = [" "] * cls.BAR_WIDTH
- runner_start = frame_step % cls.BAR_WIDTH
- for offset in range(cls.RUNNER_WIDTH):
- position = (runner_start + offset) % cls.BAR_WIDTH
- cells[position] = "="
- head_position = (runner_start + cls.RUNNER_WIDTH - 1) % cls.BAR_WIDTH
- cells[head_position] = ">"
- return f"[{''.join(cells)}]"
-
-
-def create_live_task_status_renderer(
- api_url: Optional[str],
-) -> Optional[LiveTaskStatusRenderer]:
- if api_url is None or not _stderr_sink.isatty():
- _stderr_sink.set_renderer(None)
- return None
-
- renderer = LiveTaskStatusRenderer(_stderr_sink)
- _stderr_sink.set_renderer(renderer)
- return renderer
-
-
-_stderr_sink = LiveAwareStderrSink(sys.stderr)
-logger.remove()
-logger.add(_stderr_sink, level=log_level)
-
-
-def build_http_timeout() -> httpx.Timeout:
- return _api_client.build_http_timeout()
-
-
-def find_free_port() -> int:
- return _api_client.find_free_port()
-
-
-def normalize_base_url(url: str) -> str:
- return _api_client.normalize_base_url(url)
-
-
-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 format_task_log_label(task: PlannedTask, max_documents: int = 3) -> str:
- if len(task.documents) <= max_documents:
- return format_task_label(task)
-
- visible_names = ", ".join(doc.stem for doc in task.documents[:max_documents])
- hidden_count = len(task.documents) - max_documents
- return f"task#{task.index} [{visible_names}, +{hidden_count} more]"
-
-
-def format_count(value: int, singular: str, plural: Optional[str] = None) -> str:
- unit = singular if value == 1 else (plural or f"{singular}s")
- return f"{value} {unit}"
-
-
-def format_task_submission_message(
- task: PlannedTask,
- progress: TaskExecutionProgress,
-) -> str:
- return (
- f"Submitting batch {task.index}/{progress.total_tasks} | "
- f"{format_count(len(task.documents), 'document')}, "
- f"{format_count(task.total_pages, 'page')} in this batch | "
- f"{format_count(progress.total_pages, 'page')} total | "
- f"{format_task_log_label(task)}"
- )
-
-
-def format_task_completion_message(
- task: PlannedTask,
- progress: TaskExecutionProgress,
- completed_tasks: int,
- completed_pages: int,
-) -> str:
- batch_word = "batch" if progress.total_tasks == 1 else "batches"
- page_word = "page" if progress.total_pages == 1 else "pages"
- return (
- f"Completed batch {task.index}/{progress.total_tasks} | "
- f"Processed {completed_pages}/{progress.total_pages} {page_word} | "
- f"{completed_tasks} of {progress.total_tasks} {batch_word} finished | "
- f"{format_task_log_label(task)}"
- )
-
-
-def build_task_execution_progress(
- planned_tasks: list[PlannedTask],
-) -> TaskExecutionProgress:
- return TaskExecutionProgress(
- total_tasks=len(planned_tasks),
- total_pages=sum(task.total_pages for task in planned_tasks),
- completed_tasks=0,
- completed_pages=0,
- lock=asyncio.Lock(),
- )
-
-
-async def mark_task_completed(
- progress: TaskExecutionProgress,
- completed_pages: int,
-) -> tuple[int, int]:
- async with progress.lock:
- progress.completed_tasks += 1
- progress.completed_pages += completed_pages
- return progress.completed_tasks, progress.completed_pages
-
-
-def create_visualization_context() -> Optional[VisualizationContext]:
- try:
- spawn_context = multiprocessing.get_context("spawn")
- return VisualizationContext(
- executor=ProcessPoolExecutor(
- max_workers=1,
- mp_context=spawn_context,
- ),
- futures=[],
- )
- except Exception as exc:
- logger.warning(f"Failed to start visualization worker process: {exc}")
- return None
-
-
-def build_visualization_jobs(
- planned_task: PlannedTask,
- output_dir: Path,
- backend: str,
- parse_method: str,
-) -> list[VisualizationJob]:
- return [
- VisualizationJob(
- document_stem=document.stem,
- backend=backend,
- parse_method=parse_method,
- parse_dir=resolve_parse_dir(
- output_dir,
- document.stem,
- backend,
- parse_method,
- is_office=document.suffix in office_suffixes,
- ),
- )
- for document in planned_task.documents
- ]
-
-
-def log_visualization_future_result(
- job: VisualizationJob,
- future: Future,
-) -> None:
- try:
- result = future.result()
- except Exception as exc:
- logger.warning(f"Skipping visualization for {job.document_stem}: {exc}")
- return
-
- if result.status != "finished":
- logger.warning(f"Skipping visualization for {result.document_stem}: {result.message}")
-
-
-def queue_visualization_jobs(
- visualization_context: Optional[VisualizationContext],
- jobs: list[VisualizationJob],
- planned_task: PlannedTask,
-) -> int:
- if visualization_context is None or not jobs:
- return 0
-
- del planned_task
- queued_jobs = 0
- for job in jobs:
- try:
- future = visualization_context.executor.submit(run_visualization_job, job)
- except Exception as exc:
- logger.warning(f"Skipping visualization for {job.document_stem}: {exc}")
- continue
-
- future.add_done_callback(
- lambda completed_future, job=job: log_visualization_future_result(
- job,
- completed_future,
- )
- )
- visualization_context.futures.append(future)
- queued_jobs += 1
-
- return queued_jobs
-
-
-async def wait_for_visualization_jobs(
- visualization_context: Optional[VisualizationContext],
-) -> None:
- if visualization_context is None:
- return
-
- try:
- if visualization_context.futures:
- await asyncio.gather(
- *(asyncio.wrap_future(future) for future in visualization_context.futures),
- return_exceptions=True,
- )
- finally:
- visualization_context.executor.shutdown(wait=True)
-
-
-def response_detail(response: httpx.Response) -> str:
- return _api_client.response_detail(response)
-
-
-def validate_server_health_payload(payload: dict, base_url: str) -> ServerHealth:
- return _api_client.validate_server_health_payload(payload, base_url)
-
-
-async def fetch_server_health(
- client: httpx.AsyncClient,
- base_url: str,
-) -> ServerHealth:
- return await _api_client.fetch_server_health(client, base_url)
-
-
-async def wait_for_local_api_ready(
- client: httpx.AsyncClient,
- local_server: LocalAPIServer,
- timeout_seconds: float = _api_client.LOCAL_API_STARTUP_TIMEOUT_SECONDS,
-) -> ServerHealth:
- return await _api_client.wait_for_local_api_ready(
- client,
- local_server,
- timeout_seconds=timeout_seconds,
- )
-
-
-def probe_pdf_effective_pages(
- path: Path,
- start_page_id: int,
- end_page_id: Optional[int],
-) -> int:
- with PDFDocument(str(path)) as pdf_doc:
- page_count = pdf_doc.page_count
-
- 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}: 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}")
-
- normalized_stems, renamed_stems = uniquify_task_stems([document.stem for document in collected])
- if renamed_stems:
- rename_details = ", ".join(
- f"{document.path.name} -> {effective_stem}"
- for document, effective_stem in zip(collected, normalized_stems)
- if document.stem != effective_stem
- )
- logger.warning(f"Normalized duplicate document stems within this run: {rename_details}")
- return [
- InputDocument(
- path=document.path,
- suffix=document.suffix,
- stem=effective_stem,
- effective_pages=document.effective_pages,
- order=document.order,
- )
- for document, effective_stem in zip(collected, normalized_stems)
- ]
-
- return collected
-
-
-def plan_tasks(
- documents: list[InputDocument],
- backend: str,
- processing_window_size: int,
-) -> list[PlannedTask]:
- 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,
- server_url: Optional[str],
- start_page_id: int,
- end_page_id: Optional[int],
- image_analysis: bool = True,
- effort: str = DEFAULT_HYBRID_EFFORT,
- client_side_output_generation: bool = False,
-) -> dict[str, str | list[str]]:
- backend, effort = resolve_backend_and_effort(backend, effort)
- # 开启客户端输出生成时,只关闭客户端会重建的最终产物。
- return_md = not client_side_output_generation
- return_content_list = not client_side_output_generation
- return _api_client.build_parse_request_form_data(
- lang_list=[lang],
- backend=backend,
- parse_method=method,
- image_analysis=image_analysis,
- effort=effort,
- server_url=server_url,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- return_md=return_md,
- return_middle_json=True,
- return_model_output=True,
- return_content_list=return_content_list,
- return_images=True,
- response_format_zip=True,
- return_original_file=True,
- client_side_output_generation=client_side_output_generation,
- )
-
-
-async def submit_task(
- client: httpx.AsyncClient,
- base_url: str,
- planned_task: PlannedTask,
- form_data: dict[str, str | list[str]],
-) -> SubmitResponse:
- del client
- upload_assets = [
- _api_client.UploadAsset(
- path=document.path,
- upload_name=f"{document.stem}{document.path.suffix}",
- )
- for document in planned_task.documents
- ]
- return await _api_client.submit_parse_task(
- base_url=base_url,
- upload_assets=upload_assets,
- form_data=form_data,
- )
-
-
-async def wait_for_task_result(
- client: httpx.AsyncClient,
- submit_response: SubmitResponse,
- planned_task: PlannedTask,
- live_renderer: Optional[LiveTaskStatusRenderer] = None,
- timeout_seconds: float = _api_client.TASK_RESULT_TIMEOUT_SECONDS,
-) -> None:
- return await _api_client.wait_for_task_result(
- client=client,
- submit_response=submit_response,
- task_label=format_task_label(planned_task),
- status_snapshot_callback=(
- None
- if live_renderer is None
- else lambda snapshot: live_renderer.update_status(
- submit_response.task_id,
- snapshot,
- )
- ),
- timeout_seconds=timeout_seconds,
- )
-
-
-async def download_result_zip(
- client: httpx.AsyncClient,
- submit_response: SubmitResponse,
- planned_task: PlannedTask,
-) -> Path:
- return await _api_client.download_result_zip(
- client=client,
- submit_response=submit_response,
- task_label=format_task_label(planned_task),
- )
-
-
-def safe_extract_zip(zip_path: Path, output_dir: Path) -> None:
- _api_client.safe_extract_zip(zip_path, output_dir)
-
-
-def resolve_submit_concurrency(max_concurrent_requests: int, task_count: int) -> int:
- if max_concurrent_requests <= 0:
- raise ValueError("max_concurrent_requests must be a positive integer")
- return max(1, min(max_concurrent_requests, task_count))
-
-
-def resolve_effective_max_concurrent_requests(
- local_max: int,
- server_max: int,
-) -> int:
- return _api_client.resolve_effective_max_concurrent_requests(
- local_max=local_max,
- server_max=server_max,
- )
-
-
-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,
- progress: TaskExecutionProgress,
- backend: str,
- parse_method: str,
- visualization_context: Optional[VisualizationContext],
- form_data: dict[str, str],
- output_dir: Path,
- live_renderer: Optional[LiveTaskStatusRenderer] = None,
- effort: str = DEFAULT_HYBRID_EFFORT,
- client_side_output_generation: bool = False,
-) -> None:
- logger.info(format_task_submission_message(planned_task, progress))
- submit_response = await submit_task(
- client=client,
- base_url=server_health.base_url,
- planned_task=planned_task,
- form_data=form_data,
- )
- if live_renderer is not None:
- live_renderer.register_task(
- planned_task,
- submit_response.task_id,
- queued_ahead=submit_response.queued_ahead,
- )
- try:
- await wait_for_task_result(
- client=client,
- submit_response=submit_response,
- planned_task=planned_task,
- live_renderer=live_renderer,
- )
- finally:
- if live_renderer is not None:
- live_renderer.remove_task(submit_response.task_id)
- 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)
- if client_side_output_generation:
- for document in planned_task.documents:
- # 解压后按现有 parse_dir 结构覆盖重生客户端最终输出产物。
- parse_dir = resolve_parse_dir(
- output_dir,
- document.stem,
- backend,
- parse_method,
- is_office=document.suffix in office_suffixes,
- )
- await asyncio.to_thread(
- regenerate_client_side_outputs,
- parse_dir,
- document.stem,
- "office" if document.suffix in office_suffixes else backend,
- effort=effort,
- )
- completed_tasks, completed_pages = await mark_task_completed(
- progress,
- planned_task.total_pages,
- )
- logger.info(
- format_task_completion_message(
- planned_task,
- progress,
- completed_tasks,
- completed_pages,
- )
- )
- try:
- visualization_jobs = build_visualization_jobs(
- planned_task,
- output_dir,
- backend,
- parse_method,
- )
- except Exception as exc:
- logger.warning(f"Skipping visualization for {format_task_log_label(planned_task)}: {exc}")
- else:
- queue_visualization_jobs(
- visualization_context,
- visualization_jobs,
- planned_task,
- )
-
-
-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],
- image_analysis: bool = True,
- effort: str = DEFAULT_HYBRID_EFFORT,
- client_side_output_generation: bool = False,
- extra_cli_args: tuple[str, ...] = (),
-) -> None:
- backend, effort = resolve_backend_and_effort(backend, effort)
- 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")
- if api_url is None:
- try:
- ensure_backend_dependencies(backend)
- except HybridDependencyError as exc:
- raise click.ClickException(str(exc)) from exc
-
- 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
- visualization_context: Optional[VisualizationContext] = None
- live_renderer: Optional[LiveTaskStatusRenderer] = None
- async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as http_client:
- try:
- if api_url is None:
- local_server = LocalAPIServer(extra_cli_args=extra_cli_args)
- 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)
- effective_max_concurrent_requests = server_health.max_concurrent_requests
- else:
- server_health = await fetch_server_health(
- http_client,
- normalize_base_url(api_url),
- )
- effective_max_concurrent_requests = resolve_effective_max_concurrent_requests(
- read_max_concurrent_requests(default=DEFAULT_MAX_CONCURRENT_REQUESTS),
- server_health.max_concurrent_requests,
- )
- live_renderer = create_live_task_status_renderer(api_url)
-
- planned_tasks = plan_tasks(
- documents=documents,
- backend=backend,
- processing_window_size=DEFAULT_PROCESSING_WINDOW_SIZE,
- )
- progress = build_task_execution_progress(planned_tasks)
- concurrency = resolve_submit_concurrency(
- effective_max_concurrent_requests,
- len(planned_tasks),
- )
- form_data = build_request_form_data(
- lang=lang,
- backend=backend,
- method=method,
- image_analysis=image_analysis,
- effort=effort,
- server_url=server_url,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- client_side_output_generation=client_side_output_generation,
- )
- visualization_context = create_visualization_context()
- 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,
- progress=progress,
- backend=backend,
- parse_method=method,
- visualization_context=visualization_context,
- form_data=form_data,
- output_dir=output_dir,
- live_renderer=live_renderer,
- effort=effort,
- client_side_output_generation=client_side_output_generation,
- ),
- )
- 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:
- try:
- if local_server is not None:
- local_server.stop()
- finally:
- try:
- await wait_for_visualization_jobs(visualization_context)
- finally:
- if live_renderer is not None:
- live_renderer.close()
- _stderr_sink.set_renderer(None)
-
-
[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")
- "-p",
- "--path",
- "input_path",
- type=click.Path(exists=True, path_type=Path),
- required=True,
- help="local filepath or directory. support pdf, image, docx, pptx, xlsx files",
-)
- "-o",
- "--output",
- "output_dir",
- type=click.Path(path_type=Path),
- required=True,
- 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.",
-)
- "-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.
- txt: Use text extraction method.
- 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 'hybrid-*'.""",
-)
- "-b",
- "--backend",
- "backend",
- type=str,
- default=DEFAULT_BACKEND,
- callback=normalize_backend_option,
- metavar="[" + "|".join(PUBLIC_BACKEND_CHOICES) + "]",
- help="""\b
- the backend for parsing pdf:
- hybrid-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 backend specified, hybrid-engine will be used by default.""",
-)
- "--effort",
- "effort",
- type=str,
- default=DEFAULT_HYBRID_EFFORT,
- callback=normalize_effort_option,
- metavar="[" + "|".join(HYBRID_EFFORT_CHOICES) + "]",
- help="""\b
- Hybrid parsing effort:
- medium: Local Hybrid processing without VLM calls. Image/chart analysis is disabled.
- high: Faster VLM parsing for most documents, balancing accuracy and efficiency. Image/chart analysis is disabled.
- xhigh: Higher-accuracy parsing with image/chart analysis support, which may take longer.
- Without effort specified, high will be used by default.
- Adapted only for the case where the backend is set to 'hybrid-*'.""",
-)
- "-l",
- "--lang",
- "lang",
- type=str,
- default="ch",
- callback=normalize_ocr_lang_option,
- metavar="[" + "|".join(PUBLIC_OCR_LANGUAGES) + "]",
- 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 'hybrid-*'.
- """,
-)
- "-u",
- "--url",
- "server_url",
- type=str,
- default=None,
- help="""
- When the backend is `hybrid-http-client`, you need to specify the server_url, for example:`http://127.0.0.1:30000`
- """,
-)
- "-s",
- "--start",
- "start_page_id",
- type=int,
- default=0,
- help="The starting page for PDF parsing, beginning from 0.",
-)
- "-e",
- "--end",
- "end_page_id",
- type=int,
- default=None,
- help="The ending page for PDF parsing, beginning from 0.",
-)
- "--image-analysis",
- "image_analysis",
- type=bool,
- default=True,
- help="Enable image/chart analysis for hybrid backends. Default is True. ",
-)
- "--client-side-output-generation",
- "client_side_output_generation",
- type=bool,
- default=False,
- help=("Generate markdown and content lists locally from server-returned middle json, images, and original files."),
-)
-def main(
- ctx: click.Context,
- input_path: Path,
- output_dir: Path,
- api_url: Optional[str],
- method: str,
- backend: str,
- effort: str,
- lang: str,
- server_url: Optional[str],
- start_page_id: int,
- end_page_id: Optional[int],
- image_analysis: bool,
- client_side_output_generation: bool,
-) -> None:
- asyncio.run(
- run_orchestrated_cli(
- input_path=input_path,
- output_dir=output_dir,
- method=method,
- backend=backend,
- effort=effort,
- lang=lang,
- server_url=server_url,
- api_url=api_url,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- image_analysis=image_analysis,
- client_side_output_generation=client_side_output_generation,
- extra_cli_args=tuple(ctx.args),
- )
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/mineru/cli_old/client_side_output.py b/mineru/cli_old/client_side_output.py
deleted file mode 100644
index b4ea9037..00000000
--- a/mineru/cli_old/client_side_output.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import json
-from pathlib import Path
-from typing import Any
-
-from mineru.parser.base import ParseResult
-from mineru.render import render_content_list, render_markdown, render_structured_content
-from mineru.types import PageInfo
-from mineru.utils.backend_options import (
- DEFAULT_HYBRID_EFFORT,
- normalize_backend,
- resolve_backend_and_effort,
- validate_effort,
-)
-from mineru.version import __version__
-
-PDF_BACKENDS = {"hybrid"}
-
-
-def _write_json(path: Path, payload: Any) -> None:
- """按项目现有格式写入 JSON 文件,保持中文内容可读。"""
- path.write_text(
- json.dumps(payload, ensure_ascii=False, indent=4),
- encoding="utf-8",
- )
-
-
-def _normalize_client_side_backend(backend: str) -> str:
- """将旧 CLI 传入的后端选项归一化为客户端重渲染使用的后端族。"""
- if backend == "office":
- return "office"
- try:
- backend = normalize_backend(backend)
- except ValueError:
- pass
- if backend.startswith("hybrid"):
- return "hybrid"
- raise ValueError(f"Unsupported middle json backend for client-side output generation: {backend}")
-
-
-def _stamp_client_side_backend(pages: list[PageInfo], backend: str) -> None:
- """按客户端入口的显式后端标记每页,确保后续渲染分发不依赖旧文件残留状态。"""
- for page in pages:
- page._backend = backend
-
-
-def _finalize_client_side_pages(
- pages: list[PageInfo],
- backend: str,
- effort: str = DEFAULT_HYBRID_EFFORT,
-) -> None:
- """按调用方传入的后端类型,对 pages 原地执行客户端可完成的 finalize。"""
- if backend == "hybrid":
- from mineru.backend.pdf.model_output_to_middle_json import finalize_middle_json_from_preproc
-
- finalize_middle_json_from_preproc(pages, effort=validate_effort(effort))
- return
- raise ValueError(f"Unsupported client-side finalize backend '{backend}'")
-
-
-def regenerate_client_side_outputs(
- parse_dir: str | Path,
- doc_stem: str,
- backend: str,
- effort: str = DEFAULT_HYBRID_EFFORT,
-) -> tuple[Path, ...]:
- """读取服务端 staged/finalized middle json,并在客户端覆盖生成最终输出产物。"""
- parse_dir = Path(parse_dir)
- middle_json_path = parse_dir / f"{doc_stem}_middle.json"
- markdown_path = parse_dir / f"{doc_stem}.md"
- content_list_path = parse_dir / f"{doc_stem}_content_list.json"
- structured_content_path = parse_dir / f"{doc_stem}_structured_content.json"
-
- if not middle_json_path.exists():
- raise FileNotFoundError(f"Missing middle json file: {middle_json_path}")
-
- middle_json = json.loads(middle_json_path.read_text(encoding="utf-8"))
- if not isinstance(middle_json, dict):
- raise ValueError("middle_json must be a dict.")
- backend, effort = resolve_backend_and_effort(backend, effort)
- normalized_backend = _normalize_client_side_backend(backend)
- result = ParseResult.from_dict(middle_json)
- pages = result.pages
- _stamp_client_side_backend(pages, normalized_backend)
-
- if normalized_backend in PDF_BACKENDS:
- _finalize_client_side_pages(pages, normalized_backend, effort=effort)
-
- image_dir = "images"
-
- markdown_path.write_text(
- render_markdown(pages, image_dir),
- encoding="utf-8",
- )
- _write_json(
- content_list_path,
- render_content_list(pages, image_dir),
- )
- _write_json(
- structured_content_path,
- render_structured_content(pages, image_dir),
- )
- output_middle_json = ParseResult(
- pages=pages,
- _retained_page_indices=result._retained_page_indices,
- _broken_page_indices=result._broken_page_indices,
- ).to_dict()
- output_middle_json["_backend"] = normalized_backend
- output_middle_json["_version_name"] = __version__
- _write_json(middle_json_path, output_middle_json)
-
- return (
- middle_json_path,
- markdown_path,
- content_list_path,
- structured_content_path,
- )
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
deleted file mode 100644
index e0537499..00000000
--- a/mineru/cli_old/common.py
+++ /dev/null
@@ -1,712 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import asyncio
-import importlib
-import importlib.util
-import json
-import os
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any, Callable, Sequence
-
-from loguru import logger
-
-from ..backend.office.analyze import analyze as office_analyze
-from ..filetypes import IMAGE_EXTENSIONS, OFFICE_EXTENSIONS, PDF_EXTENSIONS
-from ..parser.base import ParseResult
-from ..render import render_markdown, render_structured_content
-from ..render.writer import FileBasedDataWriter
-from ..types import MiddleJson, PageInfo
-from ..utils.backend_options import DEFAULT_BACKEND, DEFAULT_HYBRID_EFFORT, LOCAL_HYBRID_EFFORT, resolve_backend_and_effort
-from ..utils.draw_bbox import draw_layout_bbox
-from ..utils.engine_utils import get_vlm_engine
-from ..utils.guess_suffix_or_lang import guess_suffix_by_bytes
-from ..utils.image_payload import ImagePayloadCache
-from ..utils.pdf_image_tools import images_bytes_to_pdf_bytes
-from ..utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium, safe_rewrite_pdf_bytes_with_pdfium_result
-from ..version import __version__
-from .visualization import select_pages_for_pdf_visualization
-
-os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
-if os.getenv("MINERU_LMDEPLOY_DEVICE", "") == "maca":
- import torch
-
- torch.backends.cudnn.enabled = False
-
-
-pdf_suffixes = sorted(PDF_EXTENSIONS)
-image_suffixes = sorted(IMAGE_EXTENSIONS)
-docx_suffixes = ["docx"]
-pptx_suffixes = ["pptx"]
-xlsx_suffixes = ["xlsx"]
-office_suffixes = sorted(OFFICE_EXTENSIONS)
-
-os.environ["TOKENIZERS_PARALLELISM"] = "false"
-# Maximum UTF-8 byte length allowed for task stems used in filenames.
-# 200 bytes is chosen to stay well below common filesystem limits (e.g. 255 bytes)
-# and to prevent generating excessively long or incompatible filenames.
-MAX_TASK_STEM_BYTES = 200
-
-
-@dataclass(frozen=True)
-class PreparedPdfBytes:
- """记录旧 CLI PDF 预处理结果,避免页号映射在 backend 前丢失。"""
-
- pdf_bytes: bytes
- retained_page_indices: list[int] | None = None
- broken_page_indices: list[int] | None = None
-
-
-class HybridDependencyError(RuntimeError):
- pass
-
-
-def build_hybrid_dependency_error_message(backend: str) -> str:
- return (
- f"`{backend}` requires local pipeline dependencies (`mineru[pipeline]`, "
- "including `torch`). Install `mineru[pipeline]` or `mineru[core]`. "
- "The legacy `vlm-http-client` option is now mapped to `hybrid-http-client` "
- "and needs the same local dependencies."
- )
-
-
-def ensure_backend_dependencies(backend: str) -> None:
- if not backend.startswith("hybrid-"):
- return
- if importlib.util.find_spec("torch") is None:
- raise HybridDependencyError(build_hybrid_dependency_error_message(backend))
-
-
-def _load_hybrid_analyze_entrypoint(entrypoint_name: str, backend: str) -> Callable[..., Any]:
- ensure_backend_dependencies(backend)
- try:
- hybrid_analyze = importlib.import_module("mineru.backend.hybrid.hybrid_analyze")
- except (ImportError, ModuleNotFoundError) as exc:
- raise HybridDependencyError(build_hybrid_dependency_error_message(backend)) from exc
- return getattr(hybrid_analyze, entrypoint_name)
-
-
-def utf8_byte_length(value: str) -> int:
- return len(value.encode("utf-8"))
-
-
-def truncate_to_utf8_bytes(value: str, max_bytes: int) -> str:
- if max_bytes <= 0:
- return ""
-
- encoded = value.encode("utf-8")
- if len(encoded) <= max_bytes:
- return value
-
- truncated = encoded[:max_bytes]
- while truncated:
- try:
- return truncated.decode("utf-8")
- except UnicodeDecodeError as exc:
- truncated = truncated[: exc.start]
- return ""
-
-
-def normalize_task_stem(stem: str, max_bytes: int = MAX_TASK_STEM_BYTES) -> str:
- return truncate_to_utf8_bytes(stem, max_bytes)
-
-
-def build_task_stem_candidate(
- stem: str,
- suffix: str = "",
- max_bytes: int = MAX_TASK_STEM_BYTES,
-) -> str:
- if utf8_byte_length(f"{stem}{suffix}") <= max_bytes:
- return f"{stem}{suffix}"
- suffix_bytes = utf8_byte_length(suffix)
- if suffix_bytes >= max_bytes:
- return truncate_to_utf8_bytes(suffix, max_bytes)
- return f"{truncate_to_utf8_bytes(stem, max_bytes - suffix_bytes)}{suffix}"
-
-
-def uniquify_task_stems(
- stems: Sequence[str],
-) -> tuple[list[str], list[tuple[str, str]]]:
- """Assign task-local unique stems while preserving input order."""
- normalized_inputs = [normalize_task_stem(stem) for stem in stems]
- raw_keys = {stem.casefold() for stem in normalized_inputs}
- occurrence_counts: dict[str, int] = {}
- assigned_keys: set[str] = set()
- unique_stems: list[str] = []
- renamed: list[tuple[str, str]] = []
-
- for stem, normalized_stem in zip(stems, normalized_inputs):
- stem_base = normalized_stem or stem
- stem_key = stem_base.casefold()
- seen_count = occurrence_counts.get(stem_key, 0)
- occurrence_counts[stem_key] = seen_count + 1
-
- if seen_count == 0 and stem_key not in assigned_keys:
- effective_stem = stem_base
- else:
- suffix = seen_count + 1
- while True:
- candidate = build_task_stem_candidate(stem_base, f"_{suffix}")
- candidate_key = candidate.casefold()
- if candidate_key not in raw_keys and candidate_key not in assigned_keys:
- effective_stem = candidate
- break
- suffix += 1
-
- assigned_keys.add(effective_stem.casefold())
- unique_stems.append(effective_stem)
- if effective_stem != stem:
- renamed.append((stem, effective_stem))
-
- return unique_stems, renamed
-
-
-def read_fn(path: str | Path, file_suffix: str | None = None) -> bytes:
- if not isinstance(path, Path):
- path = Path(path)
- with open(str(path), "rb") as input_file:
- file_bytes = input_file.read()
- if file_suffix is None:
- file_suffix = guess_suffix_by_bytes(file_bytes, path)
- if file_suffix in image_suffixes:
- return images_bytes_to_pdf_bytes(file_bytes)
- elif file_suffix in pdf_suffixes + office_suffixes:
- return file_bytes
- else:
- raise Exception(f"Unknown file suffix: {file_suffix}")
-
-
-def prepare_env(output_dir: str, pdf_file_name: str, parse_method: str) -> tuple[str, str]:
- local_md_dir = str(os.path.join(output_dir, pdf_file_name, parse_method))
- local_image_dir = os.path.join(str(local_md_dir), "images")
- os.makedirs(local_image_dir, exist_ok=True)
- os.makedirs(local_md_dir, exist_ok=True)
- return local_image_dir, local_md_dir
-
-
-def convert_pdf_bytes_to_bytes(pdf_bytes: bytes, start_page_id: int = 0, end_page_id: int | None = None) -> bytes:
- return safe_rewrite_pdf_bytes_with_pdfium(
- pdf_bytes,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- )
-
-
-def prepare_pdf_bytes_with_page_map(
- pdf_bytes: bytes,
- start_page_id: int = 0,
- end_page_id: int | None = None,
-) -> PreparedPdfBytes:
- """重写 PDF 字节并保留小 PDF 物理页到原始页号的映射。"""
- rewrite_result = safe_rewrite_pdf_bytes_with_pdfium_result(
- pdf_bytes,
- start_page_id=start_page_id,
- end_page_id=end_page_id,
- )
- if rewrite_result.used_original:
- return PreparedPdfBytes(
- pdf_bytes=rewrite_result.pdf_bytes or pdf_bytes,
- retained_page_indices=None,
- broken_page_indices=rewrite_result.broken_page_indices,
- )
- return PreparedPdfBytes(
- pdf_bytes=rewrite_result.pdf_bytes or pdf_bytes,
- retained_page_indices=rewrite_result.retained_page_indices,
- broken_page_indices=rewrite_result.broken_page_indices,
- )
-
-
-def _prepare_pdf_bytes(pdf_bytes_list: list[bytes], start_page_id: int, end_page_id: int | None) -> list[bytes]:
- """准备处理PDF字节数据"""
- result = []
- for pdf_bytes in pdf_bytes_list:
- new_pdf_bytes = convert_pdf_bytes_to_bytes(pdf_bytes, start_page_id, end_page_id)
- result.append(new_pdf_bytes)
- return result
-
-
-def _prepare_pdf_inputs(
- pdf_bytes_list: list[bytes],
- start_page_id: int,
- end_page_id: int | None,
-) -> list[PreparedPdfBytes]:
- """批量准备 PDF 输入,并为 backend 保留逐文档页号映射。"""
- return [prepare_pdf_bytes_with_page_map(pdf_bytes, start_page_id, end_page_id) for pdf_bytes in pdf_bytes_list]
-
-
-def _process_output(
- middle_json: list[PageInfo],
- pdf_bytes: bytes,
- pdf_file_name: str,
- local_md_dir: str,
- local_image_dir: str,
- md_writer: Any,
- f_draw_layout_bbox: bool,
- f_dump_orig_pdf: bool,
- f_dump_md: bool,
- f_dump_content_list: bool,
- f_dump_middle_json: bool,
- f_dump_model_output: bool,
- f_make_md_mode: str,
- model_output: list[list[dict[str, Any]]] | None = None,
- *,
- process_mode: str,
- backend: str,
- retained_page_indices: list[int] | None = None,
- broken_page_indices: list[int] | None = None,
- image_cache: ImagePayloadCache | None = None,
-) -> None:
- """处理输出文件"""
- visualization_pages = select_pages_for_pdf_visualization(middle_json, retained_page_indices)
- if f_draw_layout_bbox:
- try:
- draw_layout_bbox(visualization_pages, pdf_bytes, local_md_dir, f"{pdf_file_name}_layout.pdf")
- except Exception as exc:
- logger.warning(f"Skipping layout bbox visualization for {pdf_file_name}: {exc}")
-
- if f_dump_orig_pdf:
- if process_mode in ["hybrid", "vlm"]:
- md_writer.write(
- f"{pdf_file_name}_origin.pdf",
- pdf_bytes,
- )
- elif process_mode in office_suffixes:
- md_writer.write(
- f"{pdf_file_name}_origin.{process_mode}",
- pdf_bytes,
- )
-
- image_dir = str(os.path.basename(local_image_dir))
- from ..version import __version__ as mineru_version
-
- export_result = ParseResult(
- middle_json=MiddleJson(
- pages=middle_json,
- file_suffix="pdf",
- effort="medium",
- parse_mode="txt",
- mineru_version=mineru_version,
- ),
- _image_cache=image_cache,
- _retained_page_indices=retained_page_indices,
- _broken_page_indices=broken_page_indices,
- )
- final_writer = FileBasedDataWriter(local_image_dir)
- for img_path, img_bytes in export_result.images().items():
- final_writer.write(img_path, img_bytes)
- public_render_pages: list[PageInfo] | None = None
-
- def get_public_render_pages() -> list[PageInfo]:
- """按需生成 public 渲染页副本,避免 staged base64 载荷进入 markdown/content 输出。"""
- nonlocal public_render_pages
- if public_render_pages is None:
- public_render_pages = export_result.export_pages()
- return public_render_pages
-
- if f_dump_md:
- md_content_str = render_markdown(
- get_public_render_pages(),
- image_dir,
- no_rich_content=(f_make_md_mode != "mm_markdown"),
- )
- md_writer.write_string(
- f"{pdf_file_name}.md",
- md_content_str,
- )
-
- if f_dump_content_list:
- structured_content = render_structured_content(get_public_render_pages(), image_dir)
- md_writer.write_string(
- f"{pdf_file_name}_structured_content.json",
- json.dumps(structured_content, ensure_ascii=False, indent=4),
- )
-
- if f_dump_middle_json:
- dump_dict = export_result.to_dict()
- dump_dict["_backend"] = backend
- dump_dict["_version_name"] = __version__
- md_writer.write_string(
- f"{pdf_file_name}_middle.json",
- json.dumps(dump_dict, ensure_ascii=False, indent=4),
- )
-
- if f_dump_model_output:
- md_writer.write_string(
- f"{pdf_file_name}_model.json",
- json.dumps(model_output, ensure_ascii=False, indent=4),
- )
-
- logger.debug(f"local output dir is {local_md_dir}")
-
-
-def _process_hybrid(
- output_dir: str,
- pdf_file_names: list[str],
- pdf_bytes_list: list[bytes],
- h_lang_list: list[str],
- parse_method: str,
- backend: str,
- f_draw_layout_bbox: bool,
- f_dump_md: bool,
- f_dump_middle_json: bool,
- f_dump_model_output: bool,
- f_dump_orig_pdf: bool,
- f_dump_content_list: bool,
- f_make_md_mode: str,
- server_url: str | None = None,
- page_index_map_list: list[list[int] | None] | None = None,
- broken_page_indices_list: list[list[int] | None] | None = None,
- **kwargs: Any,
-) -> None:
- hybrid_doc_analyze = _load_hybrid_analyze_entrypoint(
- "doc_analyze",
- f"hybrid-{backend}",
- )
- """同步处理hybrid后端逻辑"""
- if not backend.endswith("client"):
- server_url = None
-
- for idx, (pdf_bytes, lang) in enumerate(zip(pdf_bytes_list, h_lang_list)):
- pdf_file_name = pdf_file_names[idx]
- local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"hybrid_{parse_method}")
- md_writer = FileBasedDataWriter(local_md_dir)
- image_cache = ImagePayloadCache()
-
- middle_json, infer_result, _ = hybrid_doc_analyze(
- pdf_bytes,
- backend=backend,
- parse_method=parse_method,
- language=lang,
- server_url=server_url,
- page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
- image_cache=image_cache,
- **kwargs,
- )
-
- _process_output(
- middle_json,
- pdf_bytes,
- pdf_file_name,
- local_md_dir,
- local_image_dir,
- md_writer,
- f_draw_layout_bbox,
- f_dump_orig_pdf,
- f_dump_md,
- f_dump_content_list,
- f_dump_middle_json,
- f_dump_model_output,
- f_make_md_mode,
- infer_result,
- process_mode="hybrid",
- backend="hybrid",
- retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
- broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
- image_cache=image_cache,
- )
-
-
-async def _async_process_hybrid(
- output_dir: str,
- pdf_file_names: list[str],
- pdf_bytes_list: list[bytes],
- h_lang_list: list[str],
- parse_method: str,
- backend: str,
- f_draw_layout_bbox: bool,
- f_dump_md: bool,
- f_dump_middle_json: bool,
- f_dump_model_output: bool,
- f_dump_orig_pdf: bool,
- f_dump_content_list: bool,
- f_make_md_mode: str,
- server_url: str | None = None,
- page_index_map_list: list[list[int] | None] | None = None,
- broken_page_indices_list: list[list[int] | None] | None = None,
- **kwargs: Any,
-) -> None:
- aio_hybrid_doc_analyze = _load_hybrid_analyze_entrypoint(
- "aio_doc_analyze",
- f"hybrid-{backend}",
- )
- """异步处理hybrid后端逻辑"""
- if not backend.endswith("client"):
- server_url = None
-
- for idx, (pdf_bytes, lang) in enumerate(zip(pdf_bytes_list, h_lang_list)):
- pdf_file_name = pdf_file_names[idx]
- local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"hybrid_{parse_method}")
- md_writer = FileBasedDataWriter(local_md_dir)
- image_cache = ImagePayloadCache()
-
- middle_json, infer_result, _ = await aio_hybrid_doc_analyze(
- pdf_bytes,
- backend=backend,
- parse_method=parse_method,
- language=lang,
- server_url=server_url,
- page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
- image_cache=image_cache,
- **kwargs,
- )
-
- _process_output(
- middle_json,
- pdf_bytes,
- pdf_file_name,
- local_md_dir,
- local_image_dir,
- md_writer,
- f_draw_layout_bbox,
- f_dump_orig_pdf,
- f_dump_md,
- f_dump_content_list,
- f_dump_middle_json,
- f_dump_model_output,
- f_make_md_mode,
- infer_result,
- process_mode="hybrid",
- backend="hybrid",
- retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
- broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
- image_cache=image_cache,
- )
-
-
-def _process_office_doc(
- output_dir: str,
- pdf_file_names: list[str],
- pdf_bytes_list: list[bytes],
- f_dump_md: bool = True,
- f_dump_middle_json: bool = True,
- f_dump_model_output: bool = True,
- f_dump_orig_file: bool = True,
- f_dump_content_list: bool = True,
- f_make_md_mode: str = "mm_markdown",
-) -> list[int]:
- need_remove_index = []
- for i, file_bytes in enumerate(pdf_bytes_list):
- pdf_file_name = pdf_file_names[i]
- file_suffix = guess_suffix_by_bytes(file_bytes)
- if file_suffix in office_suffixes:
- need_remove_index.append(i)
-
- local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, "office")
- md_writer = FileBasedDataWriter(local_md_dir)
-
- image_cache = ImagePayloadCache()
- middle_json, infer_result = office_analyze(
- file_bytes=file_bytes,
- file_suffix=file_suffix,
- image_cache=image_cache,
- )
-
- f_draw_layout_bbox = False
-
- _process_output(
- middle_json,
- file_bytes,
- pdf_file_name,
- local_md_dir,
- local_image_dir,
- md_writer,
- f_draw_layout_bbox,
- f_dump_orig_file,
- f_dump_md,
- f_dump_content_list,
- f_dump_middle_json,
- f_dump_model_output,
- f_make_md_mode,
- infer_result,
- process_mode=file_suffix,
- backend="office",
- image_cache=image_cache,
- )
-
- return need_remove_index
-
-
-def do_parse(
- output_dir: str,
- pdf_file_names: list[str],
- pdf_bytes_list: list[bytes],
- p_lang_list: list[str],
- backend: str = DEFAULT_BACKEND,
- parse_method: str = "auto",
- server_url: str | None = None,
- f_draw_layout_bbox: bool = True,
- f_dump_md: bool = True,
- f_dump_middle_json: bool = True,
- f_dump_model_output: bool = True,
- f_dump_orig_pdf: bool = True,
- f_dump_content_list: bool = True,
- f_make_md_mode: str = "mm_markdown",
- start_page_id: int = 0,
- end_page_id: int | None = None,
- image_analysis: bool = True,
- effort: str = DEFAULT_HYBRID_EFFORT,
- client_side_output_generation: bool = False,
- **kwargs: Any,
-) -> None:
- if "f_draw_span_bbox" in kwargs:
- raise TypeError("f_draw_span_bbox is no longer supported because InlineSpan has no bbox")
- backend, effort = resolve_backend_and_effort(backend, effort)
- need_remove_index = _process_office_doc(
- output_dir,
- pdf_file_names=pdf_file_names,
- pdf_bytes_list=pdf_bytes_list,
- f_dump_md=f_dump_md,
- f_dump_middle_json=f_dump_middle_json,
- f_dump_model_output=f_dump_model_output,
- f_dump_orig_file=f_dump_orig_pdf,
- f_dump_content_list=f_dump_content_list,
- f_make_md_mode=f_make_md_mode,
- )
- for index in sorted(need_remove_index, reverse=True):
- del pdf_bytes_list[index]
- del pdf_file_names[index]
- del p_lang_list[index]
- if not pdf_bytes_list:
- logger.warning("No valid PDF or image files to process.")
- return
-
- # 预处理PDF字节数据,同时保留裁剪后 PDF 页序到原始页号的映射。
- prepared_pdf_inputs = _prepare_pdf_inputs(pdf_bytes_list, start_page_id, end_page_id)
- pdf_bytes_list = [prepared.pdf_bytes for prepared in prepared_pdf_inputs]
- page_index_map_list = [prepared.retained_page_indices for prepared in prepared_pdf_inputs]
- broken_page_indices_list = [prepared.broken_page_indices for prepared in prepared_pdf_inputs]
-
- if backend.startswith("hybrid-"):
- ensure_backend_dependencies(backend)
- backend = backend[7:]
-
- if backend == "engine" and effort != LOCAL_HYBRID_EFFORT:
- backend = get_vlm_engine(inference_engine="auto", is_async=False)
-
- _process_hybrid(
- output_dir,
- pdf_file_names,
- pdf_bytes_list,
- p_lang_list,
- parse_method,
- backend,
- f_draw_layout_bbox,
- f_dump_md,
- f_dump_middle_json,
- f_dump_model_output,
- f_dump_orig_pdf,
- f_dump_content_list,
- f_make_md_mode,
- server_url,
- page_index_map_list=page_index_map_list,
- broken_page_indices_list=broken_page_indices_list,
- image_analysis=image_analysis,
- effort=effort,
- client_side_output_generation=client_side_output_generation,
- **kwargs,
- )
- else:
- raise ValueError(f"Unsupported backend '{backend}'")
-
-
-async def aio_do_parse(
- output_dir: str,
- pdf_file_names: list[str],
- pdf_bytes_list: list[bytes],
- p_lang_list: list[str],
- backend: str = DEFAULT_BACKEND,
- parse_method: str = "auto",
- server_url: str | None = None,
- f_draw_layout_bbox: bool = True,
- f_dump_md: bool = True,
- f_dump_middle_json: bool = True,
- f_dump_model_output: bool = True,
- f_dump_orig_pdf: bool = True,
- f_dump_content_list: bool = True,
- f_make_md_mode: str = "mm_markdown",
- start_page_id: int = 0,
- end_page_id: int | None = None,
- image_analysis: bool = True,
- effort: str = DEFAULT_HYBRID_EFFORT,
- client_side_output_generation: bool = False,
- **kwargs: Any,
-) -> None:
- if "f_draw_span_bbox" in kwargs:
- raise TypeError("f_draw_span_bbox is no longer supported because InlineSpan has no bbox")
- backend, effort = resolve_backend_and_effort(backend, effort)
- # Office 解析是同步且可能耗时的操作,异步入口需要放到线程中避免阻塞事件循环。
- need_remove_index = await asyncio.to_thread(
- _process_office_doc,
- output_dir,
- pdf_file_names=pdf_file_names,
- pdf_bytes_list=pdf_bytes_list,
- f_dump_md=f_dump_md,
- f_dump_middle_json=f_dump_middle_json,
- f_dump_model_output=f_dump_model_output,
- f_dump_orig_file=f_dump_orig_pdf,
- f_dump_content_list=f_dump_content_list,
- f_make_md_mode=f_make_md_mode,
- )
- for index in sorted(need_remove_index, reverse=True):
- del pdf_bytes_list[index]
- del pdf_file_names[index]
- del p_lang_list[index]
- if not pdf_bytes_list:
- logger.warning("No valid PDF or image files to process.")
- return
-
- # 预处理PDF字节数据,同时保留裁剪后 PDF 页序到原始页号的映射。
- prepared_pdf_inputs = _prepare_pdf_inputs(pdf_bytes_list, start_page_id, end_page_id)
- pdf_bytes_list = [prepared.pdf_bytes for prepared in prepared_pdf_inputs]
- page_index_map_list = [prepared.retained_page_indices for prepared in prepared_pdf_inputs]
- broken_page_indices_list = [prepared.broken_page_indices for prepared in prepared_pdf_inputs]
-
- if backend.startswith("hybrid-"):
- ensure_backend_dependencies(backend)
- backend = backend[7:]
-
- if backend == "engine" and effort != LOCAL_HYBRID_EFFORT:
- backend = get_vlm_engine(inference_engine="auto", is_async=True)
-
- await _async_process_hybrid(
- output_dir,
- pdf_file_names,
- pdf_bytes_list,
- p_lang_list,
- parse_method,
- backend,
- f_draw_layout_bbox,
- f_dump_md,
- f_dump_middle_json,
- f_dump_model_output,
- f_dump_orig_pdf,
- f_dump_content_list,
- f_make_md_mode,
- server_url,
- page_index_map_list=page_index_map_list,
- broken_page_indices_list=broken_page_indices_list,
- image_analysis=image_analysis,
- effort=effort,
- client_side_output_generation=client_side_output_generation,
- **kwargs,
- )
- else:
- raise ValueError(f"Unsupported backend '{backend}'")
-
-
-if __name__ == "__main__":
- # pdf_path = "../../demo/pdfs/demo3.pdf"
- pdf_path = "C:/Users/zhaoxiaomeng/Downloads/4546d0e2-ba60-40a5-a17e-b68555cec741.pdf"
-
- try:
- do_parse(
- "./output",
- [Path(pdf_path).stem],
- [read_fn(Path(pdf_path))],
- ["ch"],
- end_page_id=10,
- backend="hybrid-engine",
- )
- except Exception as e:
- logger.exception(e)
diff --git a/mineru/cli_old/fast_api.py b/mineru/cli_old/fast_api.py
deleted file mode 100644
index b723d224..00000000
--- a/mineru/cli_old/fast_api.py
+++ /dev/null
@@ -1,1462 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import asyncio
-import mimetypes
-import multiprocessing
-import os
-import shutil
-import sys
-import tempfile
-import threading
-import uuid
-import zipfile
-from contextlib import asynccontextmanager, suppress
-from dataclasses import dataclass
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Annotated, Any, Optional
-
-import click
-import uvicorn
-from fastapi import (
- BackgroundTasks,
- Depends,
- FastAPI,
- HTTPException,
- Request,
- UploadFile,
-)
-from fastapi.middleware.gzip import GZipMiddleware
-from fastapi.responses import FileResponse, JSONResponse, Response
-from loguru import logger
-
-from base64 import b64encode
-
-from mineru.cli_old.common import (
- aio_do_parse,
- image_suffixes,
- office_suffixes,
- pdf_suffixes,
- normalize_task_stem,
- read_fn,
- uniquify_task_stems,
-)
-from mineru.cli_old.upload_utils import normalize_upload_filename
-from mineru.cli_old.api_request import ParseRequestOptions, parse_request_form
-from mineru.cli_old.public_http_client_policy import (
- configure_public_http_client_policy,
- is_public_bind_host,
- warn_if_public_http_client_policy as _warn_if_public_http_client_policy,
-)
-from mineru.cli_old.output_paths import resolve_parse_dir
-from mineru.cli_old.api_protocol import (
- API_PROTOCOL_VERSION,
- DEFAULT_MAX_CONCURRENT_REQUESTS,
- DEFAULT_PROCESSING_WINDOW_SIZE,
-)
-from mineru.cli_old.vlm_preload import (
- maybe_preload_vlm_model,
- split_service_and_model_config,
-)
-from mineru.model.vlm.runtime import shutdown_cached_models
-from mineru.utils.cli_parser import arg_parse
-from mineru.utils.check_sys_env import is_mac_environment
-from mineru.utils.config_reader import (
- get_max_concurrent_requests as read_max_concurrent_requests,
- get_processing_window_size,
-)
-from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
-from mineru.utils.pdf_image_tools import shutdown_pdf_render_executor
-from mineru.version import __version__
-
-os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
-log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
-logger.remove()
-logger.add(sys.stderr, level=log_level)
-
-TASK_PENDING = "pending"
-TASK_PROCESSING = "processing"
-TASK_COMPLETED = "completed"
-TASK_FAILED = "failed"
-TASK_TERMINAL_STATES = {TASK_COMPLETED, TASK_FAILED}
-SUPPORTED_UPLOAD_SUFFIXES = pdf_suffixes + image_suffixes + office_suffixes
-RESULT_IMAGE_SUFFIXES = set(image_suffixes) | {"svg"}
-DEFAULT_TASK_RETENTION_SECONDS = 24 * 60 * 60
-DEFAULT_TASK_CLEANUP_INTERVAL_SECONDS = 5 * 60
-DEFAULT_OUTPUT_ROOT = "./output"
-FILE_PARSE_TASK_ID_HEADER = "X-MinerU-Task-Id"
-FILE_PARSE_TASK_STATUS_HEADER = "X-MinerU-Task-Status"
-FILE_PARSE_TASK_STATUS_URL_HEADER = "X-MinerU-Task-Status-Url"
-FILE_PARSE_TASK_RESULT_URL_HEADER = "X-MinerU-Task-Result-Url"
-MINERU_API_PUBLIC_BIND_EXPOSED_ENV = "MINERU_API_PUBLIC_BIND_EXPOSED"
-MINERU_API_ALLOW_PUBLIC_HTTP_CLIENT_ENV = "MINERU_API_ALLOW_PUBLIC_HTTP_CLIENT"
-
-# 并发控制器
-_request_semaphore: Optional[asyncio.Semaphore] = None
-_configured_max_concurrent_requests = 1
-
-
-def env_flag_enabled(name: str, default: bool = False) -> bool:
- value = os.getenv(name)
- if value is None:
- return default
- return value.lower() in ("1", "true", "yes", "on")
-
-
-def is_main_multiprocessing_process() -> bool:
- try:
- return multiprocessing.current_process().name == "MainProcess"
- except Exception:
- return True
-
-
-def install_stdin_shutdown_watcher(server: uvicorn.Server) -> None:
- if not env_flag_enabled("MINERU_API_SHUTDOWN_ON_STDIN_EOF"):
- return
-
- def _watch_stdin_for_eof() -> None:
- stdin_stream = getattr(sys.stdin, "buffer", sys.stdin)
- try:
- stdin_stream.read()
- except Exception:
- return
- server.should_exit = True
-
- watcher = threading.Thread(
- target=_watch_stdin_for_eof,
- name="mineru-api-stdin-shutdown",
- daemon=True,
- )
- watcher.start()
-
-
-@dataclass
-class StoredUpload:
- original_name: str
- stem: str
- path: str
-
-
-@dataclass
-class AsyncParseTask:
- task_id: str
- status: str
- backend: str
- file_names: list[str]
- created_at: str
- output_dir: str
- parse_method: str
- effort: str
- lang_list: list[str]
- image_analysis: bool
- server_url: Optional[str]
- return_md: bool
- return_middle_json: bool
- return_model_output: bool
- return_content_list: bool
- return_images: bool
- response_format_zip: bool
- return_original_file: bool
- client_side_output_generation: bool
- start_page_id: int
- end_page_id: int
- upload_names: list[str]
- uploads: list[str]
- submit_order: int = 0
- started_at: Optional[str] = None
- completed_at: Optional[str] = None
- error: Optional[str] = None
-
- def to_status_payload(
- self,
- request: Request,
- queued_ahead: int | None = None,
- ) -> dict[str, Any]:
- payload = {
- "task_id": self.task_id,
- "status": self.status,
- "backend": self.backend,
- "file_names": self.file_names,
- "created_at": self.created_at,
- "started_at": self.started_at,
- "completed_at": self.completed_at,
- "error": self.error,
- "status_url": str(
- request.url_for("get_async_task_status", task_id=self.task_id)
- ),
- "result_url": str(
- request.url_for("get_async_task_result", task_id=self.task_id)
- ),
- }
- if queued_ahead is not None:
- payload["queued_ahead"] = queued_ahead
- return payload
-
-
-class TaskWaitAbortedError(RuntimeError):
- """Raised when a synchronous file_parse request cannot keep waiting safely."""
-
-
-@asynccontextmanager
-async def lifespan(app: FastAPI):
- await startup_app_state(app)
- try:
- yield
- finally:
- await shutdown_app_state(app)
-
-
-def create_app():
- # By default, the OpenAPI documentation endpoints (openapi_url, docs_url, redoc_url) are enabled.
- # To disable the FastAPI docs and schema endpoints, set the environment variable MINERU_API_ENABLE_FASTAPI_DOCS=0.
- enable_docs = env_flag_enabled("MINERU_API_ENABLE_FASTAPI_DOCS", default=True)
- app = FastAPI(
- 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,
- )
-
- global _request_semaphore, _configured_max_concurrent_requests
-
- if is_mac_environment():
- max_concurrent_requests = 1
- else:
- max_concurrent_requests = read_max_concurrent_requests(
- default=DEFAULT_MAX_CONCURRENT_REQUESTS
- )
-
- _configured_max_concurrent_requests = max_concurrent_requests
- app.state.max_concurrent_requests = max_concurrent_requests
- _request_semaphore = asyncio.Semaphore(max_concurrent_requests)
- if is_main_multiprocessing_process():
- logger.info(f"Request concurrency limited to {max_concurrent_requests}")
-
- app.add_middleware(GZipMiddleware, minimum_size=1000)
- app.state.public_bind_exposed = env_flag_enabled(
- MINERU_API_PUBLIC_BIND_EXPOSED_ENV,
- default=False,
- )
- app.state.allow_public_http_client = env_flag_enabled(
- MINERU_API_ALLOW_PUBLIC_HTTP_CLIENT_ENV,
- default=False,
- )
- default_service_config, default_model_config = split_service_and_model_config(
- {
- "enable_vlm_preload": env_flag_enabled(
- "MINERU_API_ENABLE_VLM_PRELOAD",
- default=False,
- )
- }
- )
- app.state.service_config = default_service_config
- app.state.config = default_model_config
- app.state.task_manager = None
- return app
-
-
-app = create_app()
-
-
-async def startup_app_state(app: FastAPI) -> "AsyncTaskManager":
- task_manager = AsyncTaskManager(app)
- await task_manager.start()
- try:
- service_config = getattr(app.state, "service_config", {})
- model_config = getattr(app.state, "config", {})
- maybe_preload_vlm_model(
- bool(service_config.get("enable_vlm_preload", False)),
- model_kwargs=model_config,
- )
- except Exception:
- await task_manager.shutdown()
- app.state.task_manager = None
- raise
-
- app.state.task_manager = task_manager
- return task_manager
-
-
-async def shutdown_app_state(app: FastAPI) -> None:
- current_task_manager = getattr(app.state, "task_manager", None)
- if current_task_manager is not None:
- await current_task_manager.shutdown()
- app.state.task_manager = None
- shutdown_runtime_resources()
-
-
-def shutdown_runtime_resources() -> None:
- try:
- shutdown_cached_models()
- except Exception as exc:
- logger.warning(f"Failed to shutdown cached VLM models: {exc}")
-
- try:
- shutdown_pdf_render_executor()
- except Exception as exc:
- logger.warning(f"Failed to shutdown PDF render executor: {exc}")
-
-
-def utc_now_iso() -> str:
- return datetime.now(timezone.utc).isoformat()
-
-
-def get_int_env(name: str, default: int, minimum: int = 0) -> int:
- try:
- value = int(os.getenv(name, str(default)))
- except ValueError:
- return default
- if value < minimum:
- return default
- return value
-
-
-def get_max_concurrent_requests() -> int:
- return _configured_max_concurrent_requests
-
-
-def get_task_retention_seconds() -> int:
- return get_int_env(
- "MINERU_API_TASK_RETENTION_SECONDS",
- DEFAULT_TASK_RETENTION_SECONDS,
- minimum=0,
- )
-
-
-def get_task_cleanup_interval_seconds() -> int:
- return get_int_env(
- "MINERU_API_TASK_CLEANUP_INTERVAL_SECONDS",
- DEFAULT_TASK_CLEANUP_INTERVAL_SECONDS,
- minimum=1,
- )
-
-
-def get_output_root() -> Path:
- root = Path(os.getenv("MINERU_API_OUTPUT_ROOT", DEFAULT_OUTPUT_ROOT)).expanduser()
- root.mkdir(parents=True, exist_ok=True)
- return root.resolve()
-
-
-def warn_if_public_http_client_policy(host: str, allow_public_http_client: bool) -> None:
- _warn_if_public_http_client_policy(
- service_name="API",
- host=host,
- allow_public_http_client=allow_public_http_client,
- )
-
-
-def cleanup_file(file_path: str) -> None:
- """清理临时文件或目录"""
- try:
- if os.path.exists(file_path):
- if os.path.isfile(file_path):
- os.remove(file_path)
- elif os.path.isdir(file_path):
- shutil.rmtree(file_path)
- except Exception as e:
- logger.warning(f"fail clean file {file_path}: {e}")
-
-
-def build_upload_destination(upload_dir: str, filename: str) -> Path:
- destination = Path(upload_dir) / filename
- if not destination.exists():
- return destination
-
- base_name = Path(filename).stem
- suffix = Path(filename).suffix
- index = 2
- while True:
- candidate = Path(upload_dir) / f"{base_name}__upload_{index}{suffix}"
- if not candidate.exists():
- return candidate
- index += 1
-
-
-def encode_image(image_path: str) -> str:
- """Encode image using base64"""
- with open(image_path, "rb") as f:
- return b64encode(f.read()).decode()
-
-
-def get_images_dir_image_paths(images_dir: str) -> list[str]:
- """Return all supported image files directly under images_dir."""
- if not os.path.isdir(images_dir):
- return []
-
- return sorted(
- str(path)
- for path in Path(images_dir).iterdir()
- if path.is_file() and path.suffix.lstrip(".").lower() in RESULT_IMAGE_SUFFIXES
- )
-
-
-def get_image_mime_type(image_path: str) -> str:
- mime_type, _ = mimetypes.guess_type(image_path)
- if mime_type:
- return mime_type
- return "image/jpeg"
-
-
-def get_infer_result(
- file_suffix_identifier: str, pdf_name: str, parse_dir: str
-) -> Optional[str]:
- """从结果文件中读取推理结果"""
- result_file_path = os.path.join(parse_dir, f"{pdf_name}{file_suffix_identifier}")
- if os.path.exists(result_file_path):
- with open(result_file_path, "r", encoding="utf-8") as fp:
- return fp.read()
- return None
-
-
-def normalize_lang_list(lang_list: list[str], file_count: int) -> list[str]:
- if len(lang_list) == file_count:
- return lang_list
- base_lang = lang_list[0] if lang_list else "ch"
- return [base_lang] * file_count
-
-
-def get_parse_dir(output_dir: str, pdf_name: str, backend: str, parse_method: str) -> str:
- return str(
- resolve_parse_dir(
- output_dir,
- pdf_name,
- backend,
- parse_method,
- allow_office_fallback=True,
- )
- )
-
-
-def is_task_terminal(status: str) -> bool:
- return status in TASK_TERMINAL_STATES
-
-
-def build_result_dict(
- output_dir: str,
- pdf_file_names: list[str],
- backend: str,
- parse_method: str,
- return_md: bool,
- return_middle_json: bool,
- return_model_output: bool,
- return_content_list: bool,
- return_images: bool,
-) -> dict[str, dict[str, Any]]:
- result_dict: dict[str, dict[str, Any]] = {}
- for pdf_name in pdf_file_names:
- result_dict[pdf_name] = {}
- data = result_dict[pdf_name]
-
- try:
- parse_dir = get_parse_dir(output_dir, pdf_name, backend, parse_method)
- except ValueError:
- logger.warning(f"Unknown backend type: {backend}, skipping {pdf_name}")
- continue
-
- if not os.path.exists(parse_dir):
- continue
-
- if return_md:
- data["md_content"] = get_infer_result(".md", pdf_name, parse_dir)
- if return_middle_json:
- data["middle_json"] = get_infer_result("_middle.json", pdf_name, parse_dir)
- if return_model_output:
- data["model_output"] = get_infer_result("_model.json", pdf_name, parse_dir)
- if return_content_list:
- data["content_list"] = get_infer_result(
- "_content_list.json", pdf_name, parse_dir
- )
- if return_images:
- images_dir = os.path.join(parse_dir, "images")
- image_paths = get_images_dir_image_paths(images_dir)
- data["images"] = {
- os.path.basename(
- image_path
- ): f"data:{get_image_mime_type(image_path)};base64,{encode_image(image_path)}"
- for image_path in image_paths
- }
- 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],
- backend: str,
- parse_method: str,
- return_md: bool,
- return_middle_json: bool,
- 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:
- try:
- parse_dir = get_parse_dir(output_dir, pdf_name, backend, parse_method)
- except ValueError:
- logger.warning(f"Unknown backend type: {backend}, skipping {pdf_name}")
- continue
-
- if not os.path.exists(parse_dir):
- continue
-
- if return_md:
- path = os.path.join(parse_dir, f"{pdf_name}.md")
- if os.path.exists(path):
- zf.write(
- path,
- arcname=build_zip_arcname(
- pdf_name,
- parse_dir,
- f"{pdf_name}.md",
- ),
- )
-
- if return_middle_json:
- path = os.path.join(parse_dir, f"{pdf_name}_middle.json")
- if os.path.exists(path):
- zf.write(
- path,
- arcname=build_zip_arcname(
- pdf_name,
- parse_dir,
- f"{pdf_name}_middle.json",
- ),
- )
-
- if return_model_output:
- path = os.path.join(parse_dir, f"{pdf_name}_model.json")
- if os.path.exists(path):
- zf.write(
- path,
- arcname=build_zip_arcname(
- pdf_name,
- parse_dir,
- f"{pdf_name}_model.json",
- ),
- )
-
- if return_content_list:
- path = os.path.join(parse_dir, f"{pdf_name}_content_list.json")
- if os.path.exists(path):
- zf.write(
- path,
- arcname=build_zip_arcname(
- pdf_name,
- parse_dir,
- f"{pdf_name}_content_list.json",
- ),
- )
-
- path = os.path.join(parse_dir, f"{pdf_name}_structured_content.json")
- if os.path.exists(path):
- zf.write(
- path,
- arcname=build_zip_arcname(
- pdf_name,
- parse_dir,
- f"{pdf_name}_structured_content.json",
- ),
- )
-
- if return_images:
- images_dir = os.path.join(parse_dir, "images")
- image_paths = get_images_dir_image_paths(images_dir)
- for image_path in image_paths:
- zf.write(
- 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
-
-
-def _cleanup_generated_zip_task(task: asyncio.Task[str]) -> None:
- try:
- generated_zip_path = task.result()
- except asyncio.CancelledError:
- return
- except Exception:
- return
- cleanup_file(generated_zip_path)
-
-
-async def build_result_response(
- background_tasks: BackgroundTasks,
- status_code: int,
- output_dir: str,
- pdf_file_names: list[str],
- backend: str,
- parse_method: str,
- return_md: bool,
- return_middle_json: bool,
- return_model_output: bool,
- return_content_list: bool,
- return_images: bool,
- response_format_zip: bool,
- return_original_file: bool,
- zip_filename: str = "results.zip",
-) -> Response:
- if response_format_zip:
- zip_task = asyncio.create_task(
- asyncio.to_thread(
- create_result_zip,
- output_dir=output_dir,
- pdf_file_names=pdf_file_names,
- backend=backend,
- parse_method=parse_method,
- return_md=return_md,
- return_middle_json=return_middle_json,
- return_model_output=return_model_output,
- return_content_list=return_content_list,
- return_images=return_images,
- return_original_file=return_original_file,
- )
- )
- try:
- zip_path = await asyncio.shield(zip_task)
- except asyncio.CancelledError:
- zip_task.add_done_callback(_cleanup_generated_zip_task)
- raise
- background_tasks.add_task(cleanup_file, zip_path)
- return FileResponse(
- path=zip_path,
- media_type="application/zip",
- filename=zip_filename,
- status_code=status_code,
- )
-
- result_dict = await asyncio.to_thread(
- build_result_dict,
- output_dir=output_dir,
- pdf_file_names=pdf_file_names,
- backend=backend,
- parse_method=parse_method,
- return_md=return_md,
- return_middle_json=return_middle_json,
- return_model_output=return_model_output,
- return_content_list=return_content_list,
- return_images=return_images,
- )
- return JSONResponse(
- status_code=status_code,
- content={
- "backend": backend,
- "version": __version__,
- "results": result_dict,
- },
- )
-
-
-def build_task_submission_response(
- task: AsyncParseTask,
- request: Request,
- task_manager: "AsyncTaskManager",
-) -> JSONResponse:
- payload = task_manager.build_status_payload(task, request)
- payload["message"] = "Task submitted successfully"
- return JSONResponse(status_code=202, content=payload)
-
-
-async def build_sync_file_parse_response(
- background_tasks: BackgroundTasks,
- task: AsyncParseTask,
- request: Request,
-) -> Response:
- task_payload = task.to_status_payload(request)
- if task.response_format_zip:
- response = await build_result_response(
- background_tasks=background_tasks,
- status_code=200,
- output_dir=task.output_dir,
- pdf_file_names=task.file_names,
- backend=task.backend,
- parse_method=task.parse_method,
- return_md=task.return_md,
- return_middle_json=task.return_middle_json,
- return_model_output=task.return_model_output,
- 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,
- zip_filename=f"{task.task_id}.zip",
- )
- response.headers[FILE_PARSE_TASK_ID_HEADER] = task.task_id
- response.headers[FILE_PARSE_TASK_STATUS_HEADER] = task.status
- response.headers[FILE_PARSE_TASK_STATUS_URL_HEADER] = task_payload["status_url"]
- response.headers[FILE_PARSE_TASK_RESULT_URL_HEADER] = task_payload["result_url"]
- return response
-
- result_dict = await asyncio.to_thread(
- build_result_dict,
- output_dir=task.output_dir,
- pdf_file_names=task.file_names,
- backend=task.backend,
- parse_method=task.parse_method,
- return_md=task.return_md,
- return_middle_json=task.return_middle_json,
- return_model_output=task.return_model_output,
- return_content_list=task.return_content_list,
- return_images=task.return_images,
- )
- return JSONResponse(
- status_code=200,
- content={
- **task_payload,
- "backend": task.backend,
- "version": __version__,
- "results": result_dict,
- },
- )
-
-
-async def save_upload_files(upload_dir: str, files: list[UploadFile]) -> list[StoredUpload]:
- os.makedirs(upload_dir, exist_ok=True)
- uploads: list[StoredUpload] = []
-
- for upload in files:
- original_name = upload.filename or f"upload-{uuid.uuid4()}"
- filename = normalize_upload_filename(original_name)
- normalized_stem = normalize_task_stem(Path(filename).stem)
- destination = build_upload_destination(upload_dir, filename)
- try:
- with open(destination, "wb") as handle:
- while True:
- chunk = await upload.read(1 << 20)
- if not chunk:
- break
- handle.write(chunk)
-
- file_suffix = guess_suffix_by_path(destination)
- if file_suffix not in SUPPORTED_UPLOAD_SUFFIXES:
- cleanup_file(str(destination))
- raise HTTPException(
- status_code=400,
- detail=f"Unsupported file type: {file_suffix}",
- )
-
- uploads.append(
- StoredUpload(
- original_name=original_name,
- stem=normalized_stem,
- path=str(destination),
- )
- )
- except Exception:
- cleanup_file(str(destination))
- raise
- finally:
- await upload.close()
-
- normalized_stems, renamed_stems = uniquify_task_stems(
- [upload.stem for upload in uploads]
- )
- if renamed_stems:
- rename_details = ", ".join(
- f"{Path(upload.original_name).name} -> {effective_stem}"
- for upload, effective_stem in zip(uploads, normalized_stems)
- if upload.stem != effective_stem
- )
- logger.warning(
- f"Normalized duplicate upload stems within request: {rename_details}"
- )
- uploads = [
- StoredUpload(
- original_name=upload.original_name,
- stem=effective_stem,
- path=upload.path,
- )
- for upload, effective_stem in zip(uploads, normalized_stems)
- ]
- return uploads
-
-
-def load_parse_inputs(uploads: list[StoredUpload]) -> tuple[list[str], list[bytes]]:
- pdf_file_names = []
- pdf_bytes_list = []
-
- for upload in uploads:
- try:
- pdf_bytes = read_fn(Path(upload.path))
- except Exception as exc:
- raise RuntimeError(f"Failed to load file {upload.original_name}: {exc}") from exc
- pdf_file_names.append(upload.stem)
- pdf_bytes_list.append(pdf_bytes)
- return pdf_file_names, pdf_bytes_list
-
-
-async def run_parse_job(
- output_dir: str,
- uploads: list[StoredUpload],
- request_options: ParseRequestOptions | AsyncParseTask,
- config: dict[str, Any],
-) -> list[str]:
- pdf_file_names, pdf_bytes_list = await asyncio.to_thread(load_parse_inputs, uploads)
- actual_lang_list = normalize_lang_list(request_options.lang_list, len(pdf_file_names))
- response_file_names = list(pdf_file_names)
-
- parse_kwargs = dict(
- output_dir=output_dir,
- pdf_file_names=list(pdf_file_names),
- pdf_bytes_list=list(pdf_bytes_list),
- p_lang_list=list(actual_lang_list),
- backend=request_options.backend,
- parse_method=request_options.parse_method,
- effort=request_options.effort,
- image_analysis=request_options.image_analysis,
- server_url=request_options.server_url,
- f_draw_layout_bbox=False,
- 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=(
- 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,
- client_side_output_generation=getattr(
- request_options,
- "client_side_output_generation",
- False,
- ),
- **config,
- )
-
- await aio_do_parse(**parse_kwargs)
- return response_file_names
-
-
-def create_task_output_dir(task_id: str) -> str:
- output_root = get_output_root()
- task_output_dir = output_root / task_id
- task_output_dir.mkdir(parents=True, exist_ok=True)
- return str(task_output_dir)
-
-
-async def create_async_parse_task(
- request_options: ParseRequestOptions,
-) -> AsyncParseTask:
- task_id = str(uuid.uuid4())
- task_output_dir = create_task_output_dir(task_id)
- uploads_dir = os.path.join(task_output_dir, "uploads")
- task_manager = get_task_manager()
-
- try:
- uploads = await save_upload_files(uploads_dir, request_options.files)
- request_options.files.clear()
- file_names = [upload.stem for upload in uploads]
- task = AsyncParseTask(
- task_id=task_id,
- status=TASK_PENDING,
- backend=request_options.backend,
- file_names=file_names,
- created_at=utc_now_iso(),
- output_dir=task_output_dir,
- parse_method=request_options.parse_method,
- effort=request_options.effort,
- lang_list=request_options.lang_list,
- image_analysis=request_options.image_analysis,
- server_url=request_options.server_url,
- return_md=request_options.return_md,
- return_middle_json=request_options.return_middle_json,
- return_model_output=request_options.return_model_output,
- 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,
- client_side_output_generation=request_options.client_side_output_generation,
- start_page_id=request_options.start_page_id,
- end_page_id=request_options.end_page_id,
- upload_names=[upload.original_name for upload in uploads],
- uploads=[upload.path for upload in uploads],
- )
- await task_manager.submit(task)
- return task
- except HTTPException:
- cleanup_file(task_output_dir)
- raise
- except Exception:
- cleanup_file(task_output_dir)
- raise
-
-
-class AsyncTaskManager:
- def __init__(self, fastapi_app: FastAPI):
- self.app = fastapi_app
- self.tasks: dict[str, AsyncParseTask] = {}
- self.task_events: dict[str, asyncio.Event] = {}
- self.queue: asyncio.Queue[str] = asyncio.Queue()
- self.dispatcher_task: Optional[asyncio.Task[Any]] = None
- self.cleanup_task: Optional[asyncio.Task[Any]] = None
- self.active_tasks: set[asyncio.Task[Any]] = set()
- self.last_worker_error: Optional[str] = None
- self.is_shutting_down = False
- self.task_retention_seconds = get_task_retention_seconds()
- self.task_cleanup_interval_seconds = get_task_cleanup_interval_seconds()
- self.manager_wakeup = asyncio.Event()
- self._next_submit_order = 1
-
- async def start(self) -> None:
- self.is_shutting_down = False
- self.last_worker_error = None
- self.manager_wakeup = asyncio.Event()
- if self.dispatcher_task is None or self.dispatcher_task.done():
- self.dispatcher_task = asyncio.create_task(
- self._dispatcher_loop(), name="mineru-fastapi-task-dispatcher"
- )
- if (
- self.task_retention_seconds > 0
- and (self.cleanup_task is None or self.cleanup_task.done())
- ):
- self.cleanup_task = asyncio.create_task(
- self._cleanup_loop(), name="mineru-fastapi-task-cleanup"
- )
-
- async def shutdown(self) -> None:
- self.is_shutting_down = True
- self._wake_waiters()
- if self.dispatcher_task is not None:
- self.dispatcher_task.cancel()
- with suppress(asyncio.CancelledError):
- await self.dispatcher_task
- self.dispatcher_task = None
- if self.cleanup_task is not None:
- self.cleanup_task.cancel()
- with suppress(asyncio.CancelledError):
- await self.cleanup_task
- self.cleanup_task = None
-
- pending = list(self.active_tasks)
- for processor in pending:
- processor.cancel()
- if pending:
- await asyncio.gather(*pending, return_exceptions=True)
- self.active_tasks.clear()
-
- async def submit(self, task: AsyncParseTask) -> None:
- task.submit_order = self._next_submit_order
- self._next_submit_order += 1
- self.tasks[task.task_id] = task
- self.task_events[task.task_id] = asyncio.Event()
- await self.queue.put(task.task_id)
-
- def get(self, task_id: str) -> Optional[AsyncParseTask]:
- return self.tasks.get(task_id)
-
- def get_queued_ahead(self, task_id: str) -> int | None:
- task = self.tasks.get(task_id)
- if task is None:
- return None
- if task.status != TASK_PENDING:
- return 0
-
- return sum(
- 1
- for other_task in self.tasks.values()
- if (
- other_task.task_id != task_id
- and other_task.status == TASK_PENDING
- and 0 < other_task.submit_order < task.submit_order
- )
- )
-
- def build_status_payload(
- self,
- task: AsyncParseTask,
- request: Request,
- ) -> dict[str, Any]:
- return task.to_status_payload(
- request,
- queued_ahead=self.get_queued_ahead(task.task_id),
- )
-
- async def wait_for_terminal_state(self, task_id: str) -> AsyncParseTask:
- task = self.tasks.get(task_id)
- if task is None:
- raise TaskWaitAbortedError("Task not found")
- if is_task_terminal(task.status):
- return task
-
- task_event = self.task_events.get(task_id)
- if task_event is None:
- raise TaskWaitAbortedError("Task wait handle is unavailable")
-
- event_wait_task = asyncio.create_task(task_event.wait())
- manager_wait_task = asyncio.create_task(self.manager_wakeup.wait())
- done: set[asyncio.Task[Any]] = set()
- pending: set[asyncio.Task[Any]] = set()
- try:
- done, pending = await asyncio.wait(
- {event_wait_task, manager_wait_task},
- return_when=asyncio.FIRST_COMPLETED,
- )
- finally:
- for waiter in pending:
- waiter.cancel()
- if pending:
- await asyncio.gather(*pending, return_exceptions=True)
- for waiter in done:
- with suppress(asyncio.CancelledError):
- waiter.result()
-
- task = self.tasks.get(task_id)
- if task is None:
- if self.is_shutting_down:
- raise TaskWaitAbortedError("Task manager is shutting down")
- raise TaskWaitAbortedError("Task was removed before completion")
- if is_task_terminal(task.status):
- return task
- if self.is_shutting_down:
- raise TaskWaitAbortedError("Task manager is shutting down")
- raise TaskWaitAbortedError(
- self.last_worker_error or "Task manager became unavailable while waiting"
- )
-
- def get_stats(self) -> dict[str, int]:
- stats = {
- TASK_PENDING: 0,
- TASK_PROCESSING: 0,
- TASK_COMPLETED: 0,
- TASK_FAILED: 0,
- }
- for task in self.tasks.values():
- if task.status in stats:
- stats[task.status] += 1
- return stats
-
- def is_healthy(self) -> bool:
- if self.dispatcher_task is None:
- return False
- if self.dispatcher_task.done() and not self.is_shutting_down:
- return False
- if self.task_retention_seconds > 0 and self.cleanup_task is None:
- return False
- if (
- self.task_retention_seconds > 0
- and self.cleanup_task is not None
- and self.cleanup_task.done()
- and not self.is_shutting_down
- ):
- return False
- return self.last_worker_error is None
-
- def _wake_waiters(self) -> None:
- self.manager_wakeup.set()
- for task_event in self.task_events.values():
- task_event.set()
-
- def _signal_task_event(self, task_id: str) -> None:
- task_event = self.task_events.get(task_id)
- if task_event is not None:
- task_event.set()
-
- async def _dispatcher_loop(self) -> None:
- try:
- while True:
- task_id = await self.queue.get()
- processor = asyncio.create_task(
- self._process_task(task_id),
- name=f"mineru-fastapi-task-{task_id}",
- )
- self.active_tasks.add(processor)
- processor.add_done_callback(self._on_processor_done)
- self.queue.task_done()
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- self.last_worker_error = str(exc)
- self._wake_waiters()
- logger.exception("Async task dispatcher crashed")
- raise
-
- async def _cleanup_loop(self) -> None:
- try:
- while True:
- await asyncio.sleep(self.task_cleanup_interval_seconds)
- self.cleanup_expired_tasks()
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- self.last_worker_error = str(exc)
- logger.exception("Async task cleanup loop crashed")
- raise
-
- def _on_processor_done(self, processor: asyncio.Task[Any]) -> None:
- self.active_tasks.discard(processor)
- if processor.cancelled():
- return
- exception = processor.exception()
- if exception is not None:
- logger.error(f"Async task processor crashed: {exception}")
- self.last_worker_error = str(exception)
-
- async def _process_task(self, task_id: str) -> None:
- task = self.tasks.get(task_id)
- if task is None:
- return
-
- try:
- if _request_semaphore is not None:
- async with _request_semaphore:
- await self._run_task(task)
- else:
- await self._run_task(task)
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- task.status = TASK_FAILED
- task.error = str(exc)
- task.completed_at = utc_now_iso()
- self._signal_task_event(task_id)
- logger.exception(f"Async task failed: {task_id}")
-
- async def _run_task(self, task: AsyncParseTask) -> None:
- task.status = TASK_PROCESSING
- task.started_at = utc_now_iso()
- task.error = None
-
- uploads = [
- StoredUpload(
- original_name=upload_name,
- stem=file_name,
- path=upload_path,
- )
- for upload_name, file_name, upload_path in zip(
- task.upload_names,
- task.file_names,
- task.uploads,
- )
- ]
- config = getattr(self.app.state, "config", {})
- await run_parse_job(
- output_dir=task.output_dir,
- uploads=uploads,
- request_options=task,
- config=config,
- )
- task.status = TASK_COMPLETED
- task.completed_at = utc_now_iso()
- self._signal_task_event(task.task_id)
-
- def cleanup_expired_tasks(self) -> int:
- if self.task_retention_seconds <= 0:
- return 0
-
- now = datetime.now(timezone.utc)
- expired_task_ids = [
- task_id
- for task_id, task in self.tasks.items()
- if self._is_task_expired(task, now)
- ]
-
- for task_id in expired_task_ids:
- task = self.tasks.pop(task_id, None)
- if task is None:
- continue
- task_event = self.task_events.pop(task_id, None)
- if task_event is not None:
- task_event.set()
- cleanup_file(task.output_dir)
- logger.info(f"Cleaned expired async task: {task_id}")
- return len(expired_task_ids)
-
- def _is_task_expired(self, task: AsyncParseTask, now: datetime) -> bool:
- if task.status not in (TASK_COMPLETED, TASK_FAILED):
- return False
- if not task.completed_at:
- return False
- try:
- completed_at = datetime.fromisoformat(task.completed_at)
- except ValueError:
- logger.warning(f"Invalid completed_at for task {task.task_id}: {task.completed_at}")
- return False
- if completed_at.tzinfo is None:
- completed_at = completed_at.replace(tzinfo=timezone.utc)
- return (now - completed_at).total_seconds() >= self.task_retention_seconds
-
-
-def get_task_manager() -> AsyncTaskManager:
- task_manager = getattr(app.state, "task_manager", None)
- if task_manager is None:
- raise HTTPException(status_code=503, detail="Task manager is not initialized")
- return task_manager
-
-
- path="/file_parse",
- status_code=200,
- summary="Synchronously parse uploaded files",
- description=(
- "Submit a parsing task to the shared async task manager, wait for it to "
- "finish, and return the final parsing result in the same response."
- ),
-)
-async def parse_pdf(
- http_request: Request,
- background_tasks: BackgroundTasks,
- request_options: Annotated[
- ParseRequestOptions, Depends(parse_request_form)
- ],
-):
- task = await create_async_parse_task(request_options)
- request_options = None
- task_manager = get_task_manager()
-
- try:
- task = await task_manager.wait_for_terminal_state(task.task_id)
- except TaskWaitAbortedError as exc:
- return JSONResponse(
- status_code=503,
- content={
- **task.to_status_payload(http_request),
- "message": "Task manager became unavailable while waiting for result",
- "error": str(exc),
- },
- )
-
- if task.status == TASK_FAILED:
- return JSONResponse(
- status_code=409,
- content={
- **task.to_status_payload(http_request),
- "message": "Task execution failed",
- },
- )
-
- return await build_sync_file_parse_response(
- background_tasks=background_tasks,
- task=task,
- request=http_request,
- )
-
-
- path="/tasks",
- status_code=202,
- summary="Submit an asynchronous parse task",
- description=(
- "Submit files for parsing and return immediately with a task id that can be "
- "checked via the task status and result endpoints."
- ),
-)
-async def submit_parse_task(
- http_request: Request,
- request_options: Annotated[
- ParseRequestOptions, Depends(parse_request_form)
- ],
-):
- task_manager = get_task_manager()
- task = await create_async_parse_task(request_options)
- return build_task_submission_response(task, http_request, task_manager)
-
-
[email protected](path="/tasks/{task_id}", name="get_async_task_status")
-async def get_async_task_status(task_id: str, request: Request):
- task_manager = get_task_manager()
- task = task_manager.get(task_id)
- if task is None:
- raise HTTPException(status_code=404, detail="Task not found")
- return task_manager.build_status_payload(task, request)
-
-
[email protected](path="/tasks/{task_id}/result", name="get_async_task_result")
-async def get_async_task_result(
- task_id: str,
- request: Request,
- background_tasks: BackgroundTasks,
-):
- task_manager = get_task_manager()
- task = task_manager.get(task_id)
- if task is None:
- raise HTTPException(status_code=404, detail="Task not found")
-
- if task.status in (TASK_PENDING, TASK_PROCESSING):
- return JSONResponse(
- status_code=202,
- content={
- **task.to_status_payload(request),
- "message": "Task result is not ready yet",
- },
- )
-
- if task.status == TASK_FAILED:
- return JSONResponse(
- status_code=409,
- content={
- **task.to_status_payload(request),
- "message": "Task execution failed",
- },
- )
-
- return await build_result_response(
- background_tasks=background_tasks,
- status_code=200,
- output_dir=task.output_dir,
- pdf_file_names=task.file_names,
- backend=task.backend,
- parse_method=task.parse_method,
- return_md=task.return_md,
- return_middle_json=task.return_middle_json,
- return_model_output=task.return_model_output,
- 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,
- zip_filename=f"{task.task_id}.zip",
- )
-
-
[email protected](path="/health")
-async def health_check():
- task_manager = getattr(app.state, "task_manager", None)
- if task_manager is None or not task_manager.is_healthy():
- return JSONResponse(
- status_code=503,
- content={
- "status": "unhealthy",
- "version": __version__,
- "error": (
- "Task manager is not initialized"
- if task_manager is None
- else task_manager.last_worker_error
- or (
- "Task cleanup loop is not running"
- if (
- task_manager.task_retention_seconds > 0
- and task_manager.cleanup_task is None
- )
- else "Task dispatcher is not running"
- )
- ),
- },
- )
-
- stats = task_manager.get_stats()
- 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,
- }
-
-
- context_settings=dict(ignore_unknown_options=True, allow_extra_args=True)
-)
[email protected]("--host", default="127.0.0.1", help="Server host (default: 127.0.0.1)")
[email protected]("--port", default=8000, type=int, help="Server port (default: 8000)")
[email protected]("--reload", is_flag=True, help="Enable auto-reload (development mode)")
- "--allow-public-http-client",
- is_flag=True,
- help=(
- "Allow *-http-client backends and server_url even when binding the API to "
- "0.0.0.0 or ::."
- ),
-)
- "--enable-vlm-preload",
- "enable_vlm_preload",
- type=bool,
- default=False,
- help="Preload the local VLM model during mineru-api startup.",
-)
-def main(
- ctx,
- host,
- port,
- reload,
- allow_public_http_client,
- enable_vlm_preload,
- **kwargs,
-):
- del kwargs
- raw_config = arg_parse(ctx)
- raw_config["enable_vlm_preload"] = enable_vlm_preload
- service_config, model_config = split_service_and_model_config(raw_config)
- public_bind_exposed = is_public_bind_host(host)
-
- app.state.service_config = service_config
- app.state.config = model_config
- configure_public_http_client_policy(
- app,
- public_bind_exposed=public_bind_exposed,
- allow_public_http_client=allow_public_http_client,
- )
- os.environ["MINERU_API_ENABLE_VLM_PRELOAD"] = (
- "1" if service_config["enable_vlm_preload"] else "0"
- )
- os.environ[MINERU_API_PUBLIC_BIND_EXPOSED_ENV] = "1" if public_bind_exposed else "0"
- os.environ[MINERU_API_ALLOW_PUBLIC_HTTP_CLIENT_ENV] = (
- "1" if allow_public_http_client else "0"
- )
- warn_if_public_http_client_policy(host, allow_public_http_client)
- access_log = not env_flag_enabled("MINERU_API_DISABLE_ACCESS_LOG")
-
- print(f"Start MinerU FastAPI Service: http://{host}:{port}")
- print(f"API documentation: http://{host}:{port}/docs")
-
- if reload:
- uvicorn.run(
- "mineru.cli_old.fast_api:app",
- host=host,
- port=port,
- reload=True,
- access_log=access_log,
- )
- else:
- config = uvicorn.Config(
- app,
- host=host,
- port=port,
- reload=False,
- access_log=access_log,
- )
- server = uvicorn.Server(config)
- install_stdin_shutdown_watcher(server)
- server.run()
-
-
-if __name__ == "__main__":
- main()
diff --git a/mineru/cli_old/gradio_app.py b/mineru/cli_old/gradio_app.py
deleted file mode 100644
index e8d50953..00000000
--- a/mineru/cli_old/gradio_app.py
+++ /dev/null
@@ -1,2079 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-import atexit
-import asyncio
-import html as html_lib
-import httpx
-import json
-import os
-import re
-import subprocess
-import sys
-import tempfile
-import threading
-import time
-import uuid
-import zipfile
-from contextlib import asynccontextmanager
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Callable
-from urllib.parse import quote
-
-import click
-import gradio as gr
-from gradio_pdf import PDF
-from loguru import logger
-
-os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
-# 检测 Gradio 版本,用于兼容 Gradio 5 和 Gradio 6
-_gradio_major_version = int(gr.__version__.split('.')[0])
-IS_GRADIO_6 = _gradio_major_version >= 6
-
-log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
-logger.remove() # 移除默认handler
-logger.add(sys.stderr, level=log_level) # 添加新handler
-
-from mineru.cli_old.common import (
- image_suffixes,
- normalize_task_stem,
- office_suffixes,
- pdf_suffixes,
- read_fn,
-)
-from mineru.cli_old.visualization import (
- VISUALIZATION_FINISHED,
- VisualizationJob,
- run_visualization_job,
-)
-from mineru.cli_old import api_client as _api_client
-from mineru.parser.api_client import MinerUApiParser
-from mineru.parser.base import ParseResult
-from mineru.parser.tier import ParserRuntimeOptions, runtime_options_for_tier
-from mineru.render import render_content_list, render_markdown, render_structured_content
-from mineru.render.writer import FileBasedDataWriter
-from mineru.utils.image_payload import validate_image_sidecar_path
-from mineru.utils.pdf_document import PDFDocument
-from mineru.utils.pdf_page_id import parse_page_range
-from mineru.utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium_result
-from mineru.version import __version__
-
-_gradio_local_api_server: "ReusableGradioV1APIServer"
-
-
-@dataclass(frozen=True)
-class GradioConcurrencyWaitSnapshot:
- limit: int
- active: int
- waiting: int
- ahead: int
-
-
-@dataclass
-class _LimiterState:
- semaphore: asyncio.Semaphore
- active: int = 0
- waiters: list[object] = field(default_factory=list)
-
-
-class GradioRequestConcurrencyLimiter:
- def __init__(self):
- self._lock = threading.Lock()
- self._states: dict[int, _LimiterState] = {}
-
- def _get_state(self, limit: int):
- if limit <= 0:
- return None
- with self._lock:
- state = self._states.get(limit)
- if state is None:
- state = _LimiterState(semaphore=asyncio.Semaphore(limit))
- self._states[limit] = state
- return state
-
- def _build_wait_snapshot(
- self,
- state: _LimiterState,
- limit: int,
- wait_token: object,
- ) -> GradioConcurrencyWaitSnapshot | None:
- if wait_token not in state.waiters:
- return None
-
- return GradioConcurrencyWaitSnapshot(
- limit=limit,
- active=state.active,
- waiting=len(state.waiters),
- ahead=state.waiters.index(wait_token),
- )
-
- def _remove_waiter(self, state: _LimiterState, wait_token: object) -> None:
- if wait_token in state.waiters:
- state.waiters.remove(wait_token)
-
- async def _cleanup_acquire_interruption(
- self,
- state: _LimiterState,
- acquire_task: asyncio.Task[bool],
- wait_token: object,
- should_wait: bool,
- ) -> None:
- if not acquire_task.done():
- acquire_task.cancel()
- await asyncio.gather(acquire_task, return_exceptions=True)
- elif not acquire_task.cancelled():
- try:
- acquired = acquire_task.result()
- except Exception:
- acquired = False
- if acquired:
- state.semaphore.release()
-
- if should_wait:
- with self._lock:
- self._remove_waiter(state, wait_token)
-
- @asynccontextmanager
- async def acquire(
- self,
- limit: int,
- on_wait: Callable[[GradioConcurrencyWaitSnapshot], None] | None = None,
- ):
- state = self._get_state(limit)
- if state is None:
- yield
- return
-
- wait_token = object()
- should_wait = False
- snapshot = None
- with self._lock:
- if state.active >= limit or state.waiters:
- state.waiters.append(wait_token)
- should_wait = True
- snapshot = self._build_wait_snapshot(state, limit, wait_token)
-
- acquire_task: asyncio.Task[bool] = asyncio.create_task(state.semaphore.acquire())
- last_wait_ahead = None
- if should_wait and on_wait is not None and snapshot is not None:
- on_wait(snapshot)
- last_wait_ahead = snapshot.ahead
-
- try:
- if should_wait:
- while True:
- done, _ = await asyncio.wait(
- {acquire_task},
- timeout=STATUS_TIMER_INTERVAL_SECONDS,
- )
- if acquire_task in done:
- acquire_task.result()
- break
-
- if on_wait is None:
- continue
-
- with self._lock:
- snapshot = self._build_wait_snapshot(state, limit, wait_token)
-
- if snapshot is None or snapshot.ahead == last_wait_ahead:
- continue
-
- on_wait(snapshot)
- last_wait_ahead = snapshot.ahead
- else:
- await acquire_task
- except BaseException:
- await self._cleanup_acquire_interruption(
- state=state,
- acquire_task=acquire_task,
- wait_token=wait_token,
- should_wait=should_wait,
- )
- raise
-
- with self._lock:
- if should_wait:
- self._remove_waiter(state, wait_token)
- state.active += 1
- try:
- yield
- finally:
- with self._lock:
- state.active = max(0, state.active - 1)
- state.semaphore.release()
-
-
-_gradio_request_concurrency_limiter = GradioRequestConcurrencyLimiter()
-
-STATUS_BOX_AUTOSCROLL_JS = """
-(value) => {
- const scrollToBottom = () => {
- const textarea = document.querySelector(".convert-status-box textarea");
- if (!textarea) {
- return;
- }
- textarea.scrollTop = textarea.scrollHeight;
- };
-
- requestAnimationFrame(() => {
- scrollToBottom();
- requestAnimationFrame(scrollToBottom);
- });
-
- return [];
-}
-"""
-
-STATUS_TIMER_INTERVAL_SECONDS = 0.1
-STATUS_QUEUE_ANIMATION_INTERVAL_SECONDS = 1.0
-STATUS_QUEUE_ANIMATION_MAX_DOTS = 10
-
-STATUS_PREPARING_REQUEST = "Preparing request..."
-STATUS_CHECKING_SERVER = "Checking server status..."
-STATUS_SUBMITTING_TASK = "Submitting task..."
-STATUS_DOWNLOADING_RESULT = "Task completed, downloading result..."
-STATUS_PROCESSING_OUTPUT = "Preparing outputs..."
-STATUS_COMPLETED = "Completed"
-STATUS_QUEUED_ON_SERVER = "Queued on server"
-STATUS_PROCESSING_ON_SERVER = "Processing on server"
-STATUS_QUEUED_LOCALLY_PREFIX = "Queued locally:"
-
-DEFAULT_GRADIO_TIER = "standard"
-GRADIO_TIER_CHOICES = ("flash", "basic", "standard", "advanced")
-STATUS_STEP_DEFINITIONS = [
- ("status_step_prepare", STATUS_PREPARING_REQUEST),
- ("status_step_check", STATUS_CHECKING_SERVER),
- ("status_step_submit", STATUS_SUBMITTING_TASK),
- ("status_step_queue", STATUS_QUEUED_ON_SERVER),
- ("status_step_process", STATUS_PROCESSING_ON_SERVER),
- ("status_step_download", STATUS_DOWNLOADING_RESULT),
- ("status_step_outputs", STATUS_PROCESSING_OUTPUT),
- ("status_step_done", STATUS_COMPLETED),
-]
-
-
-@dataclass(frozen=True)
-class GradioV1ServerHealth:
- """记录 Gradio 当前绑定的 v1 API server 地址和可用 tier。"""
-
- base_url: str
- tier_choices: tuple[str, ...]
- max_concurrent_requests: int = 1
-
-
-@dataclass(frozen=True)
-class GradioV1PersistedOutput:
- """记录 v1 解析结果落盘后供 Gradio UI 继续消费的路径。"""
-
- file_name: str
- local_md_dir: Path
- archive_zip_path: Path
- preview_pdf_path: Path | None
-
-
-class GradioV1LocalAPIServer:
- """管理 Gradio 内置启动的 v1 parser API server 子进程。"""
-
- def __init__(self, extra_cli_args=()):
- self.temp_dir = tempfile.TemporaryDirectory(prefix="mineru-v1-api-client-")
- self.temp_root = Path(self.temp_dir.name)
- self.upload_dir = self.temp_root / "uploads"
- self.base_url: str | None = None
- self.process: subprocess.Popen[bytes] | None = None
- self.extra_cli_args = tuple(extra_cli_args)
- self._managed_process_group_id: int | None = None
- self._atexit_registered = False
-
- def start(self) -> str:
- """启动本地 v1 parser API server,并返回可探测的 base URL。"""
- if self.process is not None:
- raise RuntimeError("Local v1 API server is already running")
-
- resolved_port = _api_client.find_free_port()
- self.base_url = f"http://127.0.0.1:{resolved_port}"
- self.upload_dir.mkdir(parents=True, exist_ok=True)
- cli_args = (
- "--host",
- "127.0.0.1",
- "--port",
- str(resolved_port),
- "--upload-dir",
- str(self.upload_dir),
- *_api_client.strip_local_api_network_args(self.extra_cli_args),
- )
- command = [
- sys.executable,
- "-m",
- "mineru.parser.api_server",
- *cli_args,
- ]
- self.process = subprocess.Popen(
- command,
- cwd=os.getcwd(),
- env=os.environ.copy(),
- stdin=subprocess.PIPE,
- **_api_client.build_managed_process_popen_kwargs(),
- )
- self._managed_process_group_id = self.process.pid
- if not self._atexit_registered:
- atexit.register(self.stop)
- self._atexit_registered = True
- return self.base_url
-
- def stop(self) -> None:
- """停止本地 v1 parser API server,并清理临时目录。"""
- process = self.process
- process_group_id = self._managed_process_group_id
- self.process = None
- self._managed_process_group_id = None
- try:
- _api_client.stop_managed_process(
- process,
- process_group_id=process_group_id,
- shutdown_timeout_seconds=_api_client.LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS,
- use_stdin_shutdown_watcher=True,
- )
- finally:
- if self._atexit_registered:
- try:
- atexit.unregister(self.stop)
- except Exception:
- pass
- self._atexit_registered = False
- self.temp_dir.cleanup()
-
-
-class ReusableGradioV1APIServer:
- """复用 Gradio 本地 v1 API server,避免每次请求重复冷启动。"""
-
- def __init__(self, extra_cli_args=()):
- self._lock = threading.Lock()
- self._server: GradioV1LocalAPIServer | None = None
- self._extra_cli_args = tuple(extra_cli_args)
-
- def configure(self, extra_cli_args) -> None:
- """记录启动参数;若现有进程已退出,则下次请求会按新参数重启。"""
- with self._lock:
- self._extra_cli_args = tuple(extra_cli_args)
- server = self._server
- if server is None:
- return
- if server.process is not None and server.process.poll() is None:
- return
- server.stop()
- self._server = None
-
- def ensure_started(self) -> tuple[GradioV1LocalAPIServer, bool]:
- """确保本地 v1 API server 存活,返回 server 实例和是否刚启动。"""
- with self._lock:
- server = self._server
- if server is not None and server.process is not None and server.process.poll() is None:
- return server, False
- if server is not None:
- server.stop()
- server = GradioV1LocalAPIServer(extra_cli_args=self._extra_cli_args)
- server.start()
- self._server = server
- return server, True
-
- def stop(self) -> None:
- """停止当前复用的本地 v1 API server。"""
- with self._lock:
- server = self._server
- self._server = None
- if server is not None:
- server.stop()
-
-
-_gradio_local_api_server = ReusableGradioV1APIServer()
-
-
-def extract_v1_tier_choices(payload) -> tuple[str, ...]:
- """从 /v1/tiers 响应中提取 Gradio 支持的 tier,保留服务端顺序并去重。"""
- data = payload.get("data") if isinstance(payload, dict) else None
- if not isinstance(data, list):
- raise click.ClickException("MinerU v1 API /v1/tiers returned an invalid payload.")
-
- choices: list[str] = []
- for item in data:
- tier_id = item.get("id") if isinstance(item, dict) else None
- if tier_id in GRADIO_TIER_CHOICES and tier_id not in choices:
- choices.append(tier_id)
- if not choices:
- supported = ", ".join(GRADIO_TIER_CHOICES)
- raise click.ClickException(
- f"MinerU v1 API did not advertise any supported tier. Supported Gradio tiers: {supported}."
- )
- return tuple(choices)
-
-
-def default_v1_gradio_tier(tier_choices: tuple[str, ...]) -> str:
- """选择 Gradio 默认 tier;优先 standard,与 API server 的无 tier 请求默认值保持一致。"""
- if not tier_choices:
- raise click.ClickException("MinerU v1 API did not advertise any supported tier.")
- if DEFAULT_GRADIO_TIER in tier_choices:
- return DEFAULT_GRADIO_TIER
- from ..types import select_default_quality_tier
-
- return select_default_quality_tier(tier_choices) or tier_choices[0]
-
-
-async def fetch_v1_tier_choices(http_client, base_url: str) -> tuple[str, ...]:
- """调用 v1 /tiers 接口并转换成 Gradio Dropdown choices。"""
- try:
- response = await http_client.get(f"{base_url}/v1/tiers")
- except httpx.HTTPError as exc:
- raise click.ClickException(
- f"Failed to query MinerU v1 API tiers from {base_url}: {exc}"
- ) from exc
- if response.status_code != 200:
- raise click.ClickException(
- f"Failed to query MinerU v1 API tiers from {base_url}: "
- f"{response.status_code} {_api_client.response_detail(response)}"
- )
- try:
- payload = response.json()
- except json.JSONDecodeError as exc:
- raise click.ClickException(
- f"MinerU v1 API /v1/tiers from {base_url} did not return JSON."
- ) from exc
- return extract_v1_tier_choices(payload)
-
-
-async def wait_for_v1_api_ready(
- http_client,
- local_server: GradioV1LocalAPIServer,
- timeout_seconds: float = _api_client.LOCAL_API_STARTUP_TIMEOUT_SECONDS,
-) -> GradioV1ServerHealth:
- """等待本地 v1 API server 返回 /v1/tiers,避免 Gradio 页面先于服务可用。"""
- 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:
- raise click.ClickException("Local MinerU v1 API exited before becoming ready.")
- try:
- choices = await fetch_v1_tier_choices(http_client, local_server.base_url)
- return GradioV1ServerHealth(base_url=local_server.base_url, tier_choices=choices)
- except click.ClickException as exc:
- last_error = str(exc)
- except httpx.HTTPError as exc:
- last_error = str(exc)
- await asyncio.sleep(_api_client.TASK_STATUS_POLL_INTERVAL_SECONDS)
-
- message = "Timed out waiting for local MinerU v1 API to become ready."
- if last_error:
- message = f"{message} {last_error}"
- raise click.ClickException(message)
-
-
-async def resolve_v1_server_health(http_client, api_url: str | None) -> GradioV1ServerHealth:
- """解析 Gradio 当前应使用的 v1 API server,并返回该 server 的 tier 能力。"""
- if api_url:
- base_url = _api_client.normalize_base_url(api_url)
- return GradioV1ServerHealth(
- base_url=base_url,
- tier_choices=await fetch_v1_tier_choices(http_client, base_url),
- )
-
- local_server, started_now = _gradio_local_api_server.ensure_started()
- if started_now:
- logger.info(f"Started local MinerU v1 API at {local_server.base_url}")
- return await wait_for_v1_api_ready(http_client, local_server)
-
-
-def resolve_gradio_v1_startup_health(api_url: str | None) -> GradioV1ServerHealth:
- """同步探测 v1 API server tier 能力,供 Gradio 构建 Dropdown 前使用。"""
-
- async def _resolve() -> GradioV1ServerHealth:
- async with httpx.AsyncClient(
- timeout=_api_client.build_http_timeout(),
- follow_redirects=True,
- ) as http_client:
- return await resolve_v1_server_health(http_client, api_url)
-
- return asyncio.run(_resolve())
-
-
-def build_v1_gradio_page_range(end_pages: int | float | None) -> str:
- """将 Gradio 旧 max_pages 控件转换成 v1 API 使用的 1-based page_range。"""
- try:
- page_limit = int(end_pages) if end_pages is not None else 0
- except (TypeError, ValueError):
- page_limit = 0
- if page_limit <= 0:
- return ""
- return f"1~{page_limit}"
-
-
-def normalize_mineru_locale(locale):
- """统一自定义 HTML 的语言归一规则:中文使用 zh,其他语言降级为英文。"""
- normalized = str(locale or "").strip().lower()
- if normalized.startswith("zh"):
- return "zh"
- return "en"
-
-
-def resolve_i18n_text(i18n, key, locale=None):
- """按指定语言读取自定义 HTML 需要的纯文本文案,避免直接渲染 Gradio I18nData 元数据。"""
- if i18n is None:
- return key
- translations = getattr(i18n, "translations", None)
- if translations:
- preferred_locale = normalize_mineru_locale(
- locale or os.getenv("MINERU_GRADIO_DEFAULT_LOCALE", "zh")
- )
- preferred_text = translations.get(preferred_locale, {}).get(key)
- if preferred_text is not None:
- return preferred_text
- fallback_text = translations.get("en", {}).get(key)
- if fallback_text is not None:
- return fallback_text
- return key
- return i18n(key)
-
-
-def translate_ui(i18n, key, locale=None):
- """按目标语言读取纯文本文案,用作自定义 HTML 的初始渲染内容。"""
- return resolve_i18n_text(i18n, key, locale)
-
-
-def resolve_request_locale(request):
- """根据 Gradio 请求头推断浏览器语言,避免流式状态面板高频刷新时闪回默认语言。"""
- headers = getattr(request, "headers", None) or {}
- if not hasattr(headers, "get"):
- return None
-
- accept_language = headers.get("accept-language") or headers.get("Accept-Language")
- if not accept_language:
- return None
-
- language_candidates = []
- for order, raw_item in enumerate(str(accept_language).split(",")):
- parts = [part.strip() for part in raw_item.split(";") if part.strip()]
- if not parts:
- continue
- quality = 1.0
- for parameter in parts[1:]:
- name, separator, value = parameter.partition("=")
- if separator and name.strip().lower() == "q":
- try:
- quality = float(value)
- except ValueError:
- quality = 0.0
- break
- language_candidates.append((-quality, order, parts[0]))
-
- if not language_candidates:
- return None
- _, _, preferred_language = min(language_candidates)
- return normalize_mineru_locale(preferred_language)
-
-
-def build_client_i18n_attrs(i18n, key):
- """为自定义 HTML 输出中英文文案属性,交给前端按浏览器语言切换。"""
- attrs = [f'data-mineru-i18n-key="{html_lib.escape(key, quote=True)}"']
- for locale in ("en", "zh"):
- text = resolve_i18n_text(i18n, key, locale)
- attrs.append(f'data-mineru-i18n-{locale}="{html_lib.escape(text, quote=True)}"')
- return " ".join(attrs)
-
-
-def render_client_i18n_text(i18n, key, locale=None):
- """生成可被前端重新本地化的文本节点,避免 header/status 在英文环境固定成中文。"""
- return (
- f"<span {build_client_i18n_attrs(i18n, key)}>"
- f"{html_lib.escape(translate_ui(i18n, key, locale))}"
- "</span>"
- )
-
-
-def resolve_gradio_runtime_options(tier: str | None) -> ParserRuntimeOptions:
- """根据 Gradio 公开 tier 派生 v1 API 任务使用的运行配置。"""
- return runtime_options_for_tier(tier or DEFAULT_GRADIO_TIER)
-
-
-def select_tier_info_key(tier_choice: object) -> str:
- """根据 Gradio tier 选择说明文案的 i18n key。"""
- if tier_choice == "flash":
- return "tier_info_flash"
- if tier_choice == "basic":
- return "tier_info_basic"
- if tier_choice == "standard":
- return "tier_info_standard"
- if tier_choice == "advanced":
- return "tier_info_advanced"
- return "tier_info_default"
-
-
-def resolve_status_step_index(status_lines):
- """根据现有状态日志推断步骤面板中当前应高亮的步骤索引。"""
- if not status_lines:
- return -1, False
- if status_lines[-1].startswith("Failed:"):
- return len(STATUS_STEP_DEFINITIONS) - 1, True
- if any(line.startswith(STATUS_COMPLETED) for line in status_lines):
- return len(STATUS_STEP_DEFINITIONS) - 1, False
-
- for index in range(len(STATUS_STEP_DEFINITIONS) - 1, -1, -1):
- _, marker = STATUS_STEP_DEFINITIONS[index]
- if marker == STATUS_QUEUED_ON_SERVER:
- if any(StatusPanelState.is_queue_message(line) for line in status_lines):
- return index, False
- continue
- if any(line.startswith(marker) for line in status_lines):
- return index, False
- return 0, False
-
-
-def render_status_steps_html(status_text, i18n, locale=None):
- """把流式状态日志渲染为步骤式状态面板,底层日志格式保持不变。"""
- status_lines = [line for line in str(status_text or "").splitlines() if line]
- current_index, is_failed = resolve_status_step_index(status_lines)
- latest_status = (
- status_lines[-1]
- if status_lines
- else render_client_i18n_text(i18n, "status_idle_hint", locale)
- )
-
- step_items = []
- for index, (label_key, _) in enumerate(STATUS_STEP_DEFINITIONS):
- classes = ["status-step"]
- if is_failed and index == current_index:
- classes.extend(["is-active", "is-error"])
- label = render_client_i18n_text(i18n, "status_step_failed", locale)
- elif index < current_index or (
- current_index == len(STATUS_STEP_DEFINITIONS) - 1 and not is_failed
- ):
- classes.append("is-done")
- label = render_client_i18n_text(i18n, label_key, locale)
- elif index == current_index:
- classes.append("is-active")
- label = render_client_i18n_text(i18n, label_key, locale)
- else:
- classes.append("is-pending")
- label = render_client_i18n_text(i18n, label_key, locale)
- step_items.append(
- f'<div class="{" ".join(classes)}">'
- f'<span class="status-dot"></span>'
- f'<span class="status-label">{label}</span>'
- "</div>"
- )
-
- title_key = "status_idle_title" if not status_lines else "status_latest"
- return (
- '<div class="status-steps-panel">'
- f'<div class="status-panel-title">'
- f'{render_client_i18n_text(i18n, title_key, locale)}'
- f'</div>'
- f'<div class="status-steps-list">{"".join(step_items)}</div>'
- f'<div class="status-latest">'
- f'{latest_status if not status_lines else html_lib.escape(latest_status)}'
- f'</div>'
- "</div>"
- )
-
-
-RESOURCE_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'resources')
-
-
-def load_resource_text(resource_name):
- """读取 mineru/resources 下的文本资源,集中管理 Gradio 静态片段。"""
- resource_path = os.path.join(RESOURCE_DIR, resource_name)
- with open(resource_path, mode='r', encoding='utf-8') as resource_file:
- return resource_file.read()
-
-
-APP_CSS = load_resource_text('gradio_app.css')
-APP_JS = load_resource_text('gradio_app.js')
-
-# Gradio 6 的 js 参数在部分托管环境里只注入函数文本,使用 head 包装确保页面加载后主动执行。
-APP_HEAD = f"""
-<script>
-(() => {{
- const installMineruAdvancedPopover = {APP_JS};
- if (document.readyState === "loading") {{
- document.addEventListener("DOMContentLoaded", installMineruAdvancedPopover, {{ once: true }});
- }} else {{
- installMineruAdvancedPopover();
- }}
-}})();
-</script>
-"""
-
-
-@dataclass
-class StatusPanelState:
- lines: list[str] = field(default_factory=list)
- processing_index: int | None = None
- processing_started_at: float | None = None
- last_processing_elapsed_seconds: float | None = None
- queue_index: int | None = None
- queue_started_at: float | None = None
- queue_base_message: str | None = None
-
- def append(self, message: str) -> bool:
- if not message:
- return False
-
- if self.is_queue_message(message):
- self.finalize_processing()
- return self.update_queue(message)
-
- if message == STATUS_PROCESSING_ON_SERVER:
- self.finalize_queue()
- return self.start_processing()
-
- self.finalize_processing()
- self.finalize_queue()
- if message == STATUS_COMPLETED:
- message = format_completed_status(self.last_processing_elapsed_seconds)
- if not self.lines or self.lines[-1] != message:
- self.lines.append(message)
- return True
- return False
-
- def start_processing(self) -> bool:
- if self.processing_started_at is not None:
- return self.tick_processing()
-
- self.processing_started_at = time.monotonic()
- self.last_processing_elapsed_seconds = 0.0
- self.processing_index = len(self.lines)
- self.lines.append(format_processing_status(0.0))
- return True
-
- def tick_processing(self) -> bool:
- if self.processing_started_at is None or self.processing_index is None:
- return False
-
- elapsed_seconds = max(0.0, time.monotonic() - self.processing_started_at)
- self.last_processing_elapsed_seconds = elapsed_seconds
- updated = format_processing_status(elapsed_seconds)
- if self.lines[self.processing_index] != updated:
- self.lines[self.processing_index] = updated
- return True
- return False
-
- def finalize_processing(self) -> bool:
- if self.processing_started_at is None or self.processing_index is None:
- return False
-
- self.tick_processing()
- self.processing_started_at = None
- self.processing_index = None
- return True
-
- def update_queue(self, message: str) -> bool:
- if (
- self.queue_index is None
- or self.queue_started_at is None
- or self.queue_base_message is None
- ):
- self.queue_started_at = time.monotonic()
- self.queue_index = len(self.lines)
- self.queue_base_message = message
- self.lines.append(format_queue_status(message, 0.0))
- return True
-
- self.queue_base_message = message
- updated = format_queue_status(
- message,
- max(0.0, time.monotonic() - self.queue_started_at),
- )
- if self.lines[self.queue_index] != updated:
- self.lines[self.queue_index] = updated
- return True
- return False
-
- def tick_queue(self) -> bool:
- if (
- self.queue_index is None
- or self.queue_started_at is None
- or self.queue_base_message is None
- ):
- return False
-
- updated = format_queue_status(
- self.queue_base_message,
- max(0.0, time.monotonic() - self.queue_started_at),
- )
- if self.lines[self.queue_index] != updated:
- self.lines[self.queue_index] = updated
- return True
- return False
-
- def finalize_queue(self) -> bool:
- if (
- self.queue_index is None
- or self.queue_started_at is None
- or self.queue_base_message is None
- ):
- return False
-
- self.tick_queue()
- self.queue_index = None
- self.queue_started_at = None
- self.queue_base_message = None
- return True
-
- def tick(self) -> bool:
- if self.is_processing:
- return self.tick_processing()
- if self.is_queueing:
- return self.tick_queue()
- return False
-
- @property
- def is_processing(self) -> bool:
- return self.processing_started_at is not None
-
- @property
- def is_queueing(self) -> bool:
- return self.queue_started_at is not None
-
- @property
- def animation_interval_seconds(self) -> float | None:
- if self.is_processing:
- return STATUS_TIMER_INTERVAL_SECONDS
- if self.is_queueing:
- return STATUS_QUEUE_ANIMATION_INTERVAL_SECONDS
- return None
-
- @staticmethod
- def is_queue_message(message: str) -> bool:
- return (
- message.startswith(STATUS_QUEUED_LOCALLY_PREFIX)
- or message.startswith(STATUS_QUEUED_ON_SERVER)
- )
-
- def render(self) -> str:
- return "\n".join(self.lines)
-
-
-def format_failed_status(error: Exception | str) -> str:
- return f"Failed: {error}"
-
-
-def format_processing_status(elapsed_seconds: float) -> str:
- return f"{STATUS_PROCESSING_ON_SERVER} ({elapsed_seconds:.1f}s)"
-
-
-def format_completed_status(elapsed_seconds: float | None) -> str:
- """生成完成状态文案,保留服务端解析阶段最终耗时。"""
- if elapsed_seconds is None:
- return STATUS_COMPLETED
- return f"{STATUS_COMPLETED} ({elapsed_seconds:.1f}s)"
-
-
-def format_queue_status(base_message: str, elapsed_seconds: float) -> str:
- dots = "." * (
- (int(max(0.0, elapsed_seconds)) % STATUS_QUEUE_ANIMATION_MAX_DOTS) + 1
- )
- return f"{base_message}{dots}"
-
-
-def format_concurrency_wait_message(snapshot: GradioConcurrencyWaitSnapshot) -> str:
- return f"{STATUS_QUEUED_LOCALLY_PREFIX} {snapshot.ahead} request(s) ahead"
-
-
-def format_remote_status_message(
- status_snapshot: _api_client.TaskStatusSnapshot | str,
-) -> str:
- if isinstance(status_snapshot, _api_client.TaskStatusSnapshot):
- status = status_snapshot.status
- queued_ahead = status_snapshot.queued_ahead
- else:
- status = status_snapshot
- queued_ahead = None
-
- if status == "pending":
- if queued_ahead is not None:
- return f"{STATUS_QUEUED_ON_SERVER}: {queued_ahead} request(s) ahead"
- return STATUS_QUEUED_ON_SERVER
- if status == "processing":
- return STATUS_PROCESSING_ON_SERVER
- if status == "completed":
- return STATUS_COMPLETED
- if status == "failed":
- return format_failed_status("server task failed")
- return f"Task status: {status}"
-
-
-def compress_directory_to_zip(directory_path, output_zip_path):
- """压缩指定目录到一个 ZIP 文件。
-
- :param directory_path: 要压缩的目录路径
- :param output_zip_path: 输出的 ZIP 文件路径
- """
- try:
- with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
-
- # 遍历目录中的所有文件和子目录
- for root, dirs, files in os.walk(directory_path):
- for file in files:
- # 构建完整的文件路径
- file_path = os.path.join(root, file)
- # 计算相对路径
- arcname = os.path.relpath(file_path, directory_path)
- # 添加文件到 ZIP 文件
- zipf.write(file_path, arcname)
- return 0
- except Exception as e:
- logger.exception(e)
- return -1
-
-
-GRADIO_PREVIEW_IMAGE_SUFFIXES = {
- ".jpg",
- ".jpeg",
- ".png",
- ".gif",
- ".webp",
- ".svg",
-}
-GRADIO_PREVIEW_EXTERNAL_SRC_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:")
-
-
-def _resolve_gradio_preview_image_path(src, image_dir_path):
- """将 Markdown/HTML 中的图片路径解析成 Gradio 文件路由需要的本地完整路径。"""
- image_src = str(src).strip()
- if not image_src:
- return None
- if Path(image_src).suffix.lower() not in GRADIO_PREVIEW_IMAGE_SUFFIXES:
- return None
-
- resolved_path = (Path(image_dir_path) / image_src).resolve(strict=False)
- if not resolved_path.is_file():
- logger.warning(f"Skip missing Gradio preview image: {resolved_path}")
- return None
- return str(resolved_path)
-
-
-def replace_image_with_gradio_file_urls(markdown_text, image_dir_path):
- """将 Gradio 预览中的本地图片路径改写为 HTTP 文件链接,不修改导出的 Markdown 文件。"""
- if not isinstance(markdown_text, str) or not image_dir_path:
- return markdown_text
-
- def _path_to_public_url(image_src):
- image_path = _resolve_gradio_preview_image_path(image_src, image_dir_path)
- if not image_path:
- return None
- return f"/gradio_api/file={quote(image_path, safe='/:')}"
-
- # 匹配 Markdown 正文图片 ![alt](path),只替换可安全访问的本地图片路径。
- def replace_md(match):
- alt_text = match.group("alt")
- image_src = match.group("src")
- public_url = _path_to_public_url(image_src)
- if public_url:
- return f"![{alt_text}]({public_url})"
- return match.group(0)
-
- result = re.sub(
- r"!\[(?P<alt>[^\]]*)\]\((?P<src>[^)]+)\)",
- replace_md,
- markdown_text,
- )
-
- # 匹配 HTML 表格内的 <img src="path">,跳过 data/http/blob 等已有可访问地址。
- def replace_html_src(match):
- prefix = match.group("prefix")
- quote_char = match.group("quote")
- image_src = match.group("src")
- public_url = _path_to_public_url(image_src)
- if public_url:
- return f"{prefix}{quote_char}{public_url}{quote_char}"
- return match.group(0)
-
- result = re.sub(
- r"(?P<prefix><img\b[^>]*?\bsrc\s*=\s*)(?P<quote>[\"'])(?P<src>[^\"']+)(?P=quote)",
- replace_html_src,
- result,
- flags=re.IGNORECASE,
- )
-
- return result
-
-
-def read_gradio_content_list_json(local_md_dir, file_name):
- """读取本次 Gradio 解析目录中的 legacy content_list JSON,失败时返回空字符串。"""
- content_list_path = Path(local_md_dir) / f"{file_name}_content_list.json"
- if not content_list_path.is_file():
- logger.warning(
- f"Content list JSON not found for Gradio preview: {content_list_path}"
- )
- return ""
- try:
- return content_list_path.read_text(encoding="utf-8")
- except Exception as exc:
- logger.warning(
- f"Failed to read Gradio content list JSON: {content_list_path}, error={exc}"
- )
- return ""
-
-
-def _middle_json_backend_for_gradio(parse_result: ParseResult, backend: str) -> str:
- """推断 Gradio 落盘 middle_json 的 backend 标识,优先使用解析结果自身标记。"""
- for page in parse_result.pages:
- if page._backend:
- return page._backend
- return "hybrid" if str(backend).startswith("hybrid") else backend
-
-
-def _write_v1_gradio_images(parse_result: ParseResult, local_image_dir: Path) -> None:
- """将 v1 API 返回的图片 sidecar 写入 Gradio legacy images 目录。"""
- writer = FileBasedDataWriter(str(local_image_dir))
- for image_path, image_bytes in parse_result.images().items():
- writer.write(validate_image_sidecar_path(image_path), image_bytes)
-
-
-def _build_v1_gradio_origin_file_bytes(source_path: Path, page_range: str) -> bytes:
- """按 v1 解析范围生成 Gradio 本地 origin 文件;图片会先转成 PDF 供预览使用。"""
- file_suffix = source_path.suffix.lower().lstrip(".")
- source_bytes = read_fn(source_path, file_suffix)
- if file_suffix != "pdf" or not page_range.strip():
- return source_bytes
-
- try:
- with PDFDocument(source_bytes) as pdf_doc:
- page_count = pdf_doc.page_count
- page_indices = parse_page_range(page_range, page_count)
- if not page_indices:
- logger.warning(f"Gradio origin PDF page_range selects no pages: {page_range}")
- return source_bytes
- if page_indices == list(range(page_count)):
- return source_bytes
-
- rewrite_result = safe_rewrite_pdf_bytes_with_pdfium_result(
- source_bytes,
- page_indices=page_indices,
- )
- if rewrite_result.used_original:
- logger.warning(
- f"Gradio origin PDF rewrite fell back to original PDF for page_range: {page_range}"
- )
- return rewrite_result.pdf_bytes or source_bytes
- except Exception as exc:
- logger.warning(
- f"Failed to build Gradio page-ranged origin PDF for {source_path}: {exc}; using original PDF."
- )
- return source_bytes
-
-
-def _generate_v1_gradio_layout_preview(
- *,
- file_name: str,
- local_md_dir: Path,
- backend: str,
-) -> None:
- """为 v1 Gradio 本地 PDF origin 生成 layout 预览;图片 origin 已提前转换为 PDF。"""
- origin_pdf_path = local_md_dir / f"{file_name}_origin.pdf"
- if not origin_pdf_path.exists():
- return
-
- result = run_visualization_job(
- VisualizationJob(
- document_stem=file_name,
- backend=backend,
- parse_method="auto",
- parse_dir=local_md_dir,
- )
- )
- if result.status != VISUALIZATION_FINISHED:
- logger.warning(f"Skipping Gradio layout preview for {file_name}: {result.message}")
-
-
-def persist_v1_gradio_result(
- *,
- parse_result: ParseResult,
- file_path: str,
- extract_root: Path,
- archive_zip_path: Path,
- backend: str,
- effort: str,
- page_range: str,
-) -> GradioV1PersistedOutput:
- """把 v1 ParseResult 保存成旧 Gradio UI 预览、JSON 面板和 ZIP 下载所需文件。"""
- source_path = Path(file_path)
- file_name = normalize_task_stem(source_path.stem)
- file_suffix = source_path.suffix.lower().lstrip(".")
- local_md_dir = extract_root / file_name
- local_image_dir = local_md_dir / "images"
- local_md_dir.mkdir(parents=True, exist_ok=True)
- local_image_dir.mkdir(parents=True, exist_ok=True)
-
- image_dir = local_image_dir.name
- render_pages = parse_result.export_pages()
- _write_v1_gradio_images(parse_result, local_image_dir)
-
- (local_md_dir / f"{file_name}.md").write_text(
- render_markdown(render_pages, image_dir),
- encoding="utf-8",
- )
- (local_md_dir / f"{file_name}_content_list.json").write_text(
- json.dumps(render_content_list(render_pages, image_dir), ensure_ascii=False, indent=4),
- encoding="utf-8",
- )
- (local_md_dir / f"{file_name}_structured_content.json").write_text(
- json.dumps(render_structured_content(render_pages, image_dir), ensure_ascii=False, indent=4),
- encoding="utf-8",
- )
-
- middle_json = parse_result.to_dict()
- middle_json["_backend"] = _middle_json_backend_for_gradio(parse_result, backend)
- middle_json["_version_name"] = __version__
- (local_md_dir / f"{file_name}_middle.json").write_text(
- json.dumps(middle_json, ensure_ascii=False, indent=4),
- encoding="utf-8",
- )
-
- model_output = getattr(parse_result, "_model_output", None)
- if model_output is not None:
- (local_md_dir / f"{file_name}_model_output.json").write_text(
- json.dumps(model_output, ensure_ascii=False, indent=4),
- encoding="utf-8",
- )
-
- origin_suffix = file_suffix if file_suffix in office_suffixes else "pdf"
- origin_bytes = _build_v1_gradio_origin_file_bytes(source_path, page_range)
- (local_md_dir / f"{file_name}_origin.{origin_suffix}").write_bytes(origin_bytes)
-
- _generate_v1_gradio_layout_preview(
- file_name=file_name,
- local_md_dir=local_md_dir,
- backend=backend,
- )
-
- zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
- if zip_archive_success == 0:
- logger.info("Compression successful")
- else:
- logger.error("Compression failed")
-
- preview_pdf_path = None if file_suffix in office_suffixes else resolve_preview_pdf_path(str(local_md_dir), file_name)
- return GradioV1PersistedOutput(
- file_name=file_name,
- local_md_dir=local_md_dir,
- archive_zip_path=archive_zip_path,
- preview_pdf_path=Path(preview_pdf_path).resolve() if preview_pdf_path else None,
- )
-
-
-def _escape_latex_html_chars_for_gradio(content):
- """转义公式内部会被 Gradio HTML 解析链路误判的尖括号,保留 LaTeX 对齐用 &。"""
- return content.replace("<", "&lt;").replace(">", "&gt;")
-
-
-def escape_latex_blocks_for_gradio_preview(markdown_text, latex_delimiters):
- """根据当前 LaTeX 分隔符,仅转义公式内容,避免影响公式外 Markdown/HTML。"""
- if not markdown_text or not latex_delimiters:
- return markdown_text
-
- delimiter_pairs = []
- for delimiter in latex_delimiters:
- left = delimiter.get("left")
- right = delimiter.get("right")
- if left and right:
- delimiter_pairs.append((left, right))
- delimiter_pairs.sort(key=lambda pair: len(pair[0]), reverse=True)
- if not delimiter_pairs:
- return markdown_text
-
- result = []
- position = 0
- text_length = len(markdown_text)
- while position < text_length:
- matched_pair = None
- for left, right in delimiter_pairs:
- if markdown_text.startswith(left, position):
- matched_pair = (left, right)
- break
-
- if matched_pair is None:
- result.append(markdown_text[position])
- position += 1
- continue
-
- left, right = matched_pair
- content_start = position + len(left)
- content_end = markdown_text.find(right, content_start)
- if content_end == -1:
- # 未闭合的分隔符保持原样,并继续扫描后续可能闭合的公式块。
- result.append(markdown_text[position])
- position += 1
- continue
-
- result.append(left)
- result.append(
- _escape_latex_html_chars_for_gradio(markdown_text[content_start:content_end])
- )
- result.append(right)
- position = content_end + len(right)
-
- return "".join(result)
-
-
-def prepare_markdown_for_gradio_preview(markdown_text, latex_delimiters):
- """准备传给 gr.Markdown 的预览文本;原始 Markdown 文件内容不在这里改写。"""
- if not isinstance(markdown_text, str):
- return markdown_text
- return escape_latex_blocks_for_gradio_preview(markdown_text, latex_delimiters)
-
-
-def create_gradio_run_paths(file_path, output_root="./output"):
- """生成 Gradio 单次任务目录,统一返回绝对路径以便文件预览组件访问。"""
- run_id = f"{time.strftime('%y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}_{safe_stem(Path(file_path).stem)}"
- output_root_path = Path(output_root).expanduser().resolve()
- run_root = output_root_path / "gradio" / run_id
- extract_root = run_root / "result"
- archive_zip_path = run_root / f"{safe_stem(Path(file_path).stem)}.zip"
- return run_root, extract_root, archive_zip_path
-
-
-def build_gradio_allowed_paths(output_root="./output"):
- """生成 Gradio 可公开访问目录,确保预览 HTTP 图片链接能被 /gradio_api/file= 读取。"""
- allowed_paths = []
- for item in os.environ.get("GRADIO_ALLOWED_PATHS", "").split(","):
- item = item.strip()
- if item:
- allowed_paths.append(item)
-
- output_path = str(Path(output_root).resolve())
- if output_path not in allowed_paths:
- allowed_paths.append(output_path)
- return allowed_paths
-
-
-def resolve_gradio_max_concurrent_requests(api_url, server_health):
- if api_url is None:
- return server_health.max_concurrent_requests
-
- return _api_client.resolve_effective_max_concurrent_requests(
- local_max=_api_client.read_max_concurrent_requests(
- default=_api_client.DEFAULT_MAX_CONCURRENT_REQUESTS
- ),
- server_max=server_health.max_concurrent_requests,
- )
-
-
-async def _run_to_markdown_job(
- file_path,
- end_pages=10,
- tier=DEFAULT_GRADIO_TIER,
- api_url=None,
- status_callback: Callable[[str], None] | None = None,
-):
- if file_path is None:
- return "", "", "", None, None
-
- def emit_status(message: str) -> None:
- if status_callback is not None:
- status_callback(message)
-
- file_path = str(file_path)
- file_suffix = Path(file_path).suffix.lower().lstrip('.')
- runtime = resolve_gradio_runtime_options(tier)
- backend = runtime.backend
- effort = runtime.effort
- page_range = build_v1_gradio_page_range(end_pages)
- run_root, extract_root, archive_zip_path = create_gradio_run_paths(file_path)
- run_root.mkdir(parents=True, exist_ok=True)
-
- async with httpx.AsyncClient(
- timeout=_api_client.build_http_timeout(),
- follow_redirects=True,
- ) as http_client:
- emit_status(STATUS_PREPARING_REQUEST)
- emit_status(STATUS_CHECKING_SERVER)
- server_health = await resolve_v1_server_health(http_client, api_url)
- effective_max_concurrent_requests = resolve_gradio_max_concurrent_requests(
- api_url=api_url,
- server_health=server_health,
- )
- async with _gradio_request_concurrency_limiter.acquire(
- effective_max_concurrent_requests,
- on_wait=lambda snapshot: emit_status(
- format_concurrency_wait_message(snapshot)
- ),
- ):
- emit_status(STATUS_SUBMITTING_TASK)
- parser = MinerUApiParser(
- api_url=server_health.base_url,
- tier=runtime.tier,
- include_images=True,
- include_model_output=True,
- )
- parse_result = await parser.parse_async(
- file_path,
- page_range=page_range,
- )
- emit_status(STATUS_DOWNLOADING_RESULT)
- emit_status(STATUS_PROCESSING_OUTPUT)
- persisted_output = await asyncio.to_thread(
- persist_v1_gradio_result,
- parse_result=parse_result,
- file_path=file_path,
- extract_root=extract_root,
- archive_zip_path=archive_zip_path,
- backend=backend,
- effort=effort,
- page_range=page_range,
- )
-
- file_name = persisted_output.file_name
- local_md_dir = persisted_output.local_md_dir
- preview_pdf_path = persisted_output.preview_pdf_path
-
- md_path = local_md_dir / f"{file_name}.md"
- txt_content = md_path.read_text(encoding="utf-8")
- md_content = replace_image_with_gradio_file_urls(txt_content, local_md_dir)
- content_list_json = read_gradio_content_list_json(local_md_dir, file_name)
-
- if file_suffix in office_suffixes:
- preview_pdf_path = None
-
- emit_status(STATUS_COMPLETED)
- return md_content, txt_content, content_list_json, str(archive_zip_path), str(preview_pdf_path) if preview_pdf_path else None
-
-
-async def stream_to_markdown(
- file_path,
- end_pages=10,
- tier=DEFAULT_GRADIO_TIER,
- api_url=None,
-):
- status_state = StatusPanelState()
- job_task: asyncio.Task | None = None
- queue_get_task: asyncio.Task | None = None
- timer_task: asyncio.Task | None = None
- yield status_state.render(), None, "", "", "", gr.skip()
-
- if file_path is None:
- return
-
- status_queue: asyncio.Queue[str] = asyncio.Queue()
- loop = asyncio.get_running_loop()
-
- def enqueue_status(message: str) -> None:
- loop.call_soon_threadsafe(status_queue.put_nowait, message)
-
- try:
- job_task = asyncio.create_task(
- _run_to_markdown_job(
- file_path=file_path,
- end_pages=end_pages,
- tier=tier,
- api_url=api_url,
- status_callback=enqueue_status,
- )
- )
-
- while True:
- if job_task.done() and status_queue.empty():
- status_state.finalize_processing()
- status_state.finalize_queue()
- break
-
- queue_get_task = asyncio.create_task(status_queue.get())
- wait_tasks: set[asyncio.Task] = {job_task, queue_get_task}
- timer_task = None
- animation_interval = status_state.animation_interval_seconds
- if animation_interval is not None:
- timer_task = asyncio.create_task(
- asyncio.sleep(animation_interval)
- )
- wait_tasks.add(timer_task)
-
- done, pending = await asyncio.wait(
- wait_tasks,
- return_when=asyncio.FIRST_COMPLETED,
- )
-
- if queue_get_task in done:
- message = queue_get_task.result()
- if status_state.append(message):
- yield status_state.render(), None, "", "", "", gr.skip()
- elif timer_task is not None and timer_task in done:
- if status_state.tick():
- yield status_state.render(), None, "", "", "", gr.skip()
- else:
- queue_get_task.cancel()
- await asyncio.gather(queue_get_task, return_exceptions=True)
-
- for pending_task in pending:
- if pending_task is job_task:
- continue
- pending_task.cancel()
- await asyncio.gather(pending_task, return_exceptions=True)
- queue_get_task = None
- timer_task = None
-
- while not status_queue.empty():
- status_state.append(status_queue.get_nowait())
- except Exception as exc:
- status_state.append(format_failed_status(exc))
- yield status_state.render(), None, "", "", "", gr.skip()
- raise
- finally:
- for task in (queue_get_task, timer_task, job_task):
- if task is None or task.done():
- continue
- task.cancel()
- await asyncio.gather(task, return_exceptions=True)
-
- try:
- md_content, txt_content, content_list_json, archive_zip_path, preview_pdf_path = await job_task
- except Exception as exc:
- status_state.append(format_failed_status(exc))
- yield status_state.render(), None, "", "", "", gr.skip()
- raise
-
- status_state.append(STATUS_COMPLETED)
- yield (
- status_state.render(),
- archive_zip_path,
- md_content,
- txt_content,
- content_list_json,
- preview_pdf_path,
- )
-
-
-def resolve_preview_pdf_path(local_md_dir, file_name):
- layout_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')
- if os.path.exists(layout_pdf_path):
- return layout_pdf_path
-
- origin_pdf_path = os.path.join(local_md_dir, file_name + '_origin.pdf')
- if os.path.exists(origin_pdf_path):
- logger.warning(
- f"Layout preview PDF not found for {file_name}, "
- f"falling back to origin PDF: {origin_pdf_path}"
- )
- return origin_pdf_path
-
- logger.warning(f"No preview PDF found for {file_name} under {local_md_dir}")
- return None
-
-
-latex_delimiters_type_a = [
- {'left': '$$', 'right': '$$', 'display': True},
- {'left': '$', 'right': '$', 'display': False},
-]
-latex_delimiters_type_b = [
- {'left': '\\(', 'right': '\\)', 'display': False},
- {'left': '\\[', 'right': '\\]', 'display': True},
-]
-latex_delimiters_type_all = latex_delimiters_type_a + latex_delimiters_type_b
-
-header_template = load_resource_text('gradio_header.html')
-
-HEADER_I18N_PLACEHOLDERS = {
- "{{HEADER_TITLE}}": "header_title",
- "{{HEADER_SUBTITLE}}": "header_subtitle",
- "{{HEADER_SUPPORT_TEXT}}": "header_support_text",
- "{{HEADER_STARS_ALT}}": "header_stars_alt",
- "{{HEADER_CODE_LINK}}": "header_code_link",
- "{{HEADER_MODEL_LINK}}": "header_model_link",
- "{{HEADER_MODEL_HUGGINGFACE_LINK}}": "header_model_huggingface_link",
- "{{HEADER_MODEL_MODELSCOPE_LINK}}": "header_model_modelscope_link",
- "{{HEADER_PAPER_LINK}}": "header_paper_link",
- "{{HEADER_PAPER_MINERU_REPORT}}": "header_paper_mineru_report",
- "{{HEADER_PAPER_MINERU25_REPORT}}": "header_paper_mineru25_report",
- "{{HEADER_PAPER_MINERU25PRO_REPORT}}": "header_paper_mineru25pro_report",
- "{{HEADER_HOMEPAGE_LINK}}": "header_homepage_link",
- "{{HEADER_DOWNLOAD_LINK}}": "header_download_link",
-}
-HEADER_GRADIO_VERSION_CLASS_PLACEHOLDER = "{{HEADER_GRADIO_VERSION_CLASS}}"
-
-
-def render_header_html(i18n):
- """渲染支持 i18n 的顶部 Header,保留静态模板中的样式和链接。"""
- rendered_header = header_template
- for placeholder, translation_key in HEADER_I18N_PLACEHOLDERS.items():
- if translation_key == "header_stars_alt":
- replacement = html_lib.escape(translate_ui(i18n, translation_key), quote=True)
- else:
- replacement = render_client_i18n_text(i18n, translation_key)
- rendered_header = rendered_header.replace(
- placeholder,
- replacement,
- )
- rendered_header = rendered_header.replace(
- HEADER_GRADIO_VERSION_CLASS_PLACEHOLDER,
- " mineru-gradio6-header" if IS_GRADIO_6 else "",
- )
- return rendered_header
-
-def safe_stem(file_path):
- stem = Path(file_path).stem
- # 只保留字母、数字、下划线和点,其他字符替换为下划线
- return re.sub(r'[^\w.]', '_', stem)
-
-
-def to_pdf(file_path):
-
- if file_path is None:
- return None
-
- pdf_bytes = read_fn(file_path)
-
- # unique_filename = f'{uuid.uuid4()}.pdf'
- unique_filename = f'{safe_stem(file_path)}.pdf'
-
- # 构建完整的文件路径
- tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)
-
- # 将字节数据写入文件
- with open(tmp_file_path, 'wb') as tmp_pdf_file:
- tmp_pdf_file.write(pdf_bytes)
-
- return tmp_file_path
-
-
-def to_pdf_preview(file_path):
- """用于 PDF 预览的转换函数,office 文件不支持预览,返回 None。"""
- if file_path is None:
- return None
- file_suffix = Path(file_path).suffix.lower().lstrip('.')
- if file_suffix in office_suffixes:
- return None
- return to_pdf(file_path)
-
-
-def build_gradio_file_public_url(file_path, request: gr.Request):
- """根据当前 Gradio 请求构建上传文件的外部访问 URL,兼容本地和反代环境。"""
- headers = getattr(request, "headers", None) or {}
- host = (
- headers.get('x-forwarded-host')
- or headers.get('host', 'localhost:7860')
- )
- proto = headers.get('x-forwarded-proto', 'http')
- return f"{proto}://{host}/gradio_api/file={quote(str(file_path), safe='/:')}"
-
-
-def build_short_gradio_file_url(public_url, file_path):
- """生成页面展示用的短链接文本,保留站点前缀和文件名尾部以避免长路径撑破预览区。"""
- base_url = public_url.split("/gradio_api/file=", 1)[0]
- file_name = Path(file_path).name
- file_suffix = Path(file_name).suffix
- file_stem = Path(file_name).stem
- short_file_name = f"{file_stem[-12:]}{file_suffix}" if file_stem else file_name
- return f"{base_url}/....{short_file_name}"
-
-
-def build_office_preview_html(file_path, request: gr.Request, i18n=None):
- """生成 Office 在线预览 HTML,并提示该预览依赖外部 Microsoft 服务访问。"""
- public_url = build_gradio_file_public_url(file_path, request)
- short_public_url = build_short_gradio_file_url(public_url, file_path)
- viewer_url = (
- "https://view.officeapps.live.com/op/embed.aspx?src="
- f"{quote(public_url, safe='')}"
- )
- title = render_client_i18n_text(i18n, "office_preview_title")
- notice = render_client_i18n_text(i18n, "office_preview_notice")
- source_link = render_client_i18n_text(i18n, "office_preview_source_link")
- ignore_once = render_client_i18n_text(i18n, "office_preview_ignore_once")
- ignore_forever = render_client_i18n_text(i18n, "office_preview_ignore_forever")
- return (
- '<div class="office-preview-shell">'
- '<div class="office-preview-notice">'
- '<div class="office-preview-copy">'
- f"<strong>{title}</strong>"
- f"<span>{notice}</span>"
- '<div class="office-preview-source-link">'
- f"{source_link}: "
- f"{html_lib.escape(short_public_url)}"
- "</div>"
- "</div>"
- '<div class="office-preview-actions">'
- f'<button type="button" class="office-preview-ignore-once">{ignore_once}</button>'
- f'<button type="button" class="office-preview-ignore-forever">{ignore_forever}</button>'
- "</div>"
- "</div>"
- f'<iframe class="office-preview-frame" src="{html_lib.escape(viewer_url)}" '
- 'frameborder="0"></iframe>'
- "</div>"
- )
-
-
-def update_file_options_html(file_path, request: gr.Request, i18n=None):
- """处理文件上传第一阶段:根据文件类型更新 options_group 和 office_html。
- 将 doc_show(gradio_pdf.PDF)的更新拆分到独立的 .then() 事件中,
- 以规避 gradio_pdf 0.0.24 在 Gradio 6 中对 value=None 处理不当导致的
- 整个事件 processing 状态卡死的兼容性问题。
- """
- if file_path is None:
- return (
- gr.update(visible=True), # options_group - 恢复显示
- gr.update(value="", visible=False), # office_html - 隐藏
- )
-
- file_suffix = Path(file_path).suffix.lower().lstrip('.')
- is_office = file_suffix in office_suffixes
-
- if is_office:
- html_content = build_office_preview_html(file_path, request, i18n)
- return (
- gr.update(visible=False), # options_group - 隐藏
- gr.update(value=html_content, visible=True), # office_html - 显示
- )
- else:
- return (
- gr.update(visible=True), # options_group - 显示
- gr.update(value="", visible=False), # office_html - 隐藏
- )
-
-
-def update_doc_show(file_path):
- """处理文件上传第二阶段:单独更新 doc_show(gradio_pdf.PDF)组件。
- 对 office 文件仅改变 visible,避免传递 value=None 触发
- gradio_pdf 0.0.24 在 Gradio 6 中无法完成的加载周期。
- """
- if file_path is None:
- # 无文件时恢复显示并清空(clear 按钮路径)
- return gr.update(value=None, visible=True)
-
- file_suffix = Path(file_path).suffix.lower().lstrip('.')
- is_office = file_suffix in office_suffixes
-
- if is_office:
- # 仅隐藏,不改变 value,避免触发 gradio_pdf 加载周期导致事件 pending 卡死
- return gr.update(visible=False)
- else:
- pdf_path = to_pdf_preview(file_path)
- return gr.update(value=pdf_path, visible=True)
-
-
[email protected](context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
- '--enable-example',
- 'example_enable',
- type=bool,
- help="Enable example files for input."
- "The example files to be input need to be placed in the `examples` folder within the directory where the command is currently executed.",
- default=True,
-)
- '--enable-http-client',
- 'http_client_enable',
- type=bool,
- help="Deprecated no-op; use --api-url to bind Gradio to an external v1 API server.",
- default=False,
-)
- '--enable-api',
- 'api_enable',
- type=bool,
- help="Enable gradio API for serving the application.",
- default=True,
-)
- '--max-convert-pages',
- 'max_convert_pages',
- type=int,
- help="Set the maximum number of pages to convert from PDF to Markdown.",
- default=1000,
-)
- '--server-name',
- 'server_name',
- type=str,
- help="Set the server name for the Gradio app.",
- default=None,
-)
- '--server-port',
- 'server_port',
- type=int,
- help="Set the server port for the Gradio app.",
- default=None,
-)
- '--api-url',
- 'api_url',
- type=str,
- help="MinerU FastAPI base URL. If omitted, gradio starts a reusable local mineru-api service.",
- default=None,
-)
- '--enable-vlm-preload',
- 'enable_vlm_preload',
- type=bool,
- help="Deprecated no-op; Gradio v1 starts or connects to a parser API server.",
- default=False,
-)
- '--client-side-output-generation',
- 'client_side_output_generation',
- type=bool,
- help="Deprecated no-op; Gradio v1 persists outputs from ParseResult locally.",
- default=False,
-)
- '--latex-delimiters-type',
- 'latex_delimiters_type',
- type=click.Choice(['a', 'b', 'all']),
- help="Set the type of LaTeX delimiters to use in Markdown rendering:"
- "'a' for type '$', 'b' for type '()[]', 'all' for both types.",
- default='all',
-)
-def main(ctx,
- example_enable,
- http_client_enable,
- api_enable, max_convert_pages,
- server_name, server_port, api_url, enable_vlm_preload,
- client_side_output_generation, latex_delimiters_type, **kwargs
-):
-
- # 创建 i18n 实例,支持中英文
- i18n = gr.I18n(
- en={
- "upload_file": "Select or paste a file to upload\nPDF, image, DOCX, PPTX, or XLSX",
- "header_title": "MinerU 3: Document Extraction Demo",
- "header_subtitle": "Open-source document extraction for PDF, DOCX, PPTX, XLSX, and images to Markdown and JSON.",
- "header_support_text": "If you found our project helpful, please give us a ⭐️ to support us!",
- "header_stars_alt": "stars",
- "header_code_link": "Code",
- "header_model_link": "Model",
- "header_model_huggingface_link": "Hugging Face",
- "header_model_modelscope_link": "ModelScope",
- "header_paper_link": "Paper",
- "header_paper_mineru_report": "MinerU · arXiv: 2409.18839",
- "header_paper_mineru25_report": "MinerU 2.5 · arXiv: 2509.22186",
- "header_paper_mineru25pro_report": "MinerU 2.5 Pro · arXiv: 2604.04771",
- "header_homepage_link": "Homepage",
- "header_download_link": "Download",
- "max_pages": "Max convert pages",
- "tier": "Tier",
- "tier_info_default": "Select the parsing tier.",
- "tier_info_flash": "Flash tier uses fast local text extraction.",
- "tier_info_basic": "Basic tier uses local Hybrid parsing on CPU-capable systems.",
- "tier_info_standard": "Standard tier provides high-quality Hybrid parsing.",
- "tier_info_advanced": "Advanced tier spends more compute on difficult documents.",
- "convert": "Convert",
- "clear": "Clear",
- "doc_preview": "Document preview",
- "examples": "Examples:",
- "convert_status": "Conversion Status",
- "convert_result": "Convert result",
- "result_file": "Result file",
- "md_rendering": "Markdown rendering",
- "md_text": "Markdown text",
- "content_list_json": "JSON Content List",
- "status_idle_title": "Waiting",
- "status_idle_hint": "Upload a file and start conversion.",
- "status_latest": "Latest status",
- "status_step_prepare": "Prepare",
- "status_step_check": "Check service",
- "status_step_submit": "Submit",
- "status_step_queue": "Queue",
- "status_step_process": "Parse",
- "status_step_download": "Download",
- "status_step_outputs": "Build outputs",
- "status_step_done": "Done",
- "status_step_failed": "Failed",
- "office_preview_title": "Office online preview",
- "office_preview_notice": "This preview requires the current file to be reachable by Microsoft Office Online. Conversion does not depend on this preview.",
- "office_preview_source_link": "File url",
- "office_preview_ignore_once": "Dismiss",
- "office_preview_ignore_forever": "Always dismiss",
- },
- zh={
- "upload_file": "请选择或粘贴要上传的文件\nPDF、图片、DOCX、PPTX 或 XLSX",
- "header_title": "MinerU 3:文档提取演示",
- "header_subtitle": "开源文档提取工具,支持将 PDF、DOCX、PPTX、XLSX 和图片转换为 Markdown 与 JSON。",
- "header_support_text": "如果我们的项目对你有帮助,请点亮 ⭐️ 支持我们!",
- "header_stars_alt": "GitHub 星标",
- "header_code_link": "代码",
- "header_model_link": "模型",
- "header_model_huggingface_link": "Hugging Face",
- "header_model_modelscope_link": "ModelScope",
- "header_paper_link": "论文",
- "header_paper_mineru_report": "MinerU · arXiv: 2409.18839",
- "header_paper_mineru25_report": "MinerU 2.5 · arXiv: 2509.22186",
- "header_paper_mineru25pro_report": "MinerU 2.5 Pro · arXiv: 2604.04771",
- "header_homepage_link": "主页",
- "header_download_link": "下载",
- "max_pages": "最大转换页数",
- "tier": "解析 tier",
- "tier_info_default": "选择文档解析 tier。",
- "tier_info_flash": "flash 使用快速本地文本提取。",
- "tier_info_basic": "基础解析使用可在 CPU 环境运行的本地 Hybrid 解析。",
- "tier_info_standard": "标准解析提供高质量 Hybrid 解析。",
- "tier_info_advanced": "高级解析为困难文档投入更多推理算力。",
- "convert": "转换",
- "clear": "清除",
- "doc_preview": "文档预览",
- "examples": "示例:",
- "convert_status": "转换状态",
- "convert_result": "转换结果",
- "result_file": "结果文件",
- "md_rendering": "Markdown 渲染",
- "md_text": "Markdown 文本",
- "content_list_json": "JSON 内容列表",
- "status_idle_title": "等待任务",
- "status_idle_hint": "上传文件后开始转换。",
- "status_latest": "最新状态",
- "status_step_prepare": "准备请求",
- "status_step_check": "检查服务",
- "status_step_submit": "提交任务",
- "status_step_queue": "排队",
- "status_step_process": "解析中",
- "status_step_download": "下载结果",
- "status_step_outputs": "整理输出",
- "status_step_done": "完成",
- "status_step_failed": "失败",
- "office_preview_title": "Office 在线预览",
- "office_preview_notice": "该预览需要当前文件可被 Microsoft 在线预览服务访问,转换不依赖该预览。",
- "office_preview_source_link": "文件链接",
- "office_preview_ignore_once": "忽略",
- "office_preview_ignore_forever": "不再提示",
- },
- )
-
- def get_tier_info(tier_choice):
- return i18n(select_tier_info_key(tier_choice))
-
- del kwargs
- if http_client_enable:
- logger.warning(
- "Ignoring --enable-http-client because Gradio v1 selects external parser services with --api-url."
- )
- if enable_vlm_preload:
- logger.warning(
- "Ignoring --enable-vlm-preload because Gradio now launches the v1 parser API server."
- )
- if client_side_output_generation:
- logger.warning(
- "Ignoring --client-side-output-generation because Gradio v1 persists outputs from ParseResult locally."
- )
- _gradio_local_api_server.configure(ctx.args)
- startup_health = resolve_gradio_v1_startup_health(api_url=api_url)
- tier_choices = startup_health.tier_choices
-
- if latex_delimiters_type == 'a':
- latex_delimiters = latex_delimiters_type_a
- elif latex_delimiters_type == 'b':
- latex_delimiters = latex_delimiters_type_b
- elif latex_delimiters_type == 'all':
- latex_delimiters = latex_delimiters_type_all
- else:
- raise ValueError(f"Invalid latex delimiters type: {latex_delimiters_type}.")
-
-
- async def convert_to_markdown_stream(
- file_path,
- end_pages=10,
- tier=DEFAULT_GRADIO_TIER,
- request: gr.Request = None,
- ):
- request_locale = resolve_request_locale(request)
- async for update in stream_to_markdown(
- file_path=file_path,
- end_pages=end_pages,
- tier=tier,
- api_url=api_url,
- ):
- update = (
- render_status_steps_html(update[0], i18n, locale=request_locale),
- update[1],
- prepare_markdown_for_gradio_preview(update[2], latex_delimiters),
- *update[3:],
- )
- yield update
-
- suffixes = [f".{suffix}" for suffix in pdf_suffixes + image_suffixes + office_suffixes]
- _blocks_kwargs = {} if IS_GRADIO_6 else {"css": APP_CSS, "js": APP_JS}
- with gr.Blocks(**_blocks_kwargs) as demo:
- gr.HTML(render_header_html(i18n), elem_classes=["mineru-header-html"])
- with gr.Row(elem_classes=["mineru-workspace-row"]):
- with gr.Column(variant='panel', scale=2, min_width=280, elem_classes=["mineru-control-column"]):
- input_file = gr.File(
- label=i18n("upload_file"),
- file_types=suffixes,
- elem_classes=["mineru-upload-file"],
- )
- preferred_tier = default_v1_gradio_tier(tier_choices)
- with gr.Group(elem_classes=["mineru-backend-options-block"]):
- tier = gr.Dropdown(
- list(tier_choices),
- label=i18n("tier"),
- value=preferred_tier,
- info=get_tier_info(preferred_tier),
- elem_classes=["mineru-tier-select"],
- )
- # 页数控件在上传 Office 文件时会被自动隐藏。
- with gr.Group() as options_group:
- max_pages = gr.Slider(1, max_convert_pages, max_convert_pages, step=1, label=i18n("max_pages"))
- with gr.Row(elem_classes=["mineru-actions"]):
- change_bu = gr.Button(i18n("convert"), variant="primary", scale=1, min_width=0)
- clear_bu = gr.ClearButton(value=i18n("clear"), scale=1, min_width=0)
- output_file = gr.File(
- label=i18n("convert_result"),
- interactive=False,
- elem_classes=["mineru-result-file"],
- )
- status_panel = gr.HTML(
- value=render_status_steps_html("", i18n),
- label=i18n("convert_status"),
- elem_classes=["mineru-status-panel"],
- )
-
- _doc_preview_label = "doc preview" if IS_GRADIO_6 else i18n("doc_preview")
- # preview_content_height 约束文档预览/Markdown 的内容区;gradio_pdf 的 height
- # 实际是单页 canvas 高度,需要单独扣除 label 和分页器占用,避免上传 PDF 后撑高预览块。
- preview_content_height = 775
- pdf_preview_page_height = 720
- with gr.Column(variant='panel', scale=4, min_width=340, elem_classes=["mineru-preview-pane"]):
- doc_show = PDF(
- label=_doc_preview_label,
- interactive=False,
- visible=True,
- height=pdf_preview_page_height,
- )
- office_html = gr.HTML(
- value="",
- visible=False,
- min_height=preview_content_height,
- elem_classes=["mineru-office-preview-html"],
- )
-
- with gr.Column(variant='panel', scale=4, min_width=340, elem_classes=["mineru-markdown-pane"]):
- _md_copy_kwargs = {"buttons": ["copy"]} if IS_GRADIO_6 else {"show_copy_button": True}
- _textarea_copy_kwargs = {"buttons": ["copy"]} if IS_GRADIO_6 else {"show_copy_button": True}
- with gr.Tabs(elem_classes=["mineru-markdown-tabs"]):
- with gr.Tab(i18n("md_rendering")):
- md = gr.Markdown(
- label=i18n("md_rendering"),
- height=preview_content_height,
- elem_classes=["mineru-markdown-output"],
- latex_delimiters=latex_delimiters,
- line_breaks=True,
- **_md_copy_kwargs
- )
- with gr.Tab(i18n("md_text")):
- md_text = gr.Code(
- lines=28,
- language="markdown",
- label=i18n("md_text"),
- interactive=False,
- wrap_lines=True,
- show_label=False,
- elem_classes=["mineru-markdown-text"],
- )
- with gr.Tab(i18n("content_list_json")):
- content_list_json = gr.Code(
- lines=28,
- language="json",
- label=i18n("content_list_json"),
- interactive=False,
- wrap_lines=True,
- show_label=False,
- elem_classes=["mineru-content-list-json"],
- )
-
- if example_enable:
- example_root = os.path.join(os.getcwd(), 'examples')
- if os.path.exists(example_root):
- example_files = [
- os.path.join(example_root, _) for _ in os.listdir(example_root)
- if _.endswith(tuple(suffixes))
- ]
- if example_files:
- with gr.Accordion(i18n("examples"), open=True, elem_classes=["mineru-examples-panel"]):
- gr.Examples(
- examples=example_files,
- inputs=input_file,
- elem_id="mineru-example-files",
- label=None,
- )
-
- # 添加事件处理
- _private_api_kwargs = (
- {"api_visibility": "private", "queue": False}
- if IS_GRADIO_6
- else {"api_name": False, "queue": False}
- )
- clear_bu.add([input_file, md, doc_show, md_text, content_list_json, output_file, office_html, status_panel])
-
- def reset_primary_ui():
- """清除主界面状态,并恢复文件预览与状态面板。"""
- return (
- gr.update(visible=True),
- gr.update(value=None, visible=True),
- gr.update(value="", visible=False),
- gr.update(value=render_status_steps_html("", i18n)),
- gr.update(value=""),
- )
-
- # 清除按钮额外重置 UI 可见性(ClearButton 不一定触发 input_file.change)
- clear_bu.click(
- fn=reset_primary_ui,
- inputs=[],
- outputs=[options_group, doc_show, office_html, status_panel, content_list_json],
- **_private_api_kwargs
- )
-
- def update_file_options_html_for_ui(file_path, request: gr.Request):
- """绑定当前 i18n 的文件上传 UI 更新函数,避免事件签名暴露额外参数。"""
- return update_file_options_html(file_path, request, i18n)
-
- # 第一阶段:快速更新 options_group 和 office_html,不涉及 gradio_pdf 组件
- # 第二阶段(.then):单独更新 doc_show,使 office_html 的 processing 遮罩
- # 在第一阶段完成后立即消失,规避 gradio_pdf 0.0.24 与 Gradio 6 的兼容性问题。
- input_file.change(
- fn=update_file_options_html_for_ui,
- inputs=input_file,
- outputs=[options_group, office_html],
- **_private_api_kwargs
- ).then(
- fn=update_doc_show,
- inputs=input_file,
- outputs=[doc_show],
- **_private_api_kwargs
- )
- _to_md_api_kwargs = (
- {
- "api_visibility": "public" if api_enable else "private",
- "queue": True,
- "show_progress": "hidden",
- }
- if IS_GRADIO_6
- else {
- "api_name": "to_markdown" if api_enable else False,
- "queue": True,
- "show_progress": "hidden",
- }
- )
- change_bu.click(
- fn=convert_to_markdown_stream,
- inputs=[input_file, max_pages, tier],
- outputs=[status_panel, output_file, md, md_text, content_list_json, doc_show],
- **_to_md_api_kwargs
- )
-
- demo.queue(default_concurrency_limit=None)
-
- if IS_GRADIO_6:
- footer_links = ["gradio", "settings"]
- if api_enable:
- footer_links.append("api")
- _launch_kwargs = {"footer_links": footer_links, "css": APP_CSS, "head": APP_HEAD}
- else:
- _launch_kwargs = {"show_api": api_enable}
- demo.launch(
- server_name=server_name,
- server_port=server_port,
- i18n=i18n,
- allowed_paths=build_gradio_allowed_paths(),
- **_launch_kwargs,
- )
-
-
-if __name__ == '__main__':
- main()
diff --git a/mineru/cli_old/output_paths.py b/mineru/cli_old/output_paths.py
deleted file mode 100644
index c73308ae..00000000
--- a/mineru/cli_old/output_paths.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from pathlib import Path
-
-from mineru.utils.backend_options import normalize_backend
-
-
-OFFICE_PARSE_DIR_NAME = "office"
-
-
-def build_parse_dir(
- output_dir: str | Path,
- pdf_name: str,
- backend: str,
- parse_method: str,
- *,
- is_office: bool = False,
-) -> Path:
- output_root = Path(output_dir)
- try:
- backend = normalize_backend(backend)
- except ValueError:
- pass
- if is_office:
- return output_root / pdf_name / OFFICE_PARSE_DIR_NAME
- if backend.startswith("hybrid"):
- return output_root / pdf_name / f"hybrid_{parse_method}"
- raise ValueError(f"Unknown backend type: {backend}")
-
-
-def resolve_parse_dir(
- output_dir: str | Path,
- pdf_name: str,
- backend: str,
- parse_method: str,
- *,
- is_office: bool = False,
- allow_office_fallback: bool = False,
-) -> Path:
- parse_dir = build_parse_dir(
- output_dir,
- pdf_name,
- backend,
- parse_method,
- is_office=is_office,
- )
- if is_office:
- return parse_dir
-
- if allow_office_fallback and not parse_dir.exists():
- office_dir = build_parse_dir(
- output_dir,
- pdf_name,
- backend,
- parse_method,
- is_office=True,
- )
- if office_dir.exists():
- return office_dir
- return parse_dir
diff --git a/mineru/cli_old/public_http_client_policy.py b/mineru/cli_old/public_http_client_policy.py
deleted file mode 100644
index e1442030..00000000
--- a/mineru/cli_old/public_http_client_policy.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from fastapi import FastAPI, HTTPException
-from loguru import logger
-
-
-PUBLIC_HTTP_CLIENT_DISABLED_DETAIL = (
- "Publicly exposed API disables *-http-client backends and server_url by "
- "default. Rebind to 127.0.0.1 or start with "
- "--allow-public-http-client if you understand the SSRF risk."
-)
-
-
-def is_public_bind_host(host: str) -> bool:
- return host in {"0.0.0.0", "::"}
-
-
-def configure_public_http_client_policy(
- app: FastAPI,
- *,
- public_bind_exposed: bool,
- allow_public_http_client: bool,
-) -> None:
- app.state.public_bind_exposed = public_bind_exposed
- app.state.allow_public_http_client = allow_public_http_client
-
-
-def validate_public_http_client_request(
- *,
- public_bind_exposed: bool,
- allow_public_http_client: bool,
- backend: str,
- server_url: str | None,
-) -> None:
- if not public_bind_exposed or allow_public_http_client:
- return
- if backend.endswith("-http-client") or bool(server_url and server_url.strip()):
- raise HTTPException(status_code=400, detail=PUBLIC_HTTP_CLIENT_DISABLED_DETAIL)
-
-
-def warn_if_public_http_client_policy(
- *,
- service_name: str,
- host: str,
- allow_public_http_client: bool,
-) -> None:
- if not is_public_bind_host(host):
- return
- if allow_public_http_client:
- logger.warning(
- "MinerU {} is listening on {} with --allow-public-http-client enabled. "
- "Requests may supply remote HTTP inference endpoints and turn the service "
- "into an externally driven outbound request primitive, creating SSRF and "
- "internal network probing risk.",
- service_name,
- host,
- )
- return
- logger.warning(
- "MinerU {} is listening on {}. Disabling *-http-client backends and "
- "server_url by default because these inputs let callers choose remote HTTP "
- "inference endpoints; when the API is publicly reachable, that creates SSRF "
- "and internal network probing risk.",
- service_name,
- host,
- )
diff --git a/mineru/cli_old/router.py b/mineru/cli_old/router.py
deleted file mode 100644
index b46ce365..00000000
--- a/mineru/cli_old/router.py
+++ /dev/null
@@ -1,1674 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import asyncio
-import json
-import os
-import random
-import shutil
-import socket
-import subprocess
-import sys
-import tempfile
-import uuid
-from contextlib import ExitStack, asynccontextmanager, suppress
-from dataclasses import dataclass, field
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Annotated, Any, Optional, Sequence
-
-import click
-import httpx
-import uvicorn
-from fastapi import Depends, FastAPI, HTTPException, Request
-from fastapi.middleware.gzip import GZipMiddleware
-from fastapi.responses import JSONResponse, Response, StreamingResponse
-from loguru import logger
-from starlette.background import BackgroundTask
-from starlette.datastructures import UploadFile as StarletteUploadFile
-
-from mineru.cli_old.api_client import (
- LOCAL_API_CLEANUP_RETRIES,
- LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS,
- LOCAL_API_STARTUP_TIMEOUT_SECONDS,
- TASK_RESULT_TIMEOUT_SECONDS,
- TASK_STATUS_POLL_INTERVAL_SECONDS,
- build_managed_process_popen_kwargs,
- build_http_timeout,
- build_result_download_timeout,
- find_free_port,
- normalize_base_url,
- stop_managed_process,
- strip_local_api_network_args,
- response_detail,
-)
-from mineru.cli_old.api_protocol import API_PROTOCOL_VERSION
-from mineru.cli_old.api_request import ParseRequestOptions, parse_request_form
-from mineru.cli_old.public_http_client_policy import (
- configure_public_http_client_policy,
- is_public_bind_host,
- validate_public_http_client_request,
- warn_if_public_http_client_policy as _warn_if_public_http_client_policy,
-)
-from mineru.cli_old.upload_utils import normalize_upload_filename
-from mineru.version import __version__
-
-TASK_PENDING = "pending"
-TASK_PROCESSING = "processing"
-TASK_COMPLETED = "completed"
-TASK_FAILED = "failed"
-TASK_TERMINAL_STATES = {TASK_COMPLETED, TASK_FAILED}
-DEFAULT_TASK_RETENTION_SECONDS = 24 * 60 * 60
-DEFAULT_TASK_CLEANUP_INTERVAL_SECONDS = 5 * 60
-FILE_PARSE_TASK_ID_HEADER = "X-MinerU-Task-Id"
-FILE_PARSE_TASK_STATUS_HEADER = "X-MinerU-Task-Status"
-FILE_PARSE_TASK_STATUS_URL_HEADER = "X-MinerU-Task-Status-Url"
-FILE_PARSE_TASK_RESULT_URL_HEADER = "X-MinerU-Task-Result-Url"
-HEALTH_ENDPOINT = "/health"
-TASKS_ENDPOINT = "/tasks"
-SOURCE_LOCAL = "local"
-SOURCE_REMOTE = "remote"
-LOCAL_GPU_AUTO = "auto"
-LOCAL_GPU_NONE = "none"
-HTTP_RETRYABLE_STATUS_CODES = {500, 502, 503, 504}
-UPSTREAM_FAILURE_THRESHOLD = 3
-WORKER_REFRESH_INTERVAL_SECONDS = 2.0
-WORKER_HEALTH_FAILURE_RESTART_THRESHOLD = 5
-MIN_HEALTHY_PROCESSING_WINDOW_SIZE = 1
-MINERU_ROUTER_PUBLIC_BIND_EXPOSED_ENV = "MINERU_ROUTER_PUBLIC_BIND_EXPOSED"
-MINERU_ROUTER_ALLOW_PUBLIC_HTTP_CLIENT_ENV = "MINERU_ROUTER_ALLOW_PUBLIC_HTTP_CLIENT"
-
-
-def utc_now_iso() -> str:
- return datetime.now(timezone.utc).isoformat()
-
-
-def env_flag_enabled(name: str, default: bool = False) -> bool:
- value = os.getenv(name)
- if value is None:
- return default
- return value.lower() in ("1", "true", "yes", "on")
-
-
-def get_int_env(name: str, default: int, minimum: int = 0) -> int:
- try:
- value = int(os.getenv(name, str(default)))
- except ValueError:
- return default
- if value < minimum:
- return default
- return value
-
-
-def _parse_json_object_response(
- response: httpx.Response,
- payload_name: str,
-) -> dict[str, Any]:
- try:
- payload = response.json()
- except ValueError as exc:
- raise ValueError(f"{payload_name} is not valid JSON") from exc
- if not isinstance(payload, dict):
- raise ValueError(f"{payload_name} must be a JSON object")
- return payload
-
-
-def get_task_retention_seconds() -> int:
- return get_int_env(
- "MINERU_API_TASK_RETENTION_SECONDS",
- DEFAULT_TASK_RETENTION_SECONDS,
- minimum=0,
- )
-
-
-def get_task_cleanup_interval_seconds() -> int:
- return get_int_env(
- "MINERU_API_TASK_CLEANUP_INTERVAL_SECONDS",
- DEFAULT_TASK_CLEANUP_INTERVAL_SECONDS,
- minimum=1,
- )
-
-
-def is_task_terminal(status: str) -> bool:
- return status in TASK_TERMINAL_STATES
-
-
-def warn_if_public_http_client_policy(host: str, allow_public_http_client: bool) -> None:
- _warn_if_public_http_client_policy(
- service_name="router",
- host=host,
- allow_public_http_client=allow_public_http_client,
- )
-
-
-def cleanup_path(path: str) -> None:
- try:
- if os.path.isfile(path):
- os.remove(path)
- elif os.path.isdir(path):
- shutil.rmtree(path)
- except FileNotFoundError:
- return
- except Exception as exc:
- logger.warning("Failed to clean up {}: {}", path, exc)
-
-
-def cleanup_temporary_directory(temp_dir: tempfile.TemporaryDirectory[str]) -> None:
- last_error: Exception | None = None
- for attempt in range(LOCAL_API_CLEANUP_RETRIES):
- try:
- temp_dir.cleanup()
- return
- except FileNotFoundError:
- return
- except Exception as exc:
- last_error = exc
- if attempt + 1 < LOCAL_API_CLEANUP_RETRIES:
- import time
-
- time.sleep(LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS)
-
- if last_error is not None:
- logger.warning("Failed to clean up temporary directory {}: {}", temp_dir.name, last_error)
-
-
-def parse_json_env(name: str, default: Sequence[str] = ()) -> tuple[str, ...]:
- raw = os.getenv(name)
- if not raw:
- return tuple(default)
- try:
- payload = json.loads(raw)
- except json.JSONDecodeError:
- logger.warning("Invalid {} value: {}", name, raw)
- return tuple(default)
- if not isinstance(payload, list) or not all(isinstance(item, str) for item in payload):
- logger.warning("Invalid {} value: {}", name, raw)
- return tuple(default)
- return tuple(payload)
-
-
-def resolve_connect_host(host: str) -> str:
- if host in {"0.0.0.0", "::"}:
- return "127.0.0.1"
- return host
-
-
-def reserve_unique_local_ports(count: int) -> list[int]:
- """一次性占用并释放多个本地端口,降低并行启动 worker 时的端口重复风险。"""
- if count <= 0:
- return []
-
- sockets: list[socket.socket] = []
- try:
- for _ in range(count):
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.bind(("127.0.0.1", 0))
- sock.listen(1)
- sockets.append(sock)
- return [int(sock.getsockname()[1]) for sock in sockets]
- finally:
- for sock in sockets:
- sock.close()
-
-
-def normalize_local_device_type(device: str | None) -> str:
- """将 get_device() 返回值规范化为基础设备类型。"""
- if not device:
- return "cuda"
- return str(device).strip().lower().split(":", 1)[0]
-
-
-def get_local_device_type() -> str:
- """懒加载读取当前设备类型,避免 router 导入阶段提前加载 torch。"""
- try:
- from mineru.utils.config_reader import get_device
-
- return normalize_local_device_type(get_device())
- except Exception as exc:
- logger.warning("Failed to resolve local device type, fallback to cuda: {}", exc)
- return "cuda"
-
-
-def get_local_device_visible_env_name() -> str:
- """根据当前设备类型选择本地 worker 的可见设备环境变量。"""
- if get_local_device_type() == "npu":
- return "ASCEND_RT_VISIBLE_DEVICES"
- return "CUDA_VISIBLE_DEVICES"
-
-
-def _parse_visible_devices_env(env_name: str) -> list[str] | None:
- """解析显式配置的可见设备列表,未配置时返回 None。"""
- configured_visible_devices = os.getenv(env_name)
- if configured_visible_devices is None:
- return None
- return [
- item.strip()
- for item in configured_visible_devices.split(",")
- if item.strip()
- ]
-
-
-def _detect_cuda_devices() -> list[str]:
- """自动探测当前 CUDA 可见设备编号。"""
- try:
- import torch # type: ignore
- except ImportError:
- return []
- if not torch.cuda.is_available():
- return []
- return [str(index) for index in range(torch.cuda.device_count())]
-
-
-def _detect_npu_devices() -> list[str]:
- """自动探测当前 Ascend NPU 可见设备编号。"""
- try:
- import torch_npu # type: ignore
- except ImportError:
- return []
- if not torch_npu.npu.is_available():
- return []
- return [str(index) for index in range(torch_npu.npu.device_count())]
-
-
-def detect_visible_local_devices() -> list[str]:
- """探测当前设备类型对应的可见本地设备编号。"""
- visible_devices_env_name = get_local_device_visible_env_name()
- configured_visible_devices = _parse_visible_devices_env(visible_devices_env_name)
- if configured_visible_devices is not None:
- return configured_visible_devices
-
- if visible_devices_env_name == "ASCEND_RT_VISIBLE_DEVICES":
- return _detect_npu_devices()
- return _detect_cuda_devices()
-
-
-def parse_local_gpus(local_gpus: str) -> list[str | None]:
- value = local_gpus.strip().lower()
- if value == LOCAL_GPU_NONE:
- return []
- if value == LOCAL_GPU_AUTO:
- detected = detect_visible_local_devices()
- if detected:
- return detected
- return [None]
-
- resolved: list[str | None] = []
- for item in local_gpus.split(","):
- normalized = item.strip()
- if not normalized:
- continue
- resolved.append(normalized)
- return resolved
-
-
-@dataclass(frozen=True)
-class RouterSettings:
- upstream_urls: tuple[str, ...] = ()
- local_gpus: str = LOCAL_GPU_AUTO
- worker_host: str = "127.0.0.1"
- enable_vlm_preload: bool = False
- worker_extra_args: tuple[str, ...] = ()
- task_retention_seconds: int = DEFAULT_TASK_RETENTION_SECONDS
- task_cleanup_interval_seconds: int = DEFAULT_TASK_CLEANUP_INTERVAL_SECONDS
- worker_refresh_interval_seconds: float = WORKER_REFRESH_INTERVAL_SECONDS
-
- @classmethod
- def from_env(cls) -> "RouterSettings":
- return cls(
- upstream_urls=parse_json_env("MINERU_ROUTER_UPSTREAM_URLS_JSON"),
- local_gpus=os.getenv("MINERU_ROUTER_LOCAL_GPUS", LOCAL_GPU_AUTO),
- worker_host=os.getenv("MINERU_ROUTER_WORKER_HOST", "127.0.0.1"),
- enable_vlm_preload=env_flag_enabled(
- "MINERU_ROUTER_ENABLE_VLM_PRELOAD",
- default=False,
- ),
- worker_extra_args=parse_json_env("MINERU_ROUTER_WORKER_ARGS_JSON"),
- task_retention_seconds=get_task_retention_seconds(),
- task_cleanup_interval_seconds=get_task_cleanup_interval_seconds(),
- )
-
-
-@dataclass
-class StagedUpload:
- field_name: str
- upload_name: str
- content_type: str
- path: str
-
-
-@dataclass
-class MultipartPayload:
- temp_dir: str
- fields: list[tuple[str, str]]
- uploads: list[StagedUpload]
-
- def cleanup(self) -> None:
- cleanup_path(self.temp_dir)
-
- def get_field_value(self, name: str) -> Optional[str]:
- for key, value in reversed(self.fields):
- if key == name:
- return value
- return None
-
-
-@dataclass
-class RouterTaskRecord:
- task_id: str
- upstream_server_id: str
- upstream_task_id: str
- upstream_base_url: str
- backend: str
- file_names: list[str]
- created_at: str
- status: str
- started_at: Optional[str] = None
- completed_at: Optional[str] = None
- error: Optional[str] = None
- queued_ahead: int | None = None
- upstream_error_count: int = 0
-
- def to_status_payload(self, request: Request) -> dict[str, Any]:
- payload = {
- "task_id": self.task_id,
- "status": self.status,
- "backend": self.backend,
- "file_names": self.file_names,
- "created_at": self.created_at,
- "started_at": self.started_at,
- "completed_at": self.completed_at,
- "error": self.error,
- "status_url": str(request.url_for("get_router_task_status", task_id=self.task_id)),
- "result_url": str(request.url_for("get_router_task_result", task_id=self.task_id)),
- }
- if self.queued_ahead is not None:
- payload["queued_ahead"] = self.queued_ahead
- return payload
-
-
-@dataclass
-class ManagedLocalServer:
- server_id: str
- worker_host: str
- gpu: str | None
- enable_vlm_preload: bool
- extra_cli_args: tuple[str, ...]
- connect_host: str = field(init=False)
- base_url: str | None = None
- process: subprocess.Popen[bytes] | None = None
- process_group_id: int | None = None
- temp_dir: tempfile.TemporaryDirectory[str] | None = None
-
- def __post_init__(self) -> None:
- self.connect_host = resolve_connect_host(self.worker_host)
-
- def is_running(self) -> bool:
- return self.process is not None and self.process.poll() is None
-
- async def start(self, client: httpx.AsyncClient, port: int | None = None) -> None:
- if self.is_running():
- return
-
- from mineru.cli_old.vlm_preload import build_local_api_cli_args
-
- self.temp_dir = tempfile.TemporaryDirectory(prefix=f"{self.server_id}-")
- output_root = Path(self.temp_dir.name) / "output"
- output_root.mkdir(parents=True, exist_ok=True)
-
- resolved_port = port if port is not None else find_free_port()
- remaining_cli_args = strip_local_api_network_args(self.extra_cli_args)
- worker_cli_args = build_local_api_cli_args(
- remaining_cli_args,
- enable_vlm_preload=self.enable_vlm_preload,
- )
- self.base_url = f"http://{self.connect_host}:{resolved_port}"
- env = os.environ.copy()
- env["MINERU_API_OUTPUT_ROOT"] = str(output_root)
- env["MINERU_API_DISABLE_ACCESS_LOG"] = "1"
- if self.gpu is not None:
- env[get_local_device_visible_env_name()] = str(self.gpu)
-
- command = [
- sys.executable,
- "-m",
- "mineru.cli_old.fast_api",
- "--host",
- self.worker_host,
- "--port",
- str(resolved_port),
- *worker_cli_args,
- ]
- self.process = subprocess.Popen(
- command,
- cwd=os.getcwd(),
- env=env,
- **build_managed_process_popen_kwargs(),
- )
- self.process_group_id = self.process.pid
-
- try:
- await self.wait_until_ready(client)
- except Exception:
- self.stop()
- raise
-
- async def wait_until_ready(
- self,
- client: httpx.AsyncClient,
- timeout_seconds: float = LOCAL_API_STARTUP_TIMEOUT_SECONDS,
- ) -> None:
- assert self.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:
- if self.process is not None and self.process.poll() is not None:
- raise RuntimeError(f"Local worker {self.server_id} exited before becoming healthy")
- try:
- response = await client.get(f"{self.base_url}{HEALTH_ENDPOINT}")
- if response.status_code == 200:
- return
- last_error = response_detail(response)
- except httpx.HTTPError as exc:
- last_error = str(exc)
- await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
-
- message = f"Timed out waiting for local worker {self.server_id} to become healthy"
- if last_error:
- message = f"{message}: {last_error}"
- raise RuntimeError(message)
-
- async def restart(self, client: httpx.AsyncClient) -> None:
- self.stop()
- await self.start(client)
-
- def stop(self) -> None:
- process = self.process
- process_group_id = self.process_group_id
- self.process = None
- self.process_group_id = None
- try:
- if process is not None or process_group_id is not None:
- stop_managed_process(
- process,
- process_group_id=process_group_id,
- shutdown_timeout_seconds=5,
- use_stdin_shutdown_watcher=False,
- )
- finally:
- temp_dir = self.temp_dir
- self.temp_dir = None
- self.base_url = None
- if temp_dir is not None:
- cleanup_temporary_directory(temp_dir)
-
-
-@dataclass
-class WorkerState:
- server_id: str
- source: str
- base_url: str
- gpu: str | None
- local_server: ManagedLocalServer | None = None
- healthy: bool = False
- queued_tasks: int = 0
- processing_tasks: int = 0
- completed_tasks: int = 0
- failed_tasks: int = 0
- max_concurrent_requests: int = 0
- processing_window_size: int = MIN_HEALTHY_PROCESSING_WINDOW_SIZE
- last_error: Optional[str] = None
- last_checked_at: Optional[str] = None
- pending_assignments: int = 0
- consecutive_health_failures: int = 0
-
- def score(self) -> float:
- denominator = max(1, self.max_concurrent_requests)
- numerator = self.queued_tasks + self.processing_tasks + self.pending_assignments
- return numerator / denominator
-
- def snapshot(self) -> dict[str, Any]:
- return {
- "server_id": self.server_id,
- "base_url": self.base_url,
- "source": self.source,
- "healthy": self.healthy,
- "gpu": self.gpu,
- "queued_tasks": self.queued_tasks,
- "processing_tasks": self.processing_tasks,
- "completed_tasks": self.completed_tasks,
- "failed_tasks": self.failed_tasks,
- "max_concurrent_requests": self.max_concurrent_requests,
- "processing_window_size": self.processing_window_size,
- "last_error": self.last_error,
- "last_checked_at": self.last_checked_at,
- }
-
-
-class WorkerPool:
- def __init__(
- self,
- settings: RouterSettings,
- client: httpx.AsyncClient,
- *,
- randomizer: Optional[random.Random] = None,
- ):
- self.settings = settings
- self.client = client
- self.randomizer = randomizer or random.Random()
- self._selection_lock = asyncio.Lock()
- self._monitor_task: asyncio.Task[Any] | None = None
- self._servers: dict[str, WorkerState] = {}
- self._build_servers()
-
- def _build_servers(self) -> None:
- for index, url in enumerate(dict.fromkeys(normalize_base_url(item) for item in self.settings.upstream_urls), start=1):
- server_id = f"remote-{index}"
- self._servers[server_id] = WorkerState(
- server_id=server_id,
- source=SOURCE_REMOTE,
- base_url=url,
- gpu=None,
- )
-
- local_specs = parse_local_gpus(self.settings.local_gpus)
- for index, gpu in enumerate(local_specs, start=1):
- if gpu is None:
- server_id = "local-cpu-1"
- else:
- server_id = f"local-gpu-{gpu}"
- local_server = ManagedLocalServer(
- server_id=server_id,
- worker_host=self.settings.worker_host,
- gpu=gpu,
- enable_vlm_preload=self.settings.enable_vlm_preload,
- extra_cli_args=self.settings.worker_extra_args,
- )
- self._servers[server_id] = WorkerState(
- server_id=server_id,
- source=SOURCE_LOCAL,
- base_url="",
- gpu=gpu,
- local_server=local_server,
- )
-
- @property
- def servers(self) -> list[WorkerState]:
- return list(self._servers.values())
-
- async def start(self) -> None:
- local_servers = [
- server for server in self.servers if server.local_server is not None
- ]
- local_ports = reserve_unique_local_ports(len(local_servers))
- await asyncio.gather(
- *(
- self._start_local_server(server, port)
- for server, port in zip(local_servers, local_ports)
- )
- )
-
- await self.refresh_all()
- if self._monitor_task is None or self._monitor_task.done():
- self._monitor_task = asyncio.create_task(self._monitor_loop(), name="mineru-router-worker-monitor")
-
- async def _start_local_server(self, server: WorkerState, port: int) -> None:
- """启动单个本地 worker,并把启动失败限制在该 worker 状态内。"""
- if server.local_server is None:
- return
- try:
- await server.local_server.start(self.client, port=port)
- server.base_url = normalize_base_url(server.local_server.base_url or "")
- except Exception as exc:
- server.healthy = False
- server.last_error = str(exc)
- server.last_checked_at = utc_now_iso()
-
- async def shutdown(self) -> None:
- if self._monitor_task is not None:
- self._monitor_task.cancel()
- with suppress(asyncio.CancelledError):
- await self._monitor_task
- self._monitor_task = None
- for server in self.servers:
- if server.local_server is not None:
- server.local_server.stop()
-
- async def _monitor_loop(self) -> None:
- while True:
- await asyncio.sleep(self.settings.worker_refresh_interval_seconds)
- await self.refresh_all()
-
- async def refresh_all(self) -> None:
- for server in self.servers:
- await self._refresh_server(server)
-
- def _update_server_from_health_payload(
- self,
- server: WorkerState,
- payload: dict[str, Any],
- ) -> None:
- protocol_version = payload.get("protocol_version")
- if protocol_version != API_PROTOCOL_VERSION:
- raise ValueError(
- f"Unsupported protocol_version={protocol_version}, expected {API_PROTOCOL_VERSION}"
- )
-
- server.queued_tasks = int(payload.get("queued_tasks", 0))
- server.processing_tasks = int(payload.get("processing_tasks", 0))
- server.completed_tasks = int(payload.get("completed_tasks", 0))
- server.failed_tasks = int(payload.get("failed_tasks", 0))
- server.max_concurrent_requests = int(payload.get("max_concurrent_requests", 0))
- if server.max_concurrent_requests <= 0:
- raise ValueError("max_concurrent_requests must be a positive integer")
- server.processing_window_size = max(
- MIN_HEALTHY_PROCESSING_WINDOW_SIZE,
- int(
- payload.get(
- "processing_window_size",
- MIN_HEALTHY_PROCESSING_WINDOW_SIZE,
- )
- ),
- )
- server.healthy = payload.get("status") == "healthy"
- server.last_error = (
- None if server.healthy else json.dumps(payload, ensure_ascii=False)
- )
- server.consecutive_health_failures = (
- 0 if server.healthy else server.consecutive_health_failures + 1
- )
-
- async def _refresh_server(self, server: WorkerState) -> None:
- if server.local_server is not None:
- if not server.local_server.is_running():
- try:
- await server.local_server.restart(self.client)
- server.base_url = normalize_base_url(server.local_server.base_url or "")
- except Exception as exc:
- server.healthy = False
- server.last_error = str(exc)
- server.last_checked_at = utc_now_iso()
- server.consecutive_health_failures += 1
- return
- elif server.local_server.base_url is not None:
- server.base_url = normalize_base_url(server.local_server.base_url)
-
- if not server.base_url:
- server.healthy = False
- server.last_error = "Upstream base_url is not configured"
- server.last_checked_at = utc_now_iso()
- server.consecutive_health_failures += 1
- return
-
- try:
- response = await self.client.get(f"{server.base_url}{HEALTH_ENDPOINT}")
- except httpx.HTTPError as exc:
- server.healthy = False
- server.last_error = str(exc)
- server.last_checked_at = utc_now_iso()
- server.consecutive_health_failures += 1
- if (
- server.local_server is not None
- and server.consecutive_health_failures
- >= WORKER_HEALTH_FAILURE_RESTART_THRESHOLD
- ):
- await self._restart_local_server(server)
- return
-
- server.last_checked_at = utc_now_iso()
- if response.status_code != 200:
- server.healthy = False
- server.last_error = response_detail(response)
- server.consecutive_health_failures += 1
- if (
- server.local_server is not None
- and server.consecutive_health_failures
- >= WORKER_HEALTH_FAILURE_RESTART_THRESHOLD
- ):
- await self._restart_local_server(server)
- return
-
- try:
- payload = _parse_json_object_response(response, "health payload")
- self._update_server_from_health_payload(server, payload)
- except (TypeError, ValueError) as exc:
- server.healthy = False
- server.last_error = f"Invalid health payload: {exc}"
- server.consecutive_health_failures += 1
- if (
- server.local_server is not None
- and server.consecutive_health_failures
- >= WORKER_HEALTH_FAILURE_RESTART_THRESHOLD
- ):
- await self._restart_local_server(server)
- return
-
- async def _restart_local_server(self, server: WorkerState) -> None:
- local_server = server.local_server
- if local_server is None:
- return
- try:
- await local_server.restart(self.client)
- server.base_url = normalize_base_url(local_server.base_url or "")
- response = await self.client.get(f"{server.base_url}{HEALTH_ENDPOINT}")
- if response.status_code == 200:
- server.last_checked_at = utc_now_iso()
- payload = _parse_json_object_response(response, "health payload")
- self._update_server_from_health_payload(server, payload)
- except (TypeError, ValueError) as exc:
- server.healthy = False
- server.last_error = f"Invalid health payload: {exc}"
- server.last_checked_at = utc_now_iso()
- except Exception as exc:
- server.healthy = False
- server.last_error = str(exc)
- server.last_checked_at = utc_now_iso()
-
- async def acquire_submission_server(self, excluded_server_ids: Optional[set[str]] = None) -> WorkerState | None:
- excluded = excluded_server_ids or set()
- async with self._selection_lock:
- candidates = [
- server
- for server in self.servers
- if server.healthy and server.server_id not in excluded
- ]
- if not candidates:
- return None
-
- randomized = list(candidates)
- self.randomizer.shuffle(randomized)
- randomized.sort(
- key=lambda item: (
- item.score(),
- item.pending_assignments,
- 0 if item.source == SOURCE_LOCAL else 1,
- )
- )
- selected = randomized[0]
- selected.pending_assignments += 1
- return selected
-
- async def release_submission_server(self, server_id: str) -> None:
- async with self._selection_lock:
- server = self._servers.get(server_id)
- if server is None:
- return
- if server.pending_assignments > 0:
- server.pending_assignments -= 1
-
- async def mark_submission_failure(self, server_id: str, error: str) -> None:
- async with self._selection_lock:
- server = self._servers.get(server_id)
- if server is None:
- return
- server.healthy = False
- server.last_error = error
- server.last_checked_at = utc_now_iso()
-
- def get_server(self, server_id: str) -> WorkerState | None:
- return self._servers.get(server_id)
-
- def health_payload(self) -> tuple[bool, dict[str, Any]]:
- servers = [server.snapshot() for server in self.servers]
- healthy_servers = [server for server in self.servers if server.healthy]
- payload = {
- "status": "healthy" if healthy_servers else "unhealthy",
- "version": __version__,
- "protocol_version": API_PROTOCOL_VERSION,
- "queued_tasks": sum(server.queued_tasks for server in self.servers),
- "processing_tasks": sum(server.processing_tasks for server in self.servers),
- "completed_tasks": sum(server.completed_tasks for server in self.servers),
- "failed_tasks": sum(server.failed_tasks for server in self.servers),
- "max_concurrent_requests": sum(
- server.max_concurrent_requests for server in healthy_servers
- ),
- "processing_window_size": min(
- (server.processing_window_size for server in healthy_servers),
- default=MIN_HEALTHY_PROCESSING_WINDOW_SIZE,
- ),
- "servers": servers,
- }
- if not healthy_servers:
- payload["error"] = "No healthy upstream MinerU API servers are available"
- return bool(healthy_servers), payload
-
-
-class RouterTaskRegistry:
- def __init__(
- self,
- *,
- task_retention_seconds: int,
- cleanup_interval_seconds: int,
- ):
- self.task_retention_seconds = task_retention_seconds
- self.cleanup_interval_seconds = cleanup_interval_seconds
- self._tasks: dict[str, RouterTaskRecord] = {}
- self._lock = asyncio.Lock()
- self._cleanup_task: asyncio.Task[Any] | None = None
-
- async def start(self) -> None:
- if self.task_retention_seconds <= 0:
- return
- if self._cleanup_task is None or self._cleanup_task.done():
- self._cleanup_task = asyncio.create_task(self._cleanup_loop(), name="mineru-router-task-cleanup")
-
- async def shutdown(self) -> None:
- if self._cleanup_task is not None:
- self._cleanup_task.cancel()
- with suppress(asyncio.CancelledError):
- await self._cleanup_task
- self._cleanup_task = None
-
- async def _cleanup_loop(self) -> None:
- while True:
- await asyncio.sleep(self.cleanup_interval_seconds)
- await self.cleanup_expired_tasks()
-
- async def register(
- self,
- *,
- upstream_server_id: str,
- upstream_base_url: str,
- upstream_task_id: str,
- backend: str,
- file_names: list[str],
- created_at: str,
- status: str,
- started_at: Optional[str],
- completed_at: Optional[str],
- error: Optional[str],
- queued_ahead: int | None,
- ) -> RouterTaskRecord:
- task = RouterTaskRecord(
- task_id=str(uuid.uuid4()),
- upstream_server_id=upstream_server_id,
- upstream_task_id=upstream_task_id,
- upstream_base_url=upstream_base_url,
- backend=backend,
- file_names=file_names,
- created_at=created_at,
- status=status,
- started_at=started_at,
- completed_at=completed_at,
- error=error,
- queued_ahead=queued_ahead,
- )
- async with self._lock:
- self._tasks[task.task_id] = task
- return task
-
- async def get(self, task_id: str) -> RouterTaskRecord | None:
- async with self._lock:
- return self._tasks.get(task_id)
-
- async def update_from_upstream_payload(
- self,
- task_id: str,
- payload: dict[str, Any],
- ) -> RouterTaskRecord | None:
- async with self._lock:
- task = self._tasks.get(task_id)
- if task is None:
- return None
- task.status = str(payload.get("status", task.status))
- task.backend = str(payload.get("backend", task.backend))
- file_names = payload.get("file_names")
- if isinstance(file_names, list) and all(isinstance(item, str) for item in file_names):
- task.file_names = list(file_names)
- task.created_at = str(payload.get("created_at", task.created_at))
- task.started_at = payload.get("started_at") if payload.get("started_at") is None else str(payload.get("started_at"))
- task.completed_at = payload.get("completed_at") if payload.get("completed_at") is None else str(payload.get("completed_at"))
- task.error = payload.get("error") if payload.get("error") is None else str(payload.get("error"))
- queued_ahead = payload.get("queued_ahead")
- task.queued_ahead = queued_ahead if isinstance(queued_ahead, int) else None
- task.upstream_error_count = 0
- return task
-
- async def increment_upstream_error(
- self,
- task_id: str,
- error: str,
- ) -> RouterTaskRecord | None:
- async with self._lock:
- task = self._tasks.get(task_id)
- if task is None:
- return None
- task.upstream_error_count += 1
- if task.upstream_error_count >= UPSTREAM_FAILURE_THRESHOLD:
- task.status = TASK_FAILED
- task.error = error
- task.completed_at = utc_now_iso()
- return task
-
- async def mark_failed(self, task_id: str, error: str) -> RouterTaskRecord | None:
- async with self._lock:
- task = self._tasks.get(task_id)
- if task is None:
- return None
- task.status = TASK_FAILED
- task.error = error
- task.completed_at = utc_now_iso()
- return task
-
- async def cleanup_expired_tasks(self) -> int:
- if self.task_retention_seconds <= 0:
- return 0
-
- now = datetime.now(timezone.utc)
- async with self._lock:
- expired_ids = [
- task_id
- for task_id, task in self._tasks.items()
- if self._is_task_expired(task, now)
- ]
- for task_id in expired_ids:
- self._tasks.pop(task_id, None)
- return len(expired_ids)
-
- def _is_task_expired(self, task: RouterTaskRecord, now: datetime) -> bool:
- if task.status not in TASK_TERMINAL_STATES or not task.completed_at:
- return False
- try:
- completed_at = datetime.fromisoformat(task.completed_at)
- except ValueError:
- return False
- if completed_at.tzinfo is None:
- completed_at = completed_at.replace(tzinfo=timezone.utc)
- return (now - completed_at).total_seconds() >= self.task_retention_seconds
-
-
-def warn_if_router_preload_ignored(settings: RouterSettings) -> None:
- if settings.enable_vlm_preload and not parse_local_gpus(settings.local_gpus):
- logger.warning(
- "Ignoring --enable-vlm-preload because mineru-router is not launching any local mineru-api workers."
- )
-
-
-async def startup_router_state(app: FastAPI, settings: RouterSettings) -> None:
- http_client = httpx.AsyncClient(
- timeout=build_http_timeout(),
- follow_redirects=True,
- )
- worker_pool = WorkerPool(settings, http_client)
- registry = RouterTaskRegistry(
- task_retention_seconds=settings.task_retention_seconds,
- cleanup_interval_seconds=settings.task_cleanup_interval_seconds,
- )
-
- try:
- await registry.start()
- await worker_pool.start()
- healthy, payload = worker_pool.health_payload()
- if not healthy:
- raise RuntimeError(
- payload.get(
- "error",
- "No healthy upstream MinerU API servers are available",
- )
- )
- except Exception:
- await registry.shutdown()
- await worker_pool.shutdown()
- await http_client.aclose()
- raise
-
- app.state.http_client = http_client
- app.state.worker_pool = worker_pool
- app.state.router_task_registry = registry
-
-
-async def shutdown_router_state(app: FastAPI) -> None:
- registry = getattr(app.state, "router_task_registry", None)
- worker_pool = getattr(app.state, "worker_pool", None)
- http_client = getattr(app.state, "http_client", None)
-
- if registry is not None:
- await registry.shutdown()
- if worker_pool is not None:
- await worker_pool.shutdown()
- if http_client is not None:
- await http_client.aclose()
-
- app.state.router_task_registry = None
- app.state.worker_pool = None
- app.state.http_client = None
-
-
-class UpstreamSubmissionUnavailable(RuntimeError):
- pass
-
-
-class UpstreamSubmissionRejected(RuntimeError):
- def __init__(self, status_code: int, detail: str):
- self.status_code = status_code
- self.detail = detail
- super().__init__(detail)
-
-
-def build_upload_destination(upload_dir: str, filename: str) -> Path:
- destination = Path(upload_dir) / filename
- if not destination.exists():
- return destination
-
- base_name = Path(filename).stem
- suffix = Path(filename).suffix
- index = 2
- while True:
- candidate = Path(upload_dir) / f"{base_name}__upload_{index}{suffix}"
- if not candidate.exists():
- return candidate
- index += 1
-
-
-async def stage_multipart_request(request: Request) -> MultipartPayload:
- temp_dir = tempfile.mkdtemp(prefix="mineru-router-request-")
- uploads: list[StagedUpload] = []
- fields: list[tuple[str, str]] = []
-
- try:
- form = await request.form()
- for key, value in form.multi_items():
- if isinstance(value, StarletteUploadFile):
- original_name = value.filename or f"upload-{uuid.uuid4()}"
- filename = normalize_upload_filename(original_name)
- destination = build_upload_destination(temp_dir, filename)
- with open(destination, "wb") as handle:
- while True:
- chunk = await value.read(1 << 20)
- if not chunk:
- break
- handle.write(chunk)
- uploads.append(
- StagedUpload(
- field_name=key,
- upload_name=original_name,
- content_type=value.content_type or "application/octet-stream",
- path=str(destination),
- )
- )
- await value.close()
- else:
- fields.append((key, str(value)))
- except Exception:
- cleanup_path(temp_dir)
- raise
-
- return MultipartPayload(temp_dir=temp_dir, fields=fields, uploads=uploads)
-
-
-def parse_submit_response(payload: Any) -> dict[str, Any]:
- if not isinstance(payload, dict):
- raise ValueError("MinerU upstream returned an invalid submit payload")
- task_id = payload.get("task_id")
- status = payload.get("status")
- backend = payload.get("backend")
- created_at = payload.get("created_at")
- if not isinstance(task_id, str) or not isinstance(status, str) or not isinstance(backend, str):
- raise ValueError("MinerU upstream returned an invalid submit payload")
- if created_at is not None and not isinstance(created_at, str):
- raise ValueError("MinerU upstream returned an invalid submit payload")
- return {
- "task_id": task_id,
- "status": status,
- "backend": backend,
- "file_names": payload.get("file_names", []),
- "created_at": created_at or utc_now_iso(),
- "started_at": payload.get("started_at"),
- "completed_at": payload.get("completed_at"),
- "error": payload.get("error"),
- "queued_ahead": payload.get("queued_ahead") if isinstance(payload.get("queued_ahead"), int) else None,
- }
-
-
-def submit_payload_to_upstream_sync(
- base_url: str,
- payload: MultipartPayload,
-) -> dict[str, Any]:
- with ExitStack() as stack, httpx.Client(
- timeout=build_http_timeout(),
- follow_redirects=True,
- ) as client:
- multipart = [
- (
- field_name,
- (None, field_value),
- )
- for field_name, field_value in payload.fields
- ]
- multipart.extend(
- [
- (
- upload.field_name,
- (
- upload.upload_name,
- stack.enter_context(open(upload.path, "rb")),
- upload.content_type,
- ),
- )
- for upload in payload.uploads
- ]
- )
- try:
- response = client.post(
- f"{base_url}{TASKS_ENDPOINT}",
- files=multipart,
- )
- except httpx.HTTPError as exc:
- raise UpstreamSubmissionUnavailable(str(exc)) from exc
-
- if response.status_code == 202:
- try:
- submit_response = _parse_json_object_response(response, "submit payload")
- return parse_submit_response(submit_response)
- except ValueError as exc:
- raise UpstreamSubmissionUnavailable(f"Invalid submit payload: {exc}") from exc
- if response.status_code in HTTP_RETRYABLE_STATUS_CODES:
- raise UpstreamSubmissionUnavailable(
- f"{response.status_code} {response_detail(response)}"
- )
- raise UpstreamSubmissionRejected(response.status_code, response_detail(response))
-
-
-async def submit_payload_to_upstream(
- base_url: str,
- payload: MultipartPayload,
-) -> dict[str, Any]:
- return await asyncio.to_thread(submit_payload_to_upstream_sync, base_url, payload)
-
-
-async def submit_router_task(
- request: Request,
- payload: MultipartPayload,
-) -> RouterTaskRecord:
- validate_public_http_client_request(
- public_bind_exposed=bool(
- getattr(request.app.state, "public_bind_exposed", False)
- ),
- allow_public_http_client=bool(
- getattr(request.app.state, "allow_public_http_client", False)
- ),
- backend=payload.get_field_value("backend") or "",
- server_url=payload.get_field_value("server_url"),
- )
- worker_pool: WorkerPool = request.app.state.worker_pool
- registry: RouterTaskRegistry = request.app.state.router_task_registry
- attempted_servers: set[str] = set()
- last_error: str | None = None
-
- while True:
- server = await worker_pool.acquire_submission_server(excluded_server_ids=attempted_servers)
- if server is None:
- if last_error is None:
- raise HTTPException(status_code=503, detail="No healthy upstream MinerU API servers are available")
- raise HTTPException(status_code=503, detail=last_error)
-
- try:
- upstream_payload = await submit_payload_to_upstream(server.base_url, payload)
- file_names = upstream_payload["file_names"]
- normalized_file_names = (
- list(file_names)
- if isinstance(file_names, list) and all(isinstance(item, str) for item in file_names)
- else []
- )
- return await registry.register(
- upstream_server_id=server.server_id,
- upstream_base_url=server.base_url,
- upstream_task_id=upstream_payload["task_id"],
- backend=upstream_payload["backend"],
- file_names=normalized_file_names,
- created_at=upstream_payload["created_at"],
- status=upstream_payload["status"],
- started_at=upstream_payload["started_at"] if isinstance(upstream_payload["started_at"], str) else None,
- completed_at=upstream_payload["completed_at"] if isinstance(upstream_payload["completed_at"], str) else None,
- error=upstream_payload["error"] if isinstance(upstream_payload["error"], str) else None,
- queued_ahead=upstream_payload["queued_ahead"],
- )
- except UpstreamSubmissionRejected as exc:
- raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
- except UpstreamSubmissionUnavailable as exc:
- attempted_servers.add(server.server_id)
- last_error = f"Failed to submit task via {server.server_id}: {exc}"
- await worker_pool.mark_submission_failure(server.server_id, str(exc))
- finally:
- await worker_pool.release_submission_server(server.server_id)
-
-
-async def fetch_router_task_status(
- request: Request,
- task: RouterTaskRecord,
-) -> RouterTaskRecord:
- if is_task_terminal(task.status):
- return task
-
- registry: RouterTaskRegistry = request.app.state.router_task_registry
- client: httpx.AsyncClient = request.app.state.http_client
- url = f"{task.upstream_base_url}{TASKS_ENDPOINT}/{task.upstream_task_id}"
- try:
- response = await client.get(url)
- except httpx.HTTPError as exc:
- updated = await registry.increment_upstream_error(task.task_id, str(exc))
- if updated is None:
- raise HTTPException(status_code=404, detail="Task not found") from exc
- return updated
-
- if response.status_code != 200:
- error = f"{response.status_code} {response_detail(response)}"
- updated = await registry.increment_upstream_error(task.task_id, error)
- if updated is None:
- raise HTTPException(status_code=404, detail="Task not found")
- return updated
-
- try:
- status_payload = _parse_json_object_response(response, "task status payload")
- except ValueError as exc:
- updated = await registry.increment_upstream_error(
- task.task_id,
- f"Invalid task status payload: {exc}",
- )
- if updated is None:
- raise HTTPException(status_code=404, detail="Task not found")
- return updated
-
- updated = await registry.update_from_upstream_payload(task.task_id, status_payload)
- if updated is None:
- raise HTTPException(status_code=404, detail="Task not found")
- return updated
-
-
-async def wait_for_router_task_terminal_state(
- request: Request,
- task: RouterTaskRecord,
- timeout_seconds: float = TASK_RESULT_TIMEOUT_SECONDS,
-) -> RouterTaskRecord:
- deadline = asyncio.get_running_loop().time() + timeout_seconds
- current_task = task
- while asyncio.get_running_loop().time() < deadline:
- current_task = await fetch_router_task_status(request, current_task)
- if is_task_terminal(current_task.status):
- return current_task
- await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
-
- raise HTTPException(
- status_code=504,
- detail=f"Timed out waiting for result of task {task.task_id}",
- )
-
-
-async def proxy_router_task_result(
- request: Request,
- task: RouterTaskRecord,
-) -> Response:
- client: httpx.AsyncClient = request.app.state.http_client
- result_url = f"{task.upstream_base_url}{TASKS_ENDPOINT}/{task.upstream_task_id}/result"
- try:
- upstream_response = await client.send(
- client.build_request(
- "GET",
- result_url,
- timeout=build_result_download_timeout(),
- ),
- stream=True,
- )
- except httpx.HTTPError as exc:
- await request.app.state.router_task_registry.increment_upstream_error(task.task_id, str(exc))
- raise HTTPException(status_code=502, detail=str(exc)) from exc
-
- if upstream_response.status_code != 200:
- body = await upstream_response.aread()
- await upstream_response.aclose()
- detail = body.decode("utf-8", errors="replace").strip() or upstream_response.reason_phrase
- await request.app.state.router_task_registry.increment_upstream_error(
- task.task_id,
- f"{upstream_response.status_code} {detail}",
- )
- raise HTTPException(
- status_code=upstream_response.status_code,
- detail=detail,
- )
-
- content_type = upstream_response.headers.get("content-type", "")
- if "application/json" in content_type:
- body = await upstream_response.aread()
- await upstream_response.aclose()
- return Response(
- content=body,
- status_code=200,
- media_type="application/json",
- )
-
- headers: dict[str, str] = {}
- content_disposition = upstream_response.headers.get("content-disposition")
- if content_disposition:
- headers["content-disposition"] = content_disposition
- return StreamingResponse(
- upstream_response.aiter_bytes(),
- status_code=200,
- media_type=content_type or "application/octet-stream",
- headers=headers,
- background=BackgroundTask(upstream_response.aclose),
- )
-
-
-async def build_sync_router_task_result_response(
- request: Request,
- task: RouterTaskRecord,
-) -> Response:
- client: httpx.AsyncClient = request.app.state.http_client
- result_url = f"{task.upstream_base_url}{TASKS_ENDPOINT}/{task.upstream_task_id}/result"
- try:
- upstream_response = await client.send(
- client.build_request(
- "GET",
- result_url,
- timeout=build_result_download_timeout(),
- ),
- stream=True,
- )
- except httpx.HTTPError as exc:
- await request.app.state.router_task_registry.increment_upstream_error(task.task_id, str(exc))
- raise HTTPException(status_code=502, detail=str(exc)) from exc
-
- if upstream_response.status_code != 200:
- body = await upstream_response.aread()
- await upstream_response.aclose()
- detail = body.decode("utf-8", errors="replace").strip() or upstream_response.reason_phrase
- await request.app.state.router_task_registry.increment_upstream_error(
- task.task_id,
- f"{upstream_response.status_code} {detail}",
- )
- raise HTTPException(status_code=upstream_response.status_code, detail=detail)
-
- sync_headers = build_sync_task_headers(task, request)
- content_type = upstream_response.headers.get("content-type", "")
- if "application/json" in content_type:
- try:
- await upstream_response.aread()
- payload_data = _parse_json_object_response(
- upstream_response,
- "task result payload",
- )
- except ValueError as exc:
- detail = f"Invalid task result payload: {exc}"
- await request.app.state.router_task_registry.increment_upstream_error(
- task.task_id,
- detail,
- )
- raise HTTPException(status_code=502, detail=detail) from exc
- finally:
- await upstream_response.aclose()
-
- merged_payload = {
- **task.to_status_payload(request),
- "backend": payload_data.get("backend", task.backend),
- "version": payload_data.get("version", __version__),
- "results": payload_data.get("results", {}),
- }
- return JSONResponse(status_code=200, content=merged_payload, headers=sync_headers)
-
- headers: dict[str, str] = {}
- content_disposition = upstream_response.headers.get("content-disposition")
- if content_disposition:
- headers["content-disposition"] = content_disposition
- return StreamingResponse(
- upstream_response.aiter_bytes(),
- status_code=200,
- media_type=content_type or "application/octet-stream",
- headers={**headers, **sync_headers},
- background=BackgroundTask(upstream_response.aclose),
- )
-
-
-def build_sync_task_headers(task: RouterTaskRecord, request: Request) -> dict[str, str]:
- payload = task.to_status_payload(request)
- return {
- FILE_PARSE_TASK_ID_HEADER: task.task_id,
- FILE_PARSE_TASK_STATUS_HEADER: task.status,
- FILE_PARSE_TASK_STATUS_URL_HEADER: payload["status_url"],
- FILE_PARSE_TASK_RESULT_URL_HEADER: payload["result_url"],
- }
-
-
-def create_app(settings: RouterSettings | None = None) -> FastAPI:
- resolved_settings = settings or RouterSettings.from_env()
- enable_docs = env_flag_enabled("MINERU_API_ENABLE_FASTAPI_DOCS", default=True)
-
- @asynccontextmanager
- async def lifespan(app: FastAPI):
- await startup_router_state(app, resolved_settings)
- try:
- yield
- finally:
- await shutdown_router_state(app)
-
- app = FastAPI(
- 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,
- )
- app.state.router_settings = resolved_settings
- configure_public_http_client_policy(
- app,
- public_bind_exposed=env_flag_enabled(
- MINERU_ROUTER_PUBLIC_BIND_EXPOSED_ENV,
- default=False,
- ),
- allow_public_http_client=env_flag_enabled(
- MINERU_ROUTER_ALLOW_PUBLIC_HTTP_CLIENT_ENV,
- default=False,
- ),
- )
- app.add_middleware(GZipMiddleware, minimum_size=1000)
-
- @app.post(
- path="/tasks",
- status_code=202,
- summary="Submit an asynchronous parse task through the router",
- description=(
- "Submit files and parse options to a healthy upstream MinerU API "
- "server selected by the router, then return a router task id."
- ),
- )
- async def submit_parse_task(
- http_request: Request,
- request_options: Annotated[
- ParseRequestOptions, Depends(parse_request_form)
- ],
- ):
- del request_options
- payload = await stage_multipart_request(http_request)
- try:
- router_task = await submit_router_task(http_request, payload)
- finally:
- payload.cleanup()
- response_payload = router_task.to_status_payload(http_request)
- response_payload["message"] = "Task submitted successfully"
- return JSONResponse(status_code=202, content=response_payload)
-
- @app.get(path="/tasks/{task_id}", name="get_router_task_status")
- async def get_router_task_status(task_id: str, request: Request):
- registry: RouterTaskRegistry = request.app.state.router_task_registry
- task = await registry.get(task_id)
- if task is None:
- raise HTTPException(status_code=404, detail="Task not found")
- task = await fetch_router_task_status(request, task)
- return task.to_status_payload(request)
-
- @app.get(path="/tasks/{task_id}/result", name="get_router_task_result")
- async def get_router_task_result(task_id: str, request: Request):
- registry: RouterTaskRegistry = request.app.state.router_task_registry
- task = await registry.get(task_id)
- if task is None:
- raise HTTPException(status_code=404, detail="Task not found")
-
- task = await fetch_router_task_status(request, task)
- if task.status in {TASK_PENDING, TASK_PROCESSING}:
- return JSONResponse(
- status_code=202,
- content={
- **task.to_status_payload(request),
- "message": "Task result is not ready yet",
- },
- )
- if task.status == TASK_FAILED:
- return JSONResponse(
- status_code=409,
- content={
- **task.to_status_payload(request),
- "message": "Task execution failed",
- },
- )
- return await proxy_router_task_result(request, task)
-
- @app.post(
- path="/file_parse",
- status_code=200,
- summary="Synchronously parse uploaded files through the router",
- description=(
- "Submit files and parse options to a healthy upstream MinerU API "
- "server selected by the router, wait for completion, and proxy the "
- "final result in the same response."
- ),
- )
- async def file_parse(
- request: Request,
- request_options: Annotated[
- ParseRequestOptions, Depends(parse_request_form)
- ],
- ):
- del request_options
- payload = await stage_multipart_request(request)
- try:
- router_task = await submit_router_task(request, payload)
- finally:
- payload.cleanup()
-
- router_task = await wait_for_router_task_terminal_state(request, router_task)
- if router_task.status == TASK_FAILED:
- return JSONResponse(
- status_code=409,
- content={
- **router_task.to_status_payload(request),
- "message": "Task execution failed",
- },
- )
-
- return await build_sync_router_task_result_response(request, router_task)
-
- @app.get(path="/health")
- async def health_check(request: Request):
- worker_pool: WorkerPool = request.app.state.worker_pool
- healthy, payload = worker_pool.health_payload()
- if healthy:
- return payload
- return JSONResponse(status_code=503, content=payload)
-
- return app
-
-
-app = create_app()
-
-
- context_settings=dict(ignore_unknown_options=True, allow_extra_args=True)
-)
[email protected]("--host", default="127.0.0.1", help="Server host (default: 127.0.0.1)")
[email protected]("--port", default=8002, type=int, help="Server port (default: 8002)")
[email protected]("--reload", is_flag=True, help="Enable auto-reload (development mode)")
- "--allow-public-http-client",
- is_flag=True,
- help=(
- "Allow *-http-client backends and server_url even when binding the router "
- "to 0.0.0.0 or ::."
- ),
-)
- "--upstream-url",
- "upstream_urls",
- multiple=True,
- help="Existing MinerU FastAPI base URL. Repeat to add multiple upstream servers.",
-)
- "--local-gpus",
- default=LOCAL_GPU_AUTO,
- help="Local GPU workers to launch: auto, none, or CSV such as 0,1,2.",
-)
- "--worker-host",
- default="127.0.0.1",
- help="Host for router-managed mineru-api workers (default: 127.0.0.1).",
-)
- "--enable-vlm-preload",
- "enable_vlm_preload",
- type=bool,
- default=False,
- help="Preload the local VLM model in router-managed mineru-api workers.",
-)
-def main(
- ctx: click.Context,
- host: str,
- port: int,
- reload: bool,
- allow_public_http_client: bool,
- upstream_urls: tuple[str, ...],
- local_gpus: str,
- worker_host: str,
- enable_vlm_preload: bool,
-):
- settings = RouterSettings(
- upstream_urls=tuple(upstream_urls),
- local_gpus=local_gpus,
- worker_host=worker_host,
- enable_vlm_preload=enable_vlm_preload,
- worker_extra_args=tuple(ctx.args),
- task_retention_seconds=get_task_retention_seconds(),
- task_cleanup_interval_seconds=get_task_cleanup_interval_seconds(),
- )
- public_bind_exposed = is_public_bind_host(host)
- warn_if_router_preload_ignored(settings)
- configure_public_http_client_policy(
- app,
- public_bind_exposed=public_bind_exposed,
- allow_public_http_client=allow_public_http_client,
- )
- os.environ["MINERU_ROUTER_UPSTREAM_URLS_JSON"] = json.dumps(list(settings.upstream_urls))
- os.environ["MINERU_ROUTER_LOCAL_GPUS"] = settings.local_gpus
- os.environ["MINERU_ROUTER_WORKER_HOST"] = settings.worker_host
- os.environ["MINERU_ROUTER_ENABLE_VLM_PRELOAD"] = (
- "1" if settings.enable_vlm_preload else "0"
- )
- os.environ["MINERU_ROUTER_WORKER_ARGS_JSON"] = json.dumps(list(settings.worker_extra_args))
- os.environ[MINERU_ROUTER_PUBLIC_BIND_EXPOSED_ENV] = (
- "1" if public_bind_exposed else "0"
- )
- os.environ[MINERU_ROUTER_ALLOW_PUBLIC_HTTP_CLIENT_ENV] = (
- "1" if allow_public_http_client else "0"
- )
- warn_if_public_http_client_policy(host, allow_public_http_client)
-
- access_log = not env_flag_enabled("MINERU_API_DISABLE_ACCESS_LOG")
- print(f"Start MinerU Router Service: http://{host}:{port}")
- print(f"API documentation: http://{host}:{port}/docs")
-
- if reload:
- uvicorn.run(
- "mineru.cli_old.router:app",
- host=host,
- port=port,
- reload=True,
- access_log=access_log,
- )
- return
-
- configured_app = create_app(settings)
- uvicorn.run(
- configured_app,
- host=host,
- port=port,
- reload=False,
- access_log=access_log,
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/mineru/cli_old/upload_utils.py b/mineru/cli_old/upload_utils.py
deleted file mode 100644
index 793895c9..00000000
--- a/mineru/cli_old/upload_utils.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from pathlib import Path
-
-
-def normalize_upload_filename(upload_name: str) -> str:
- """清理上传文件名,只保留 basename 并限制 stem 的 UTF-8 字节长度。"""
- max_stem_bytes = 200
- sanitized_name = Path(upload_name).name
- sanitized_path = Path(sanitized_name)
- encoded_stem = sanitized_path.stem.encode("utf-8")
- if len(encoded_stem) <= max_stem_bytes:
- normalized_stem = sanitized_path.stem
- else:
- truncated = encoded_stem[:max_stem_bytes]
- # 截断时回退到合法 UTF-8 边界,避免中文等多字节字符被切坏。
- while truncated:
- try:
- normalized_stem = truncated.decode("utf-8")
- break
- except UnicodeDecodeError as exc:
- truncated = truncated[: exc.start]
- else:
- normalized_stem = ""
- return f"{normalized_stem}{sanitized_path.suffix}"
diff --git a/mineru/cli_old/visualization.py b/mineru/cli_old/visualization.py
deleted file mode 100644
index dc2561c5..00000000
--- a/mineru/cli_old/visualization.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import json
-from dataclasses import dataclass
-from pathlib import Path
-
-from ..model.flash.pdf.document import PDFDocument
-from ..parser.base import ParseResult
-from ..types import PageInfo
-
-VISUALIZATION_FINISHED = "finished"
-VISUALIZATION_SKIPPED = "skipped"
-
-
-@dataclass(frozen=True)
-class VisualizationJob:
- document_stem: str
- backend: str
- parse_method: str
- parse_dir: Path
-
-
-@dataclass(frozen=True)
-class VisualizationResult:
- document_stem: str
- parse_dir: Path
- status: str
- message: str
- generated_files: tuple[str, ...] = ()
-
-
-def select_pages_for_pdf_visualization(
- pages: list[PageInfo],
- retained_page_indices: list[int] | None,
-) -> list[PageInfo]:
- """按重写 PDF 的实际页序筛选页面,避免坏页空占位参与 bbox 绘制。"""
- if retained_page_indices is None:
- return pages
- pages_by_original_index = {page.page_idx: page for page in pages}
- return [pages_by_original_index[page_idx] for page_idx in retained_page_indices if page_idx in pages_by_original_index]
-
-
-def run_visualization_job(job: VisualizationJob) -> VisualizationResult:
- middle_json_path = job.parse_dir / f"{job.document_stem}_middle.json"
- origin_pdf_path = job.parse_dir / f"{job.document_stem}_origin.pdf"
-
- if not middle_json_path.exists():
- return VisualizationResult(
- document_stem=job.document_stem,
- parse_dir=job.parse_dir,
- status=VISUALIZATION_SKIPPED,
- message=f"missing middle.json: {middle_json_path.name}",
- )
- if not origin_pdf_path.exists():
- return VisualizationResult(
- document_stem=job.document_stem,
- parse_dir=job.parse_dir,
- status=VISUALIZATION_SKIPPED,
- message=f"missing origin.pdf: {origin_pdf_path.name}",
- )
-
- try:
- payload = json.loads(middle_json_path.read_text(encoding="utf-8"))
- except Exception as exc:
- return VisualizationResult(
- document_stem=job.document_stem,
- parse_dir=job.parse_dir,
- status=VISUALIZATION_SKIPPED,
- message=f"failed to read middle.json: {exc}",
- )
-
- if not isinstance(payload, dict) or not isinstance(payload.get("pages"), list):
- return VisualizationResult(
- document_stem=job.document_stem,
- parse_dir=job.parse_dir,
- status=VISUALIZATION_SKIPPED,
- message="invalid middle.json: missing pages",
- )
-
- try:
- parse_result = ParseResult.from_dict(payload)
- pages = select_pages_for_pdf_visualization(
- parse_result.pages,
- parse_result._retained_page_indices,
- )
- pdf_bytes = origin_pdf_path.read_bytes()
- doc = PDFDocument(pdf_bytes)
- generated_files = [f"{job.document_stem}_layout.pdf"]
- doc.draw_layout_bbox(pages, str(job.parse_dir / generated_files[0]))
- except Exception as exc:
- return VisualizationResult(
- document_stem=job.document_stem,
- parse_dir=job.parse_dir,
- status=VISUALIZATION_SKIPPED,
- message=f"visualization failed: {exc}",
- )
-
- return VisualizationResult(
- document_stem=job.document_stem,
- parse_dir=job.parse_dir,
- status=VISUALIZATION_FINISHED,
- message="generated visualization pdf(s)",
- generated_files=tuple(generated_files),
- )
diff --git a/mineru/cli_old/vlm_preload.py b/mineru/cli_old/vlm_preload.py
deleted file mode 100644
index 9935e535..00000000
--- a/mineru/cli_old/vlm_preload.py
+++ /dev/null
@@ -1,85 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from collections.abc import Mapping, Sequence
-from typing import Any
-
-from loguru import logger
-
-from mineru.utils.engine_utils import get_vlm_engine
-
-SERVICE_CONFIG_DEFAULTS: dict[str, Any] = {
- "enable_vlm_preload": False,
-}
-
-
-def split_service_and_model_config(
- config: Mapping[str, Any] | None,
-) -> tuple[dict[str, Any], dict[str, Any]]:
- raw_config = dict(config or {})
- service_config: dict[str, Any] = {}
-
- for key, default in SERVICE_CONFIG_DEFAULTS.items():
- service_config[key] = bool(raw_config.pop(key, default))
-
- return service_config, raw_config
-
-
-def build_local_api_cli_args(
- extra_cli_args: Sequence[str],
- *,
- enable_vlm_preload: bool,
-) -> tuple[str, ...]:
- args = tuple(extra_cli_args)
- if not enable_vlm_preload:
- return args
-
- if "--enable-vlm-preload" in args or any(
- arg.startswith("--enable-vlm-preload=") for arg in args
- ):
- return args
-
- return args + ("--enable-vlm-preload", "true")
-
-
-def resolve_gradio_local_api_cli_args(
- extra_cli_args: Sequence[str],
- *,
- api_url: str | None,
- enable_vlm_preload: bool,
-) -> tuple[str, ...]:
- if enable_vlm_preload and api_url:
- logger.warning(
- "Ignoring --enable-vlm-preload because --api-url points to an existing MinerU FastAPI service."
- )
- return tuple(extra_cli_args)
-
- return build_local_api_cli_args(
- extra_cli_args,
- enable_vlm_preload=enable_vlm_preload,
- )
-
-
-def preload_vlm_model(*, model_kwargs: Mapping[str, Any] | None = None) -> str:
- vlm_engine = get_vlm_engine("auto", is_async=True)
- logger.info(f"Start init {vlm_engine}...")
-
- from mineru.model.vlm.runtime import ModelSingleton
-
- model_singleton = ModelSingleton()
- model_singleton.get_model(
- vlm_engine,
- None,
- None,
- **dict(model_kwargs or {}),
- )
- logger.info(f"{vlm_engine} init successfully.")
- return vlm_engine
-
-
-def maybe_preload_vlm_model(
- enable_vlm_preload: bool,
- *,
- model_kwargs: Mapping[str, Any] | None = None,
-) -> str | None:
- if not enable_vlm_preload:
- return None
- return preload_vlm_model(model_kwargs=model_kwargs)
diff --git a/mineru/kit/commands/__init__.py b/mineru/kit/commands/__init__.py
index 1b1ef711..ca3da3f9 100644
--- a/mineru/kit/commands/__init__.py
+++ b/mineru/kit/commands/__init__.py
@@ -1,5 +1,5 @@
"""mineru-kit command modules."""
-from . import api_server, models, parse, router, vlm_server
+from . import api_server, gradio, models, parse, router, vlm_server
-__all__ = ["api_server", "models", "parse", "router", "vlm_server"]
+__all__ = ["api_server", "gradio", "models", "parse", "router", "vlm_server"]
diff --git a/mineru/kit/commands/api_server.py b/mineru/kit/commands/api_server.py
index a3e2d598..1ab39237 100644
--- a/mineru/kit/commands/api_server.py
+++ b/mineru/kit/commands/api_server.py
@@ -8,6 +8,7 @@ import typer
from ...parser import api_server as parser_api_server
from ...types import SERVER_TIERS, ServerTier
from ...model.ocr.language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
+from ...utils.stdio import configure_standard_streams
from ..errors import exit_with_message
API_SERVER_LANGUAGES = PUBLIC_OCR_LANGUAGES
@@ -92,3 +93,12 @@ def api_server_cmd(
raise typer.Exit(exc.code) from None
except click.ClickException as exc:
exit_with_message("invalid_request", exc.format_message())
+
+
+def main() -> None:
+ """配置标准流后,以独立命令运行新版 API 服务入口。"""
+ configure_standard_streams()
+ typer.run(api_server_cmd)
+
+
+__all__ = ["API_SERVER_LANGUAGES", "api_server_cmd", "main"]
diff --git a/mineru/kit/commands/gradio.py b/mineru/kit/commands/gradio.py
new file mode 100644
index 00000000..311f0f86
--- /dev/null
+++ b/mineru/kit/commands/gradio.py
@@ -0,0 +1,124 @@
+"""`mineru-kit gradio` 的轻量命令门面。"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+from typing import Literal
+
+import typer
+
+from ...model.ocr.language import validate_public_ocr_lang
+from ...types import SERVER_TIERS, ServerTier
+from ...utils.stdio import configure_standard_streams
+from ..errors import exit_with_message
+
+
+def _require_gradio_dependencies() -> None:
+ """检查 Gradio 可选依赖,并在缺失时给出安装提示。"""
+ missing = [name for name in ("gradio", "gradio_pdf") if importlib.util.find_spec(name) is None]
+ if missing:
+ exit_with_message(
+ "dependency_missing",
+ "Gradio support requires the optional dependencies; install with `pip install 'mineru[gradio]'`.",
+ )
+
+
+def _validate_server_tier(value: str) -> ServerTier:
+ """校验自动启动的本地 API server 能力档位。"""
+ if value not in SERVER_TIERS:
+ exit_with_message(
+ "invalid_request",
+ f"Unsupported API server tier '{value}'. Supported tiers: {', '.join(SERVER_TIERS)}",
+ "api_server_tier",
+ )
+ return value # type: ignore[return-value]
+
+
+def _validate_positive_option(value: int, *, name: str) -> int:
+ """校验本地托管服务使用的正整数参数。"""
+ if value <= 0:
+ exit_with_message("invalid_request", f"{name} must be greater than zero", name)
+ return value
+
+
+def _validate_server_port(value: int) -> int:
+ """校验 Gradio 监听端口处于 TCP 有效范围。"""
+ if value < 1 or value > 65535:
+ exit_with_message("invalid_request", "server_port must be between 1 and 65535", "server_port")
+ return value
+
+
+def gradio_cmd(
+ api_url: str | None = typer.Option(None, "--api-url", help="External MinerU V1 API base URL"),
+ api_key: str | None = typer.Option(None, "--api-key", help="Bearer API key; falls back to MINERU_API_KEY"),
+ server_name: str = typer.Option("127.0.0.1", "--server-name", help="Gradio bind host"),
+ server_port: int = typer.Option(7860, "--server-port", help="Gradio bind port"),
+ output_dir: str = typer.Option("./output", "--output-dir", help="Directory for Gradio artifacts"),
+ enable_example: bool = typer.Option(True, "--enable-example/--no-enable-example", help="Show local examples"),
+ enable_api: bool = typer.Option(True, "--enable-api/--no-enable-api", help="Expose the Gradio event API"),
+ latex_delimiters_type: Literal["a", "b", "all"] = typer.Option(
+ "all", "--latex-delimiters-type", help="LaTeX delimiters used by the Markdown preview"
+ ),
+ api_server_tier: str = typer.Option("standard", "--api-server-tier", "--tier", help="Managed API server capability tier"),
+ api_server_no_flash: bool = typer.Option(
+ False, "--api-server-no-flash/--no-flash", help="Disable Flash on the managed server"
+ ),
+ api_server_concurrency: int = typer.Option(
+ 1, "--api-server-concurrency", "--concurrency", help="Managed server job concurrency"
+ ),
+ api_server_language: str = typer.Option("ch", "--api-server-language", "--language", help="Managed server OCR language"),
+ api_server_ocr_mode: Literal["auto", "txt", "ocr"] = typer.Option(
+ "auto", "--api-server-ocr-mode", "--ocr-mode", help="Managed server OCR mode"
+ ),
+ api_server_disable_image_analysis: bool = typer.Option(
+ False,
+ "--api-server-disable-image-analysis/--disable-image-analysis",
+ help="Disable managed server image analysis",
+ ),
+ api_server_preload_models: bool = typer.Option(
+ False, "--api-server-preload-models/--preload-models", help="Preload managed server models"
+ ),
+) -> None:
+ """启动基于 MinerU V1 API 的 Gradio 文档解析界面。"""
+ _require_gradio_dependencies()
+ _validate_server_port(server_port)
+ _validate_positive_option(api_server_concurrency, name="api_server_concurrency")
+ normalized_tier = _validate_server_tier(api_server_tier)
+ try:
+ normalized_language = validate_public_ocr_lang(api_server_language)
+ except ValueError as exc:
+ exit_with_message("invalid_request", str(exc), "api_server_language")
+
+ from ..gradio.app import launch_gradio
+
+ try:
+ resolved_api_key = api_key if api_key is not None else os.environ.get("MINERU_API_KEY")
+ launch_gradio(
+ api_url=api_url,
+ api_key=resolved_api_key,
+ server_name=server_name,
+ server_port=server_port,
+ output_dir=output_dir,
+ enable_example=enable_example,
+ enable_api=enable_api,
+ latex_delimiters_type=latex_delimiters_type,
+ api_server_tier=normalized_tier,
+ api_server_no_flash=api_server_no_flash,
+ api_server_concurrency=api_server_concurrency,
+ api_server_language=normalized_language,
+ api_server_ocr_mode=api_server_ocr_mode,
+ api_server_disable_image_analysis=api_server_disable_image_analysis,
+ api_server_preload_models=api_server_preload_models,
+ )
+ except Exception as exc:
+ exit_with_message("gradio_start_failed", str(exc))
+
+
+def main() -> None:
+ """以独立 console script 运行新版 Gradio 命令。"""
+ configure_standard_streams()
+ typer.run(gradio_cmd)
+
+
+__all__ = ["gradio_cmd", "main"]
diff --git a/mineru/kit/commands/models.py b/mineru/kit/commands/models.py
index 580a99bd..08915d91 100644
--- a/mineru/kit/commands/models.py
+++ b/mineru/kit/commands/models.py
@@ -21,6 +21,7 @@ from ...model.download import (
download_model_repo,
verify_model_repo,
)
+from ...utils.stdio import configure_standard_streams
from ..errors import exit_with_message
from ..output import print_info, print_success
@@ -182,4 +183,10 @@ def verify_cmd(
raise typer.Exit(1)
-__all__ = ["app", "download_cmd", "show_cmd", "verify_cmd", "model_repo_names"]
+def download_main() -> None:
+ """配置标准流后直接运行模型下载命令,无需再输入 download 子命令。"""
+ configure_standard_streams()
+ typer.run(download_cmd)
+
+
+__all__ = ["app", "download_cmd", "download_main", "show_cmd", "verify_cmd", "model_repo_names"]
diff --git a/mineru/kit/commands/vlm_server.py b/mineru/kit/commands/vlm_server.py
index 5fc95165..eb5c728d 100644
--- a/mineru/kit/commands/vlm_server.py
+++ b/mineru/kit/commands/vlm_server.py
@@ -10,8 +10,14 @@ import typer
from loguru import logger
from ...utils.platform import is_mac_os_version_supported
+from ...utils.stdio import configure_standard_streams
from ..errors import exit_with_message
+FORWARD_CONTEXT_SETTINGS = {
+ "ignore_unknown_options": True,
+ "allow_extra_args": True,
+}
+
def _module_available(module_name: str) -> bool:
try:
@@ -95,3 +101,14 @@ def vlm_server_cmd(
prog_name="mineru-kit vlm-server",
standalone_mode=False,
)
+
+
+def main() -> None:
+ """以独立命令启动 VLM 服务,复用 kit 的未知引擎参数透传规则。"""
+ configure_standard_streams()
+ app = typer.Typer(add_completion=False)
+ app.command(context_settings=FORWARD_CONTEXT_SETTINGS)(vlm_server_cmd)
+ app()
+
+
+__all__ = ["FORWARD_CONTEXT_SETTINGS", "main", "vlm_server_cmd"]
diff --git a/mineru/kit/gradio/__init__.py b/mineru/kit/gradio/__init__.py
new file mode 100644
index 00000000..49c4b72b
--- /dev/null
+++ b/mineru/kit/gradio/__init__.py
@@ -0,0 +1,13 @@
+"""MinerU Kit Gradio 实现。"""
+
+from .app import build_gradio_app, launch_gradio
+from .client import ManagedLocalApiServer, V1ArtifactClient, V1ArtifactError, V1ServerCapabilities
+
+__all__ = [
+ "ManagedLocalApiServer",
+ "V1ArtifactClient",
+ "V1ArtifactError",
+ "V1ServerCapabilities",
+ "build_gradio_app",
+ "launch_gradio",
+]
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.py
new file mode 100644
index 00000000..3fa7194d
--- /dev/null
+++ b/mineru/kit/gradio/app.py
@@ -0,0 +1,719 @@
+"""MinerU Kit 的 V1 Gradio 应用组装与启动入口。"""
+
+from __future__ import annotations
+
+import asyncio
+import html
+import os
+from pathlib import Path
+from collections.abc import Callable
+from typing import Any, Literal
+from urllib.parse import quote
+
+from ...filetypes import IMAGE_EXTENSIONS, OFFICE_EXTENSIONS, PARSEABLE_EXTENSIONS, PDF_EXTENSIONS
+from ...utils.stdio import configure_standard_streams
+from .artifacts import RunArtifacts, markdown_for_gradio, persist_parse_result, render_download
+from .client import (
+ ManagedLocalApiServer,
+ STATUS_COMPLETED,
+ STATUS_PREPARING_REQUEST,
+ STATUS_PROCESSING_OUTPUT,
+ V1ArtifactClient,
+ V1ServerCapabilities,
+)
+
+_DOWNLOAD_FORMATS: tuple[tuple[str, str], ...] = (
+ ("zip", "ZIP"),
+ ("html", "HTML"),
+ ("docx", "DOCX"),
+ ("latex", "LaTeX bundle"),
+ ("epub", "EPUB"),
+ ("pdf", "PDF"),
+)
+_DEFAULT_TIER = "standard"
+_DEFAULT_STATUS = "Upload a file and start conversion."
+_STATUS_STEPS = (
+ ("prepare", "准备"),
+ ("check", "检查服务"),
+ ("submit", "提交任务"),
+ ("process", "服务端解析"),
+ ("download", "下载结果"),
+ ("output", "整理输出"),
+ ("done", "完成"),
+)
+_LATEX_DELIMITERS_A = [
+ {"left": "$$", "right": "$$", "display": True},
+ {"left": "$", "right": "$", "display": False},
+]
+_LATEX_DELIMITERS_B = [
+ {"left": "\\(", "right": "\\)", "display": False},
+ {"left": "\\[", "right": "\\]", "display": True},
+]
+_KIT_MENU_CSS = """
+.mineru-kit-download-menu { position: relative; width: 100%; }
+.mineru-kit-download-trigger { width: 100%; }
+.mineru-kit-download-options {
+ position: absolute; left: 0; right: 0; top: calc(100% + 6px); z-index: 40;
+ display: flex !important; flex-direction: column; gap: 4px; padding: 6px;
+ border: 1px solid var(--mineru-panel-border, rgba(17,24,39,.12)); border-radius: 8px;
+ background: var(--background-fill-primary, #fff); box-shadow: 0 12px 28px rgba(15,23,42,.18);
+ opacity: 0; pointer-events: none; transform: translateY(-4px); visibility: hidden;
+ transition: opacity 120ms ease, transform 120ms ease, visibility 120ms ease;
+}
+.mineru-kit-download-menu:hover .mineru-kit-download-options,
+.mineru-kit-download-menu:focus-within .mineru-kit-download-options {
+ opacity: 1; pointer-events: auto; transform: translateY(0); visibility: visible;
+}
+.mineru-kit-download-options button { width: 100%; min-height: 34px; }
+.mineru-kit-status { min-height: 84px; }
+.mineru-kit-status-steps { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
+.mineru-kit-status-steps .status-step {
+ display: inline-flex; align-items: center; gap: 4px;
+ color: var(--body-text-color-subdued, #6b7280); font-size: 12px;
+}
+.mineru-kit-status-steps .status-step i { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .35; }
+.mineru-kit-status-steps .status-step.is-active { color: var(--mineru-accent, #f97316); font-weight: 600; }
+.mineru-kit-status-steps .status-step.is-active i, .mineru-kit-status-steps .status-step.is-done i { opacity: 1; }
+.mineru-kit-status-steps .status-step.is-error { color: #dc2626; font-weight: 600; }
+.mineru-kit-empty-preview { min-height: 160px; display: grid; place-items: center; opacity: .65; }
+.mineru-kit-image-preview img { max-height: var(--mineru-pdf-page-height, 720px); object-fit: contain; }
+@media (max-width: 900px) {
+ .mineru-kit-workspace { flex-direction: column !important; }
+ .mineru-kit-control, .mineru-kit-preview, .mineru-kit-results { min-width: 0 !important; width: 100% !important; }
+}
+"""
+
+
+def _resource_text(resource_name: str) -> str:
+ """从已安装 MinerU 包资源中读取 Gradio 静态文本。"""
+ resource_path = Path(__file__).resolve().parents[2] / "resources" / resource_name
+ return resource_path.read_text(encoding="utf-8")
+
+
+def _render_header(*, gradio_major_version: int = 5) -> str:
+ """渲染复用旧版视觉风格的静态 Header。"""
+ template = _resource_text("gradio_header.html")
+ values = {
+ "{{HEADER_TITLE}}": "MinerU 4:文档提取",
+ "{{HEADER_SUBTITLE}}": "开源文档提取工具,支持 PDF、Office、EPUB、OFD、HTML、CSV 与图片。",
+ "{{HEADER_SUPPORT_TEXT}}": "",
+ "{{HEADER_STARS_ALT}}": "GitHub 星标",
+ "{{HEADER_CODE_LINK}}": "代码",
+ "{{HEADER_MODEL_LINK}}": "模型",
+ "{{HEADER_MODEL_HUGGINGFACE_LINK}}": "Hugging Face",
+ "{{HEADER_MODEL_MODELSCOPE_LINK}}": "ModelScope",
+ "{{HEADER_PAPER_LINK}}": "论文",
+ "{{HEADER_PAPER_MINERU_REPORT}}": "MinerU · arXiv",
+ "{{HEADER_PAPER_MINERU25_REPORT}}": "MinerU 2.5 · arXiv",
+ "{{HEADER_PAPER_MINERU25PRO_REPORT}}": "MinerU 2.5 Pro · arXiv",
+ "{{HEADER_HOMEPAGE_LINK}}": "主页",
+ "{{HEADER_DOWNLOAD_LINK}}": "下载",
+ "{{HEADER_GRADIO_VERSION_CLASS}}": " mineru-gradio6-header" if gradio_major_version >= 6 else "",
+ }
+ rendered = template
+ for placeholder, value in values.items():
+ rendered = rendered.replace(placeholder, html.escape(value, quote=True))
+ return rendered
+
+
+def _supported_file_types() -> list[str]:
+ """把统一 filetypes 集合转换为 Gradio 文件选择器后缀。"""
+ return [f".{extension}" for extension in sorted(PARSEABLE_EXTENSIONS)]
+
+
+def _default_tier(capabilities: V1ServerCapabilities) -> str:
+ """按服务能力选择默认 tier,优先保持 Standard 语义。"""
+ if _DEFAULT_TIER in capabilities.tiers:
+ return _DEFAULT_TIER
+ for tier in ("advanced", "standard", "basic", "flash"):
+ if tier in capabilities.tiers:
+ return tier
+ return capabilities.tiers[0]
+
+
+def _status_html(message: str) -> str:
+ """生成不解释协议细节、只显示当前阶段的安全状态片段。"""
+ raw_message = str(message or _DEFAULT_STATUS)
+ safe_message = html.escape(raw_message)
+ lowered = raw_message.lower()
+ if raw_message.startswith("Failed:"):
+ current_index = len(_STATUS_STEPS) - 1
+ state_for_index = "error"
+ elif "downloading" in lowered or "downloaded" in lowered:
+ current_index, state_for_index = 4, "active"
+ elif "completed" in lowered:
+ current_index = len(_STATUS_STEPS) - 1
+ state_for_index = "done"
+ elif "preparing outputs" in lowered:
+ current_index, state_for_index = 5, "active"
+ elif "preparing" in lowered:
+ current_index, state_for_index = 0, "active"
+ elif "checking" in lowered:
+ current_index, state_for_index = 1, "active"
+ elif "submitting" in lowered:
+ current_index, state_for_index = 2, "active"
+ elif "processing" in lowered:
+ current_index, state_for_index = 3, "active"
+ else:
+ current_index, state_for_index = -1, "pending"
+ items: list[str] = []
+ for index, (_key, label) in enumerate(_STATUS_STEPS):
+ if state_for_index == "error" and index == current_index:
+ state = "is-error"
+ elif state_for_index == "done" or index < current_index:
+ state = "is-done"
+ elif index == current_index:
+ state = "is-active"
+ else:
+ state = "is-pending"
+ items.append(f'<span class="status-step {state}"><i></i>{label}</span>')
+ return (
+ '<div class="mineru-kit-status">'
+ f'<div class="mineru-kit-status-steps">{"".join(items)}</div>'
+ f"<strong>{safe_message}</strong>"
+ "</div>"
+ )
+
+
+def _file_suffix(path_value: str | Path | None) -> str:
+ """读取上传文件的小写后缀,供 UI 预览和页码控件判断。"""
+ if not path_value:
+ return ""
+ return Path(path_value).suffix.lower().lstrip(".")
+
+
+def _effective_page_range(path_value: str | Path | None, raw_page_range: str | None) -> str:
+ """仅为 PDF 保留用户输入的 V1 page_range,其它格式统一返回空字符串。"""
+ if _file_suffix(path_value) not in PDF_EXTENSIONS:
+ return ""
+ return str(raw_page_range or "").strip()
+
+
+def _is_pdf_or_image(path_value: str | Path | None) -> bool:
+ """判断上传文件是否可以在 PDF 预览组件中展示。"""
+ suffix = _file_suffix(path_value)
+ return suffix in PDF_EXTENSIONS or suffix in IMAGE_EXTENSIONS
+
+
+def _is_office(path_value: str | Path | None) -> bool:
+ """判断上传文件是否适合展示 Office 在线预览提示。"""
+ return _file_suffix(path_value) in OFFICE_EXTENSIONS
+
+
+def _preview_update(gr: Any, value: object, *, visible: bool) -> Any:
+ """构造跨 Gradio 5/6 兼容的组件更新对象。"""
+ return gr.update(value=value, visible=visible)
+
+
+def _download_updates(gr: Any, *, interactive: bool) -> tuple[Any, ...]:
+ """清空全部下载按钮的旧文件,并统一切换交互状态。"""
+ return tuple(gr.update(value=None, interactive=interactive) for _format_name, _label in _DOWNLOAD_FORMATS)
+
+
+def _latex_delimiters(delimiters_type: Literal["a", "b", "all"]) -> list[dict[str, Any]]:
+ """按 CLI 选择返回 Gradio Markdown 组件使用的公式分隔符。"""
+ if delimiters_type == "a":
+ return list(_LATEX_DELIMITERS_A)
+ if delimiters_type == "b":
+ return list(_LATEX_DELIMITERS_B)
+ return [*(_LATEX_DELIMITERS_A), *(_LATEX_DELIMITERS_B)]
+
+
+def build_gradio_app(
+ client: V1ArtifactClient,
+ capabilities: V1ServerCapabilities,
+ *,
+ output_root: Path,
+ enable_example: bool = True,
+ enable_api: bool = True,
+ latex_delimiters_type: Literal["a", "b", "all"] = "all",
+) -> Any:
+ """构建不启动监听端口的 Gradio Blocks 应用,便于单元测试和外部托管。"""
+ import gradio as gr
+ from gradio_pdf import PDF
+
+ if not capabilities.tiers:
+ raise ValueError("V1 API server did not advertise any parsing tier")
+ tier_choices = list(capabilities.tiers)
+ preferred_tier = _default_tier(capabilities)
+ file_types = _supported_file_types()
+ markdown_copy_kwargs = {"buttons": ["copy"]} if _gradio_major_version(gr) >= 6 else {"show_copy_button": True}
+
+ with gr.Blocks() as demo:
+ gr.HTML(
+ _render_header(gradio_major_version=_gradio_major_version(gr)),
+ elem_classes=["mineru-header-html"],
+ )
+ with gr.Row(elem_classes=["mineru-kit-workspace"]):
+ with gr.Column(scale=2, min_width=280, elem_classes=["mineru-kit-control", "mineru-control-column"]):
+ input_file = gr.File(
+ label="请选择要解析的文件",
+ file_types=file_types,
+ file_count="single",
+ type="filepath",
+ elem_classes=["mineru-upload-file"],
+ )
+ tier = gr.Dropdown(
+ choices=tier_choices,
+ value=preferred_tier,
+ label="解析 tier",
+ elem_classes=["mineru-tier-select"],
+ )
+ page_range = gr.Textbox(
+ value="",
+ label="页码范围",
+ placeholder="例如 1~5,8,-1;留空表示全部",
+ interactive=False,
+ elem_classes=["mineru-kit-page-range"],
+ )
+ with gr.Row(elem_classes=["mineru-actions"]):
+ convert_button = gr.Button("转换", variant="primary", scale=1, min_width=0)
+ clear_button = gr.ClearButton(value="清除", scale=1, min_width=1)
+ with gr.Column(elem_classes=["mineru-kit-download-menu"]):
+ gr.Button("下载", elem_classes=["mineru-kit-download-trigger"])
+ with gr.Column(elem_classes=["mineru-kit-download-options"]):
+ download_buttons: dict[str, Any] = {}
+ for format_name, label in _DOWNLOAD_FORMATS:
+ download_buttons[format_name] = gr.DownloadButton(
+ label,
+ visible=True,
+ interactive=False,
+ size="sm",
+ elem_classes=[f"mineru-kit-download-{format_name}"],
+ )
+ status_panel = gr.HTML(_status_html(_DEFAULT_STATUS), elem_classes=["mineru-kit-status"])
+
+ with gr.Column(scale=4, min_width=340, elem_classes=["mineru-kit-preview", "mineru-preview-pane"]):
+ pdf_preview = PDF(
+ label="文档预览",
+ interactive=False,
+ visible=False,
+ height=720,
+ elem_classes=["mineru-kit-pdf-preview"],
+ )
+ image_preview = gr.Image(
+ label="文档预览",
+ type="filepath",
+ interactive=False,
+ visible=False,
+ height=720,
+ elem_classes=["mineru-kit-image-preview"],
+ )
+ office_preview = gr.HTML(
+ value="",
+ visible=False,
+ min_height=320,
+ elem_classes=["mineru-kit-office-preview", "mineru-office-preview-html"],
+ )
+ generic_preview = gr.HTML(
+ value='<div class="mineru-kit-empty-preview">暂无源文档预览</div>',
+ visible=True,
+ elem_classes=["mineru-kit-generic-preview"],
+ )
+
+ with gr.Column(scale=4, min_width=340, elem_classes=["mineru-kit-results", "mineru-markdown-pane"]):
+ with gr.Tabs(elem_classes=["mineru-markdown-tabs"]):
+ with gr.Tab("Markdown 渲染"):
+ markdown_output = gr.Markdown(
+ value="",
+ height=775,
+ line_breaks=True,
+ latex_delimiters=_latex_delimiters(latex_delimiters_type),
+ **markdown_copy_kwargs,
+ elem_classes=["mineru-markdown-output"],
+ )
+ with gr.Tab("Markdown 源码"):
+ markdown_source = gr.Code(
+ value="",
+ language="markdown",
+ lines=28,
+ interactive=False,
+ elem_classes=["mineru-markdown-text"],
+ )
+ with gr.Tab("Structured Content 源码"):
+ structured_source = gr.Code(
+ value="",
+ language="json",
+ lines=28,
+ interactive=False,
+ elem_classes=["mineru-structured-content"],
+ )
+
+ if enable_example:
+ examples = _example_files(file_types)
+ if examples:
+ gr.Examples(examples=examples, inputs=input_file, label="示例", elem_id="mineru-kit-examples")
+
+ artifact_state = gr.State(value=None)
+ clear_button.add(
+ [
+ input_file,
+ page_range,
+ markdown_output,
+ markdown_source,
+ structured_source,
+ pdf_preview,
+ image_preview,
+ office_preview,
+ generic_preview,
+ status_panel,
+ ]
+ )
+
+ def update_file_preview(file_path: str | None) -> tuple[Any, ...]:
+ """切换源文件预览,并清除上一份文档的结果与下载状态。"""
+ reset_result = (_status_html(_DEFAULT_STATUS), "", "", "", None, *_download_updates(gr, interactive=False))
+ if not file_path:
+ return (
+ gr.update(value="", interactive=False),
+ _preview_update(gr, None, visible=False),
+ _preview_update(gr, None, visible=False),
+ _preview_update(gr, "", visible=False),
+ _preview_update(gr, '<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),
+ *reset_result,
+ )
+ suffix = _file_suffix(file_path)
+ page_update = gr.update(interactive=suffix in PDF_EXTENSIONS, value="")
+ if suffix in PDF_EXTENSIONS:
+ return (
+ page_update,
+ _preview_update(gr, file_path, visible=True),
+ _preview_update(gr, None, visible=False),
+ _preview_update(gr, "", visible=False),
+ _preview_update(gr, '<div class="mineru-kit-empty-preview">源文档预览</div>', visible=False),
+ *reset_result,
+ )
+ if suffix in IMAGE_EXTENSIONS:
+ return (
+ page_update,
+ _preview_update(gr, None, visible=False),
+ _preview_update(gr, file_path, visible=True),
+ _preview_update(gr, "", visible=False),
+ _preview_update(gr, '<div class="mineru-kit-empty-preview">源文档预览</div>', visible=False),
+ *reset_result,
+ )
+ if _is_office(file_path):
+ return (
+ page_update,
+ _preview_update(gr, None, visible=False),
+ _preview_update(gr, None, visible=False),
+ _preview_update(
+ gr,
+ '<div class="mineru-kit-empty-preview">Office 文件将在转换后提供结果</div>',
+ visible=True,
+ ),
+ _preview_update(gr, "", visible=False),
+ *reset_result,
+ )
+ return (
+ page_update,
+ _preview_update(gr, None, visible=False),
+ _preview_update(gr, None, visible=False),
+ _preview_update(gr, "", visible=False),
+ _preview_update(gr, '<div class="mineru-kit-empty-preview">该格式暂无源文档预览</div>', visible=True),
+ *reset_result,
+ )
+
+ private_event_kwargs = _private_event_kwargs(gr)
+ input_file.change(
+ fn=update_file_preview,
+ inputs=input_file,
+ outputs=[
+ page_range,
+ pdf_preview,
+ image_preview,
+ office_preview,
+ generic_preview,
+ status_panel,
+ markdown_output,
+ markdown_source,
+ structured_source,
+ artifact_state,
+ *download_buttons.values(),
+ ],
+ **private_event_kwargs,
+ )
+
+ async def convert_handler(
+ file_path: str | None,
+ selected_tier: str,
+ raw_page_range: str,
+ request: object | None = None,
+ ) -> Any:
+ """执行单文件 V1 解析并流式更新状态与三个结果标签。"""
+ empty_result = (
+ _status_html(_DEFAULT_STATUS),
+ "",
+ "",
+ "",
+ gr.update(value=None, visible=False),
+ gr.update(value=None, visible=False),
+ gr.update(value="", visible=False),
+ gr.update(value='<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),
+ None,
+ *_download_updates(gr, interactive=False),
+ )
+ if not file_path:
+ yield empty_result
+ return
+ source_path = Path(file_path).resolve()
+ if not source_path.is_file():
+ yield (_status_html("Failed: input file does not exist"), "", "", "", *empty_result[4:])
+ return
+ suffix = _file_suffix(source_path)
+ if suffix not in PARSEABLE_EXTENSIONS:
+ yield (_status_html(f"Failed: unsupported file type '.{suffix}'"), "", "", "", *empty_result[4:])
+ return
+ page_text = _effective_page_range(source_path, raw_page_range)
+ yield (_status_html(STATUS_PREPARING_REQUEST), "", "", "", *empty_result[4:])
+ status_queue: asyncio.Queue[str] = asyncio.Queue()
+ loop = asyncio.get_running_loop()
+
+ def emit(message: str) -> None:
+ """把同步 client 状态安全投递到当前 Gradio 事件循环。"""
+ loop.call_soon_threadsafe(status_queue.put_nowait, message)
+
+ task = asyncio.create_task(
+ client.parse_file(
+ source_path,
+ tier=selected_tier,
+ page_range=page_text,
+ status_callback=emit,
+ )
+ )
+ try:
+ while not task.done():
+ try:
+ message = await asyncio.wait_for(status_queue.get(), timeout=0.25)
+ except asyncio.TimeoutError:
+ continue
+ yield (_status_html(message), "", "", "", *empty_result[4:])
+ while not status_queue.empty():
+ yield (_status_html(status_queue.get_nowait()), "", "", "", *empty_result[4:])
+ result = await task
+ emit(STATUS_PROCESSING_OUTPUT)
+ yield (_status_html(STATUS_PROCESSING_OUTPUT), "", "", "", *empty_result[4:])
+ artifacts = await asyncio.to_thread(
+ persist_parse_result,
+ result,
+ source_path,
+ output_root=output_root,
+ page_range=page_text,
+ )
+ markdown_text = artifacts.markdown_path.read_text(encoding="utf-8")
+ structured_text = artifacts.structured_content_path.read_text(encoding="utf-8")
+ preview_path = artifacts.layout_pdf_path or artifacts.origin_pdf_path
+ office_html = _build_office_result_html(artifacts, request) if _is_office(source_path) else ""
+ generic_html = "" if preview_path or office_html else '<div class="mineru-kit-empty-preview">结果已生成</div>'
+ show_image_preview = suffix in IMAGE_EXTENSIONS and preview_path is None
+ yield (
+ _status_html(STATUS_COMPLETED),
+ markdown_for_gradio(markdown_text, artifacts),
+ markdown_text,
+ structured_text,
+ gr.update(value=str(preview_path) if preview_path else None, visible=preview_path is not None),
+ gr.update(value=str(source_path) if show_image_preview else None, visible=show_image_preview),
+ gr.update(value=office_html, visible=bool(office_html)),
+ gr.update(value=generic_html, visible=bool(generic_html)),
+ artifacts.as_state(),
+ *_download_updates(gr, interactive=True),
+ )
+ except Exception as exc:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ yield (_status_html(f"Failed: {exc}"), "", "", "", *empty_result[4:])
+
+ convert_outputs = [
+ status_panel,
+ markdown_output,
+ markdown_source,
+ structured_source,
+ pdf_preview,
+ image_preview,
+ office_preview,
+ generic_preview,
+ artifact_state,
+ *download_buttons.values(),
+ ]
+ # Gradio 在读取函数签名时需要真实的 Request 类型对象;注解在运行时补回以保持延迟导入。
+ convert_handler.__annotations__["request"] = gr.Request
+ event_kwargs: dict[str, Any] = {"queue": True, "show_progress": "hidden"}
+ if _gradio_major_version(gr) >= 6:
+ event_kwargs["api_visibility"] = "public" if enable_api else "private"
+ else:
+ event_kwargs["api_name"] = "to_markdown" if enable_api else False
+ convert_button.click(
+ fn=convert_handler,
+ inputs=[input_file, tier, page_range],
+ outputs=convert_outputs,
+ **event_kwargs,
+ )
+
+ reset_outputs = [
+ status_panel,
+ markdown_output,
+ markdown_source,
+ structured_source,
+ pdf_preview,
+ image_preview,
+ office_preview,
+ generic_preview,
+ artifact_state,
+ *download_buttons.values(),
+ ]
+
+ def reset_ui() -> tuple[Any, ...]:
+ """清除当前任务结果并恢复空预览状态。"""
+ return (
+ _status_html(_DEFAULT_STATUS),
+ "",
+ "",
+ "",
+ gr.update(value=None, visible=False),
+ gr.update(value=None, visible=False),
+ gr.update(value="", visible=False),
+ gr.update(value='<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),
+ None,
+ *_download_updates(gr, interactive=False),
+ )
+
+ clear_button.click(fn=reset_ui, inputs=[], outputs=reset_outputs, queue=False)
+
+ for format_name, _label in _DOWNLOAD_FORMATS:
+ download_buttons[format_name].click(
+ fn=_download_handler(format_name, output_root),
+ inputs=artifact_state,
+ outputs=download_buttons[format_name],
+ queue=True,
+ api_name=False,
+ )
+
+ demo._mineru_kit_css = _resource_text("gradio_app.css") + _KIT_MENU_CSS
+ demo._mineru_kit_js = _resource_text("gradio_app.js")
+ demo.queue(default_concurrency_limit=1)
+ return demo
+
+
+def launch_gradio(
+ *,
+ api_url: str | None,
+ api_key: str | None,
+ server_name: str,
+ server_port: int,
+ output_dir: str,
+ enable_example: bool,
+ enable_api: bool,
+ latex_delimiters_type: Literal["a", "b", "all"],
+ api_server_tier: str,
+ api_server_no_flash: bool,
+ api_server_concurrency: int,
+ api_server_language: str,
+ api_server_ocr_mode: Literal["auto", "txt", "ocr"],
+ api_server_disable_image_analysis: bool,
+ api_server_preload_models: bool,
+) -> None:
+ """启动 Gradio,并在未指定外部 URL 时托管一个本地 V1 API server。"""
+ configure_standard_streams()
+ resolved_api_key = api_key if api_key is not None else os.environ.get("MINERU_API_KEY")
+ output_root = Path(output_dir).expanduser().resolve()
+ output_root.mkdir(parents=True, exist_ok=True)
+ managed_server: ManagedLocalApiServer | None = None
+ resolved_api_url = api_url
+ try:
+ if resolved_api_url is None:
+ managed_server = ManagedLocalApiServer(
+ tier=api_server_tier, # type: ignore[arg-type]
+ no_flash=api_server_no_flash,
+ concurrency=api_server_concurrency,
+ language=api_server_language,
+ ocr_mode=api_server_ocr_mode,
+ disable_image_analysis=api_server_disable_image_analysis,
+ preload_models=api_server_preload_models,
+ api_key=resolved_api_key,
+ )
+ resolved_api_url = managed_server.start()
+ client = V1ArtifactClient(api_url=resolved_api_url, api_key=resolved_api_key)
+ capabilities = asyncio.run(client.discover())
+ demo = build_gradio_app(
+ client,
+ capabilities,
+ output_root=output_root,
+ enable_example=enable_example,
+ enable_api=enable_api,
+ latex_delimiters_type=latex_delimiters_type,
+ )
+ demo.launch(
+ server_name=server_name,
+ server_port=server_port,
+ allowed_paths=[str(output_root)],
+ css=getattr(demo, "_mineru_kit_css", None),
+ js=getattr(demo, "_mineru_kit_js", None),
+ )
+ finally:
+ if managed_server is not None:
+ managed_server.stop()
+
+
+def _example_files(file_types: list[str]) -> list[str]:
+ """读取当前工作目录 examples 下的受支持示例文件。"""
+ example_root = Path.cwd() / "examples"
+ if not example_root.is_dir():
+ return []
+ suffixes = set(file_types)
+ return [str(path) for path in sorted(example_root.iterdir()) if path.is_file() and path.suffix.lower() in suffixes]
+
+
+def _build_office_result_html(artifacts: RunArtifacts, request: Any = None) -> str:
+ """为 Office 结果生成带可选在线预览的安全提示,转换不依赖该 iframe。"""
+ source_name = html.escape(artifacts.source_path.name, quote=True)
+ headers = getattr(request, "headers", None) or {}
+ host = headers.get("x-forwarded-host") or headers.get("host") or "localhost:7860"
+ protocol = headers.get("x-forwarded-proto") or "http"
+ public_url = f"{protocol}://{host}/gradio_api/file={quote(str(artifacts.source_path), safe='/:')}"
+ viewer_url = "https://view.officeapps.live.com/op/embed.aspx?src=" + quote(public_url, safe="")
+ return (
+ '<div class="office-preview-shell">'
+ '<div class="office-preview-notice">'
+ '<div class="office-preview-copy">'
+ f"<strong>{source_name} 已完成解析</strong>"
+ "<span>Office 在线预览依赖外部服务,转换结果不依赖该预览。</span>"
+ f'<div class="office-preview-source-link">{html.escape(public_url, quote=True)}</div>'
+ "</div>"
+ '<div class="office-preview-actions">'
+ '<button type="button" class="office-preview-ignore-once">忽略</button>'
+ '<button type="button" class="office-preview-ignore-forever">不再提示</button>'
+ "</div>"
+ "</div>"
+ f'<iframe class="office-preview-frame" src="{html.escape(viewer_url, quote=True)}" frameborder="0"></iframe>'
+ "</div>"
+ )
+
+
+def _gradio_major_version(gr: Any) -> int:
+ """读取 Gradio 主版本,用于兼容 Gradio 5/6 事件参数。"""
+ raw_version = str(getattr(gr, "__version__", "5"))
+ try:
+ return int(raw_version.split(".", 1)[0])
+ except (TypeError, ValueError):
+ return 5
+
+
+def _private_event_kwargs(gr: Any) -> dict[str, Any]:
+ """生成不把内部文件事件公开为 Gradio API 的兼容参数。"""
+ if _gradio_major_version(gr) >= 6:
+ return {"queue": False, "api_visibility": "private"}
+ return {"queue": False, "api_name": False}
+
+
+def _download_handler(format_name: str, output_root: Path) -> Callable[[object], str]:
+ """创建一个绑定格式和 output root 的 Gradio 下载回调。"""
+
+ def handler(state: object) -> str:
+ """从当前任务 State 生成或读取指定格式的下载文件。"""
+ return render_download(state, format_name, allowed_root=output_root)
+
+ return handler
+
+
+__all__ = ["build_gradio_app", "launch_gradio"]
diff --git a/mineru/kit/gradio/artifacts.py b/mineru/kit/gradio/artifacts.py
new file mode 100644
index 00000000..f62552a5
--- /dev/null
+++ b/mineru/kit/gradio/artifacts.py
@@ -0,0 +1,840 @@
+"""Gradio 解析结果的持久化、图片物化与按需多格式渲染。"""
+
+from __future__ import annotations
+
+import base64
+import json
+import re
+import shutil
+import uuid
+import zipfile
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Literal, cast
+from urllib.parse import quote
+
+from loguru import logger
+
+from ...filetypes import IMAGE_EXTENSIONS, PDF_EXTENSIONS
+from ...model.flash.pdf.document import PDFDocument
+from ...model.flash.pdf.pdfium import safe_rewrite_pdf_bytes_with_pdfium_result
+from ...parser.base import ParseResult
+from ...parser.page_range import parse_page_range
+from ...render import (
+ DocxRenderOptions,
+ EpubRenderOptions,
+ HtmlRenderOptions,
+ LatexRenderOptions,
+ MarkdownRenderOptions,
+ PdfRenderOptions,
+ RenderFormat,
+ RenderMode,
+ StructuredContentRenderOptions,
+ render,
+)
+from ...types import BlockBase, ImagePayloadBlock, MiddleJson
+from ...utils.image_payload import parse_image_data_uri_strict, validate_image_sidecar_path
+
+DownloadFormat = Literal["zip", "html", "docx", "latex", "epub", "pdf"]
+
+_IMAGE_DATA_URI_RE = re.compile(r"data:image/[A-Za-z0-9.+-]+;base64,[A-Za-z0-9+/=]+")
+_MARKDOWN_IMAGE_RE = re.compile(r"!\[(?P<alt>[^\]]*)\]\((?P<src>[^)]+)\)")
+_HTML_IMAGE_RE = re.compile(
+ r"(?P<prefix><img\b[^>]*?\bsrc\s*=\s*)(?P<quote>[\"'])(?P<src>[^\"']+)(?P=quote)",
+ re.IGNORECASE,
+)
+_IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tiff", ".svg"}
+
+
+@dataclass
+class RunArtifacts:
+ """保存一次 Gradio 解析所产生的稳定文件路径。"""
+
+ root: Path
+ stem: str
+ source_path: Path
+ middle_json_path: Path
+ markdown_path: Path
+ structured_content_path: Path
+ bundle_zip_path: Path
+ downloads_dir: Path
+ file_suffix: str
+ origin_pdf_path: Path | None = None
+ layout_pdf_path: Path | None = None
+ page_indices: tuple[int, ...] = ()
+ generated_downloads: dict[str, Path] = field(default_factory=dict)
+
+ def as_state(self) -> dict[str, Any]:
+ """转换为可安全放入 Gradio State 的纯字符串字典。"""
+ return {
+ "root": str(self.root),
+ "stem": self.stem,
+ "source_path": str(self.source_path),
+ "middle_json_path": str(self.middle_json_path),
+ "markdown_path": str(self.markdown_path),
+ "structured_content_path": str(self.structured_content_path),
+ "bundle_zip_path": str(self.bundle_zip_path),
+ "downloads_dir": str(self.downloads_dir),
+ "file_suffix": self.file_suffix,
+ "origin_pdf_path": str(self.origin_pdf_path) if self.origin_pdf_path else "",
+ "layout_pdf_path": str(self.layout_pdf_path) if self.layout_pdf_path else "",
+ "page_indices": list(self.page_indices),
+ "generated_downloads": {key: str(value) for key, value in self.generated_downloads.items()},
+ }
+
+ @classmethod
+ def from_state(cls, state: object) -> "RunArtifacts":
+ """从 Gradio State 恢复路径,并拒绝缺失或类型错误的字段。"""
+ if not isinstance(state, dict):
+ raise ValueError("No parsed document is available")
+ required = (
+ "root",
+ "stem",
+ "source_path",
+ "middle_json_path",
+ "markdown_path",
+ "structured_content_path",
+ "bundle_zip_path",
+ "downloads_dir",
+ "file_suffix",
+ )
+ if any(not isinstance(state.get(key), str) for key in required):
+ raise ValueError("Invalid Gradio artifact state")
+ stem = cast(str, state["stem"])
+ if stem != _safe_stem(stem):
+ raise ValueError("Invalid Gradio artifact stem")
+ generated = state.get("generated_downloads")
+ generated_downloads: dict[str, Path] = {}
+ if isinstance(generated, dict):
+ root = Path(cast(str, state["root"])).resolve()
+ for key, value in generated.items():
+ if not isinstance(value, str):
+ continue
+ candidate = Path(value).resolve()
+ _ensure_path_inside(root, candidate)
+ generated_downloads[str(key)] = candidate
+ raw_indices = state.get("page_indices", [])
+ page_indices = tuple(int(value) for value in raw_indices) if isinstance(raw_indices, list) else ()
+ root = Path(cast(str, state["root"])).resolve()
+ core_paths = [
+ Path(cast(str, state[key])).resolve()
+ for key in (
+ "source_path",
+ "middle_json_path",
+ "markdown_path",
+ "structured_content_path",
+ "bundle_zip_path",
+ "downloads_dir",
+ )
+ ]
+ for path in core_paths:
+ _ensure_path_inside(root, path)
+ optional_paths = [_optional_path(state.get(key)) for key in ("origin_pdf_path", "layout_pdf_path")]
+ for path in optional_paths:
+ if path is not None:
+ _ensure_path_inside(root, path)
+ return cls(
+ root=root,
+ stem=stem,
+ source_path=Path(cast(str, state["source_path"])).resolve(),
+ middle_json_path=Path(cast(str, state["middle_json_path"])).resolve(),
+ markdown_path=Path(cast(str, state["markdown_path"])).resolve(),
+ structured_content_path=Path(cast(str, state["structured_content_path"])).resolve(),
+ bundle_zip_path=Path(cast(str, state["bundle_zip_path"])).resolve(),
+ downloads_dir=Path(cast(str, state["downloads_dir"])).resolve(),
+ file_suffix=cast(str, state["file_suffix"]),
+ origin_pdf_path=optional_paths[0],
+ layout_pdf_path=optional_paths[1],
+ page_indices=page_indices,
+ generated_downloads=generated_downloads,
+ )
+
+
+@dataclass
+class _ImageContext:
+ """为一次渲染保存源 PDF、页面映射和已写出的图片资源。"""
+
+ source_pdf: PDFDocument | None
+ source_page_by_middle_page: dict[int, int]
+ output_dir: Path
+ asset_root: Path
+ image_paths: dict[tuple[int, str, int | None, tuple[float, ...]], str] = field(default_factory=dict)
+
+ def crop_for_block(self, block: BlockBase, *, middle_page_idx: int) -> tuple[str, bytes] | None:
+ """按严格 block bbox 从源 PDF 裁剪图片并写入任务目录。"""
+ if self.source_pdf is None or block.bbox is None:
+ return None
+ source_page_idx = self.source_page_by_middle_page.get(middle_page_idx, middle_page_idx)
+ if source_page_idx < 0 or source_page_idx >= self.source_pdf.page_count:
+ return None
+ bbox = tuple(float(item) for item in block.bbox)
+ key = (source_page_idx, str(block.type), block.index, bbox)
+ existing = self.image_paths.get(key)
+ if existing is not None:
+ path = self.output_dir / existing
+ return existing, path.read_bytes() if path.is_file() else b""
+ try:
+ data = self.source_pdf.crop_image(block.bbox, source_page_idx)
+ except Exception as exc:
+ logger.warning("Failed to crop Gradio PDF image page={} bbox={}: {}", source_page_idx, bbox, exc)
+ return None
+ relative = f"images/page_{source_page_idx}_{_safe_type_name(str(block.type))}_{block.index or 0}.jpg"
+ relative = _unique_relative_image_name(relative, self.image_paths.values())
+ target = self.output_dir / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(data)
+ self.image_paths[key] = relative
+ return relative, data
+
+
+def create_run_artifacts(source_path: Path, output_root: Path) -> RunArtifacts:
+ """创建一次解析专属目录,并返回全部基础产物路径。"""
+ output_root = output_root.expanduser().resolve()
+ output_root.mkdir(parents=True, exist_ok=True)
+ stem = _safe_stem(source_path.stem)
+ run_id = f"{stem}_{uuid.uuid4().hex[:12]}"
+ root = output_root / "gradio" / run_id
+ root.mkdir(parents=True, exist_ok=False)
+ downloads_dir = root / "downloads"
+ downloads_dir.mkdir()
+ source_suffix = source_path.suffix.lower() or ".bin"
+ source_copy = root / f"source{source_suffix}"
+ return RunArtifacts(
+ root=root,
+ stem=stem,
+ source_path=source_copy,
+ middle_json_path=root / "middle_json.json",
+ markdown_path=root / "markdown.md",
+ structured_content_path=root / "structured_content.json",
+ bundle_zip_path=root / f"{stem}.zip",
+ downloads_dir=downloads_dir,
+ file_suffix=source_suffix.removeprefix("."),
+ )
+
+
+def persist_parse_result(
+ result: ParseResult,
+ source_path: Path,
+ *,
+ output_root: Path,
+ page_range: str,
+) -> RunArtifacts:
+ """保存 V1 ParseResult,并生成旧 UI 所需的 Markdown、JSON 和预览文件。"""
+ artifacts = create_run_artifacts(source_path, output_root)
+ shutil.copyfile(source_path, artifacts.source_path)
+ artifacts.middle_json_path.write_text(result.to_json(), encoding="utf-8")
+ if result._model_output is not None:
+ model_output = (
+ result._model_output.to_dict(skip_defaults=False)
+ if hasattr(result._model_output, "to_dict")
+ else result._model_output
+ )
+ (artifacts.root / "model_output.json").write_text(
+ json.dumps(model_output, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+
+ origin_pdf, page_indices = _prepare_origin_pdf(
+ artifacts.source_path,
+ page_range=page_range,
+ output_path=artifacts.root / "origin.pdf",
+ )
+ artifacts.origin_pdf_path = origin_pdf
+ artifacts.page_indices = tuple(page_indices)
+
+ image_context = _build_image_context(
+ result.middle_json,
+ origin_pdf,
+ artifacts.root,
+ page_indices=artifacts.page_indices,
+ )
+ try:
+ markdown = cast(
+ str,
+ render(
+ result.middle_json,
+ RenderFormat.MARKDOWN,
+ options=MarkdownRenderOptions(
+ mode=RenderMode.DEFAULT,
+ image_renderer=(lambda block: _markdown_image_for_block(image_context, block, result.middle_json))
+ if image_context.source_pdf is not None
+ else None,
+ ),
+ ),
+ )
+ artifacts.markdown_path.write_text(markdown, encoding="utf-8")
+ structured = cast(
+ dict[str, Any],
+ render(
+ result.middle_json,
+ RenderFormat.STRUCTURED_CONTENT,
+ options=StructuredContentRenderOptions(),
+ ),
+ )
+ artifacts.structured_content_path.write_text(
+ json.dumps(structured, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+ finally:
+ _close_image_context(image_context)
+
+ if origin_pdf is not None:
+ from .preview import draw_layout_overlay
+
+ layout_path = artifacts.root / "layout.pdf"
+ try:
+ draw_layout_overlay(
+ result.middle_json,
+ origin_pdf,
+ layout_path,
+ page_indices=artifacts.page_indices,
+ )
+ except Exception as exc:
+ logger.warning("Skipping Gradio layout overlay for {}: {}", artifacts.stem, exc)
+ else:
+ artifacts.layout_pdf_path = layout_path
+
+ build_bundle_zip(artifacts)
+ return artifacts
+
+
+def build_bundle_zip(artifacts: RunArtifacts) -> Path:
+ """把当前任务的源文件和基础产物压缩为用户可下载的 ZIP。"""
+ _ensure_path_inside(artifacts.root, artifacts.bundle_zip_path)
+ with zipfile.ZipFile(artifacts.bundle_zip_path, "w", zipfile.ZIP_DEFLATED) as archive:
+ for path in sorted(artifacts.root.rglob("*")):
+ if path.is_symlink():
+ raise ValueError(f"Artifact tree must not contain symlinks: {path}")
+ if not path.is_file() or path == artifacts.bundle_zip_path or artifacts.downloads_dir in path.parents:
+ continue
+ relative = path.relative_to(artifacts.root).as_posix()
+ validate_image_sidecar_path(relative)
+ archive.write(path, arcname=relative)
+ return artifacts.bundle_zip_path
+
+
+def markdown_for_gradio(markdown: str, artifacts: RunArtifacts) -> str:
+ """把任务目录中的相对图片路径转换为 Gradio 可访问的绝对文件 URL。"""
+ if not isinstance(markdown, str):
+ return ""
+
+ def _resolve(src: str) -> str | None:
+ """解析并校验任务目录内的图片引用。"""
+ normalized = src.strip()
+ if not normalized or _is_external_source(normalized):
+ return None
+ try:
+ safe = validate_image_sidecar_path(normalized)
+ except ValueError:
+ return None
+ candidate = (artifacts.root / safe).resolve()
+ try:
+ candidate.relative_to(artifacts.root.resolve())
+ except ValueError:
+ return None
+ if not candidate.is_file() or candidate.suffix.lower() not in _IMAGE_SUFFIXES:
+ return None
+ return f"/gradio_api/file={quote(str(candidate), safe='/:')}"
+
+ def replace_markdown(match: re.Match[str]) -> str:
+ """替换 Markdown 图片链接,保留无法安全解析的原文。"""
+ public = _resolve(match.group("src"))
+ return f"![{match.group('alt')}]({public})" if public else match.group(0)
+
+ result = _MARKDOWN_IMAGE_RE.sub(replace_markdown, markdown)
+
+ def replace_html(match: re.Match[str]) -> str:
+ """替换 HTML img 的本地图片链接。"""
+ public = _resolve(match.group("src"))
+ if public is None:
+ return match.group(0)
+ return f"{match.group('prefix')}{match.group('quote')}{public}{match.group('quote')}"
+
+ return _HTML_IMAGE_RE.sub(replace_html, result)
+
+
+def render_download(artifacts_state: object, format_name: str, *, allowed_root: Path | None = None) -> str:
+ """从已保存 Middle JSON 按需生成指定下载文件,并返回绝对路径。"""
+ artifacts = RunArtifacts.from_state(artifacts_state)
+ if allowed_root is not None:
+ _ensure_path_inside(allowed_root.resolve(), artifacts.root)
+ for path in (
+ artifacts.source_path,
+ artifacts.middle_json_path,
+ artifacts.markdown_path,
+ artifacts.structured_content_path,
+ artifacts.bundle_zip_path,
+ artifacts.downloads_dir,
+ ):
+ _ensure_path_inside(artifacts.root, path)
+ if format_name not in {"zip", "html", "docx", "latex", "epub", "pdf"}:
+ raise ValueError(f"Unsupported download format: {format_name}")
+ download_format = cast(DownloadFormat, format_name)
+ cached = artifacts.generated_downloads.get(download_format)
+ if cached is not None and cached.is_file():
+ return str(cached)
+ inferred_cache = _inferred_download_path(artifacts, download_format)
+ if inferred_cache is not None and inferred_cache.is_file():
+ return str(inferred_cache)
+ if download_format == "zip":
+ return str(build_bundle_zip(artifacts))
+
+ result = ParseResult.from_json(artifacts.middle_json_path.read_text(encoding="utf-8"))
+ middle_json = result.middle_json
+ source_pdf = artifacts.origin_pdf_path if artifacts.origin_pdf_path and artifacts.origin_pdf_path.is_file() else None
+ page_indices = artifacts.page_indices
+ if source_pdf is None:
+ source_pdf, resolved_page_indices = _prepare_origin_pdf(
+ artifacts.source_path,
+ page_range="",
+ output_path=artifacts.downloads_dir / f".{artifacts.stem}_render_source.pdf",
+ keep_existing=True,
+ )
+ page_indices = tuple(resolved_page_indices)
+ image_context = _build_image_context(
+ middle_json,
+ source_pdf,
+ artifacts.root,
+ page_indices=page_indices,
+ )
+ try:
+ if download_format == "html":
+ target = artifacts.downloads_dir / f"{artifacts.stem}.html"
+ _ensure_path_inside(artifacts.root, target)
+ html_middle = _materialize_middle_json(middle_json, image_context, mode="inline")
+ value = cast(
+ str,
+ render(
+ html_middle,
+ RenderFormat.HTML,
+ options=HtmlRenderOptions(standalone=True, document_title=artifacts.stem),
+ ),
+ )
+ target.write_text(value, encoding="utf-8")
+ elif download_format == "docx":
+ target = artifacts.downloads_dir / f"{artifacts.stem}.docx"
+ _ensure_path_inside(artifacts.root, target)
+ docx_middle = _materialize_middle_json(middle_json, image_context, mode="path")
+ value = cast(
+ bytes,
+ render(
+ docx_middle,
+ RenderFormat.DOCX,
+ options=DocxRenderOptions(asset_resolver=_asset_resolver(artifacts.root)),
+ ),
+ )
+ target.write_bytes(value)
+ elif download_format == "epub":
+ target = artifacts.downloads_dir / f"{artifacts.stem}.epub"
+ _ensure_path_inside(artifacts.root, target)
+ epub_middle = _materialize_middle_json(middle_json, image_context, mode="path")
+ value = cast(
+ bytes,
+ render(
+ epub_middle,
+ RenderFormat.EPUB,
+ options=EpubRenderOptions(title=artifacts.stem, asset_resolver=_asset_resolver(artifacts.root)),
+ ),
+ )
+ target.write_bytes(value)
+ elif download_format == "pdf":
+ target = artifacts.downloads_dir / f"{artifacts.stem}_rendered.pdf"
+ _ensure_path_inside(artifacts.root, target)
+ pdf_middle = _materialize_middle_json(middle_json, image_context, mode="path")
+ value = cast(
+ bytes,
+ render(
+ pdf_middle,
+ RenderFormat.PDF,
+ options=PdfRenderOptions(
+ document_title=artifacts.stem,
+ asset_resolver=_asset_resolver(artifacts.root),
+ ),
+ ),
+ )
+ target.write_bytes(value)
+ else:
+ target = artifacts.downloads_dir / f"{artifacts.stem}_latex.zip"
+ latex_root = artifacts.downloads_dir / "latex"
+ _ensure_path_inside(artifacts.root, target)
+ _ensure_path_inside(artifacts.root, latex_root)
+ latex_root.mkdir(parents=True, exist_ok=True)
+ latex_context = _build_image_context(
+ middle_json,
+ source_pdf,
+ latex_root,
+ page_indices=page_indices,
+ asset_root=artifacts.root,
+ )
+ try:
+ latex_middle = _materialize_middle_json(middle_json, latex_context, mode="path")
+ latex_text = cast(
+ str,
+ render(
+ latex_middle,
+ RenderFormat.LATEX,
+ options=LatexRenderOptions(document_title=artifacts.stem),
+ ),
+ )
+ tex_path = latex_root / f"{artifacts.stem}.tex"
+ tex_path.write_text(latex_text, encoding="utf-8")
+ _zip_directory(latex_root, target)
+ finally:
+ _close_image_context(latex_context)
+ _ensure_path_inside(artifacts.root, target)
+ build_bundle_zip(artifacts)
+ artifacts.generated_downloads[download_format] = target
+ return str(target)
+ finally:
+ _close_image_context(image_context)
+
+
+def _prepare_origin_pdf(
+ source_path: Path,
+ *,
+ page_range: str,
+ output_path: Path,
+ keep_existing: bool = False,
+) -> tuple[Path | None, list[int]]:
+ """将 PDF/image 输入转换为与解析范围一致的 origin PDF。"""
+ if keep_existing and output_path.is_file():
+ try:
+ with PDFDocument(output_path.read_bytes()) as doc:
+ return output_path, list(range(doc.page_count))
+ except Exception:
+ output_path.unlink(missing_ok=True)
+ suffix = source_path.suffix.lower().lstrip(".")
+ source_bytes = source_path.read_bytes()
+ if suffix in IMAGE_EXTENSIONS:
+ pdf_bytes = PDFDocument.from_image(source_bytes).bytes
+ output_path.write_bytes(pdf_bytes)
+ return output_path, [0]
+ if suffix not in PDF_EXTENSIONS:
+ return None, []
+ with PDFDocument(source_bytes) as doc:
+ page_count = doc.page_count
+ page_indices = parse_page_range(page_range, page_count)
+ if page_range.strip() and not page_indices:
+ raise ValueError(f"Page range does not select any pages: {page_range}")
+ if page_indices == list(range(page_count)):
+ output_path.write_bytes(source_bytes)
+ return output_path, page_indices
+ rewrite = safe_rewrite_pdf_bytes_with_pdfium_result(source_bytes, page_indices=page_indices)
+ output_path.write_bytes(rewrite.pdf_bytes or source_bytes)
+ return output_path, rewrite.retained_page_indices or page_indices
+
+
+def _build_image_context(
+ middle_json: MiddleJson,
+ origin_pdf: Path | None,
+ output_dir: Path,
+ *,
+ page_indices: tuple[int, ...] = (),
+ asset_root: Path | None = None,
+) -> _ImageContext:
+ """创建页面映射和源 PDF 上下文,供 Markdown 与多格式渲染共享。"""
+ resolved_asset_root = (asset_root or output_dir).resolve()
+ if origin_pdf is None:
+ return _ImageContext(
+ source_pdf=None,
+ source_page_by_middle_page={},
+ output_dir=output_dir,
+ asset_root=resolved_asset_root,
+ )
+ source_pdf = PDFDocument(origin_pdf.read_bytes())
+ page_map = _source_page_map(middle_json, source_pdf.page_count, page_indices)
+ return _ImageContext(
+ source_pdf=source_pdf,
+ source_page_by_middle_page=page_map,
+ output_dir=output_dir,
+ asset_root=resolved_asset_root,
+ )
+
+
+def _source_page_map(middle_json: MiddleJson, source_page_count: int, page_indices: tuple[int, ...]) -> dict[int, int]:
+ """将 Middle JSON 原始页号映射到当前 origin PDF 的顺序页号。"""
+ original_to_output = {
+ original_page_idx: output_page_idx
+ for output_page_idx, original_page_idx in enumerate(page_indices)
+ if output_page_idx < source_page_count
+ }
+ page_map: dict[int, int] = {}
+ for position, page in enumerate(middle_json.pages):
+ mapped = original_to_output.get(page.page_idx)
+ if mapped is not None:
+ page_map[page.page_idx] = mapped
+ elif position < source_page_count:
+ page_map[page.page_idx] = position
+ elif page.page_idx < source_page_count:
+ page_map[page.page_idx] = page.page_idx
+ return page_map
+
+
+def _close_image_context(context: _ImageContext) -> None:
+ """释放上下文持有的 PDFium 文档。"""
+ if context.source_pdf is not None:
+ context.source_pdf.close()
+
+
+def _markdown_image_for_block(context: _ImageContext, block: BlockBase, middle_json: MiddleJson) -> str:
+ """为 Markdown renderer 提供当前视觉 block 的相对图片引用。"""
+ page_idx = _find_block_page_idx(middle_json, block)
+ if page_idx is None:
+ return ""
+ cropped = context.crop_for_block(block, middle_page_idx=page_idx)
+ if cropped is None:
+ return ""
+ relative, _data = cropped
+ return f"![{str(block.type)}]({relative})"
+
+
+def _materialize_middle_json(middle_json: MiddleJson, context: _ImageContext, *, mode: Literal["path", "inline"]) -> MiddleJson:
+ """复制 Middle JSON,并为 PDF bbox 或 inline image 准备目标 renderer 所需的图片载荷。"""
+ copied = middle_json.model_copy(deep=True)
+ for page in copied.pages:
+ page.blocks = [_materialize_block(block, context, middle_page_idx=page.page_idx, mode=mode) for block in page.blocks]
+ return copied
+
+
+def _materialize_block(
+ block: BlockBase,
+ context: _ImageContext,
+ *,
+ middle_page_idx: int,
+ mode: Literal["path", "inline"],
+) -> BlockBase:
+ """递归复制 block 树,并统一处理图片 data URI、sidecar 和 PDF bbox。"""
+ updates: dict[str, Any] = {}
+ if isinstance(block, ImagePayloadBlock):
+ data: bytes | None = None
+ extension = "jpg"
+ if block.image_base64:
+ try:
+ data, extension = parse_image_data_uri_strict(block.image_base64)
+ except ValueError:
+ data = None
+ elif block.image_path:
+ safe_path = validate_image_sidecar_path(block.image_path)
+ candidate = (context.asset_root / safe_path).resolve()
+ _ensure_path_inside(context.asset_root, candidate)
+ if candidate.is_file():
+ data = candidate.read_bytes()
+ extension = candidate.suffix.lstrip(".") or extension
+ elif block.bbox is not None:
+ cropped = context.crop_for_block(block, middle_page_idx=middle_page_idx)
+ if cropped is not None:
+ relative, data = cropped
+ extension = Path(relative).suffix.lstrip(".") or extension
+ if data:
+ if mode == "inline":
+ updates["image_base64"] = _data_uri(data, extension)
+ updates["image_path"] = None
+ else:
+ relative = _write_materialized_asset(context.output_dir, data, extension, block, middle_page_idx)
+ updates["image_path"] = relative
+ updates["image_base64"] = None
+
+ content = getattr(block, "content", None)
+ if isinstance(content, list):
+ updates["content"] = [
+ _materialize_block(child, context, middle_page_idx=middle_page_idx, mode=mode) for child in content
+ ]
+ elif isinstance(content, str) and "<img" in content.lower():
+ if mode == "path":
+ updates["content"] = _replace_inline_images_in_markup(content, context.output_dir, block, middle_page_idx)
+ else:
+ updates["content"] = _inline_relative_images_in_markup(content, context.asset_root)
+ return block.model_copy(update=updates, deep=True) if updates else block
+
+
+def _write_materialized_asset(
+ output_dir: Path,
+ data: bytes,
+ extension: str,
+ block: BlockBase,
+ page_idx: int,
+ *,
+ ordinal: int = 0,
+) -> str:
+ """把图片写入受控目录并返回安全相对路径。"""
+ safe_extension = extension.lower().lstrip(".") or "jpg"
+ suffix = f"_{ordinal}" if ordinal > 0 else ""
+ relative = f"images/page_{page_idx}_{_safe_type_name(str(block.type))}_{block.index or 0}{suffix}.{safe_extension}"
+ relative = validate_image_sidecar_path(relative)
+ target = output_dir / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if not target.exists():
+ target.write_bytes(data)
+ return relative
+
+
+def _replace_inline_images_in_markup(content: str, output_dir: Path, block: BlockBase, page_idx: int) -> str:
+ """将 HTML 字符串中的 data URI 图片外置为安全相对路径。"""
+ ordinal = 0
+
+ def replace(match: re.Match[str]) -> str:
+ """写出匹配到的内嵌图片并返回相对 sidecar 路径。"""
+ nonlocal ordinal
+ ordinal += 1
+ try:
+ data, extension = parse_image_data_uri_strict(match.group(0))
+ except ValueError:
+ return match.group(0)
+ relative = _write_materialized_asset(output_dir, data, extension, block, page_idx, ordinal=ordinal)
+ return relative
+
+ return _IMAGE_DATA_URI_RE.sub(replace, content)
+
+
+def _inline_relative_images_in_markup(content: str, root: Path) -> str:
+ """将已有 HTML sidecar 引用读取为 data URI,保证 HTML 下载单文件可用。"""
+
+ def replace(match: re.Match[str]) -> str:
+ """读取一个安全相对图片并替换 src 属性。"""
+ source = match.group("src").strip()
+ if _is_external_source(source):
+ return match.group(0)
+ try:
+ safe_path = validate_image_sidecar_path(source)
+ except ValueError:
+ return match.group(0)
+ candidate = (root / safe_path).resolve()
+ try:
+ candidate.relative_to(root.resolve())
+ except ValueError:
+ return match.group(0)
+ if not candidate.is_file():
+ return match.group(0)
+ uri = _data_uri(candidate.read_bytes(), candidate.suffix.lstrip(".") or "png")
+ return f"{match.group('prefix')}{match.group('quote')}{uri}{match.group('quote')}"
+
+ return _HTML_IMAGE_RE.sub(replace, content)
+
+
+def _asset_resolver(root: Path) -> Callable[[str], bytes]:
+ """创建只允许读取当前任务目录内安全相对路径的 renderer asset resolver。"""
+ resolved_root = root.resolve()
+
+ def resolve(relative_path: str) -> bytes:
+ """读取一个已验证的任务图片 sidecar。"""
+ safe_path = validate_image_sidecar_path(relative_path)
+ candidate = (resolved_root / safe_path).resolve()
+ _ensure_path_inside(resolved_root, candidate)
+ if not candidate.is_file():
+ raise FileNotFoundError(safe_path)
+ return candidate.read_bytes()
+
+ return resolve
+
+
+def _find_block_page_idx(middle_json: MiddleJson, target: BlockBase) -> int | None:
+ """按 block 类型、index 和 bbox 查找视觉 block 所属页面。"""
+ target_key = _block_lookup_key(target)
+ for page in middle_json.pages:
+ pending: list[BlockBase] = list(page.blocks)
+ while pending:
+ block = pending.pop()
+ if block is target or _block_lookup_key(block) == target_key:
+ return page.page_idx
+ content = getattr(block, "content", None)
+ if isinstance(content, list):
+ pending.extend(child for child in content if isinstance(child, BlockBase))
+ return None
+
+
+def _block_lookup_key(block: BlockBase) -> tuple[str, int | None, tuple[float, ...] | None]:
+ """生成跨 renderer 深拷贝仍稳定的 block 查找键。"""
+ block_type = getattr(block.type, "value", block.type)
+ bbox = tuple(float(item) for item in block.bbox) if block.bbox is not None else None
+ return str(block_type), block.index, bbox
+
+
+def _zip_directory(directory: Path, target: Path) -> None:
+ """将目录内容压缩为稳定的相对路径 ZIP。"""
+ with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as archive:
+ for path in sorted(directory.rglob("*")):
+ if path.is_symlink():
+ raise ValueError(f"LaTeX artifact tree must not contain symlinks: {path}")
+ if path.is_file() and path != target:
+ relative = path.relative_to(directory).as_posix()
+ validate_image_sidecar_path(relative)
+ archive.write(path, arcname=relative)
+
+
+def _inferred_download_path(artifacts: RunArtifacts, format_name: DownloadFormat) -> Path | None:
+ """根据稳定命名规则定位已生成的下载文件,避免 State 未更新时重复渲染。"""
+ if format_name == "zip":
+ return artifacts.bundle_zip_path
+ names = {
+ "html": f"{artifacts.stem}.html",
+ "docx": f"{artifacts.stem}.docx",
+ "latex": f"{artifacts.stem}_latex.zip",
+ "epub": f"{artifacts.stem}.epub",
+ "pdf": f"{artifacts.stem}_rendered.pdf",
+ }
+ name = names.get(format_name)
+ return artifacts.downloads_dir / name if name is not None else None
+
+
+def _ensure_path_inside(root: Path, target: Path) -> None:
+ """确保文件路径解析后仍位于任务根目录内。"""
+ try:
+ target.resolve().relative_to(root.resolve())
+ except ValueError as exc:
+ raise ValueError(f"Artifact path escapes output root: {target}") from exc
+
+
+def _optional_path(value: object) -> Path | None:
+ """把 State 中的可选路径字段转换为绝对 Path。"""
+ if not isinstance(value, str) or not value:
+ return None
+ return Path(value).resolve()
+
+
+def _safe_stem(value: str) -> str:
+ """生成文件系统安全且长度受限的任务名称。"""
+ normalized = re.sub(r"[^\w.-]+", "_", str(value), flags=re.UNICODE).strip("._")
+ if not normalized:
+ normalized = "document"
+ encoded = normalized.encode("utf-8")
+ return encoded[:120].decode("utf-8", errors="ignore") or "document"
+
+
+def _safe_type_name(value: str) -> str:
+ """把 block 类型转换为稳定的文件名片段。"""
+ return re.sub(r"[^A-Za-z0-9_-]+", "_", value).strip("_") or "image"
+
+
+def _unique_relative_image_name(relative: str, existing: Any) -> str:
+ """在同一任务中为重复图片路径追加稳定序号。"""
+ existing_set = set(existing)
+ if relative not in existing_set:
+ return relative
+ path = Path(relative)
+ for index in range(2, 10000):
+ candidate = path.with_name(f"{path.stem}_{index}{path.suffix}").as_posix()
+ if candidate not in existing_set:
+ return candidate
+ raise ValueError("Too many duplicate image assets")
+
+
+def _data_uri(data: bytes, extension: str) -> str:
+ """按图片扩展名生成严格的 image data URI。"""
+ subtype = {"jpg": "jpeg", "jpeg": "jpeg", "svg": "svg+xml"}.get(extension.lower(), extension.lower())
+ return f"data:image/{subtype};base64,{base64.b64encode(data).decode('ascii')}"
+
+
+def _is_external_source(value: str) -> bool:
+ """判断图片引用是否已经是 scheme URL 或 data URI。"""
+ return bool(re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", value))
+
+
+__all__ = [
+ "DownloadFormat",
+ "RunArtifacts",
+ "build_bundle_zip",
+ "create_run_artifacts",
+ "markdown_for_gradio",
+ "persist_parse_result",
+ "render_download",
+]
diff --git a/mineru/kit/gradio/client.py b/mineru/kit/gradio/client.py
new file mode 100644
index 00000000..bf70924d
--- /dev/null
+++ b/mineru/kit/gradio/client.py
@@ -0,0 +1,445 @@
+"""Gradio 使用的 MinerU V1 能力发现与本地服务生命周期。"""
+
+from __future__ import annotations
+
+import atexit
+import os
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, cast
+
+import httpx
+
+from ...parser.api_client import MinerUApiParser, should_trust_env_for_url
+from ...parser.base import ParseResult
+from ...parser.process_control import ManagedProcessControl
+from ...types import SERVER_TIERS, TIERS, ServerTier, Tier
+from ...utils.stdio import utf8_subprocess_env
+
+STATUS_PREPARING_REQUEST = "Preparing request..."
+STATUS_CHECKING_SERVER = "Checking server status..."
+STATUS_SUBMITTING_TASK = "Submitting task..."
+STATUS_PROCESSING_ON_SERVER = "Processing on server..."
+STATUS_DOWNLOADING_RESULT = "Result archive downloaded."
+STATUS_PROCESSING_OUTPUT = "Preparing outputs..."
+STATUS_COMPLETED = "Completed"
+
+
+class V1ArtifactError(RuntimeError):
+ """表示 Gradio 访问 V1 API 或读取解析产物时的稳定错误。"""
+
+ def __init__(self, message: str, *, code: str = "v1_api_error") -> None:
+ """保存可供状态面板展示的错误消息和协议错误码。"""
+ self.code = code
+ super().__init__(message)
+
+
+@dataclass(frozen=True)
+class V1ServerCapabilities:
+ """记录一次 V1 server 能力发现结果,供 UI 构造控件使用。"""
+
+ base_url: str
+ tiers: tuple[str, ...]
+ output_formats: tuple[str, ...]
+ sources: tuple[str, ...]
+
+
+def normalize_v1_base_url(value: str) -> str:
+ """规范化 V1 API base URL,并拒绝空地址和缺少 scheme 的输入。"""
+ normalized = str(value).strip().rstrip("/")
+ if not normalized:
+ raise V1ArtifactError("V1 API URL must not be empty", code="invalid_api_url")
+ if "://" not in normalized:
+ normalized = f"http://{normalized}"
+ try:
+ parsed = httpx.URL(normalized)
+ except (httpx.InvalidURL, ValueError) as exc:
+ raise V1ArtifactError(f"Invalid V1 API URL: {value}", code="invalid_api_url") from exc
+ if parsed.scheme not in {"http", "https"} or not parsed.host:
+ raise V1ArtifactError(f"Unsupported V1 API URL: {value}", code="invalid_api_url")
+ if parsed.query or parsed.fragment or parsed.username or parsed.password:
+ raise V1ArtifactError("V1 API URL must not contain credentials, query, or fragment", code="invalid_api_url")
+ return str(parsed).rstrip("/")
+
+
+def _error_detail(response: httpx.Response) -> tuple[str, str]:
+ """从 V1 error envelope 提取稳定 code/message,避免把整段 HTML 返回给用户。"""
+ try:
+ payload = response.json()
+ except ValueError:
+ payload = None
+ error = payload.get("error") if isinstance(payload, dict) else None
+ if isinstance(error, dict):
+ code = str(error.get("code") or f"http_{response.status_code}")
+ message = str(error.get("message") or response.text[:500] or "V1 API request failed")
+ return code, message
+ return f"http_{response.status_code}", response.text[:500] or "V1 API request failed"
+
+
+def _check_json_response(response: httpx.Response, *, endpoint: str) -> dict[str, Any]:
+ """校验 V1 JSON 响应并将协议错误转换为 Gradio client 异常。"""
+ if response.status_code >= 400:
+ code, message = _error_detail(response)
+ raise V1ArtifactError(f"{endpoint}: {message}", code=code)
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise V1ArtifactError(f"{endpoint} did not return JSON", code="invalid_response") from exc
+ if not isinstance(payload, dict):
+ raise V1ArtifactError(f"{endpoint} returned a non-object JSON payload", code="invalid_response")
+ return payload
+
+
+class V1ArtifactClient:
+ """复用 `MinerUApiParser` 的 V1 请求流程并提供 Gradio 能力发现。"""
+
+ def __init__(
+ self,
+ *,
+ api_url: str,
+ api_key: str | None = None,
+ transport: httpx.AsyncBaseTransport | None = None,
+ ) -> None:
+ """创建不保存文档内容的 V1 client;API Key 只保存在当前进程内存。"""
+ self.base_url = normalize_v1_base_url(api_url)
+ self.api_key = api_key if api_key is not None else os.environ.get("MINERU_API_KEY")
+ self._transport = transport
+ self._capabilities: V1ServerCapabilities | None = None
+
+ @property
+ def capabilities(self) -> V1ServerCapabilities | None:
+ """返回最近一次能力发现快照。"""
+ return self._capabilities
+
+ async def discover(self) -> V1ServerCapabilities:
+ """调用 `/v1/health` 与 `/v1/tiers`,校验 Gradio 所需的 V1 能力。"""
+ trust_env = should_trust_env_for_url(self.base_url)
+ try:
+ async with httpx.AsyncClient(
+ timeout=httpx.Timeout(30, connect=10),
+ follow_redirects=True,
+ trust_env=trust_env,
+ transport=self._transport,
+ ) as client:
+ health_response = await client.get(f"{self.base_url}/v1/health", headers=self._headers())
+ health = _check_json_response(health_response, endpoint="GET /v1/health")
+ tiers_response = await client.get(f"{self.base_url}/v1/tiers", headers=self._headers())
+ tiers_payload = _check_json_response(tiers_response, endpoint="GET /v1/tiers")
+ except V1ArtifactError:
+ raise
+ except httpx.HTTPError as exc:
+ raise V1ArtifactError(f"Unable to reach V1 API at {self.base_url}: {exc}", code="server_unreachable") from exc
+
+ features = health.get("features")
+ if health.get("status") != "ok":
+ raise V1ArtifactError("V1 health response did not report status=ok", code="invalid_response")
+ if not isinstance(features, dict):
+ raise V1ArtifactError("V1 health response is missing features", code="invalid_response")
+ output_formats = _string_tuple(features.get("output_formats"), "features.output_formats")
+ sources = _string_tuple(features.get("sources"), "features.sources")
+ if "zip" not in output_formats:
+ raise V1ArtifactError(
+ "The configured V1 API server does not advertise zip output, which is required by Gradio.",
+ code="unsupported_output_format",
+ )
+ if "file_id" not in sources:
+ raise V1ArtifactError(
+ "The configured V1 API server does not advertise file_id uploads, which are required by Gradio.",
+ code="unsupported_source",
+ )
+
+ raw_tiers = tiers_payload.get("data")
+ if not isinstance(raw_tiers, list):
+ raise V1ArtifactError("V1 tiers response is missing data", code="invalid_response")
+ tiers: list[str] = []
+ for item in raw_tiers:
+ tier_id = item.get("id") if isinstance(item, dict) else None
+ if isinstance(tier_id, str) and tier_id in TIERS and tier_id not in tiers:
+ tiers.append(tier_id)
+ if not tiers:
+ raise V1ArtifactError("The V1 API server did not advertise a supported parsing tier", code="tier_unavailable")
+
+ capabilities = V1ServerCapabilities(
+ base_url=self.base_url,
+ tiers=tuple(tiers),
+ output_formats=output_formats,
+ sources=sources,
+ )
+ self._capabilities = capabilities
+ return capabilities
+
+ async def parse_file(
+ self,
+ path: Path,
+ *,
+ tier: str,
+ page_range: str,
+ status_callback: Callable[[str], None] | None = None,
+ ) -> ParseResult:
+ """通过 V1 API 解析单个文件,并返回带图片/模型输出的 `ParseResult`。"""
+ if not path.is_file():
+ raise FileNotFoundError(path)
+ if tier not in TIERS:
+ raise V1ArtifactError(f"Unsupported parse tier: {tier}", code="invalid_request")
+
+ emit = status_callback or (lambda _message: None)
+ emit(STATUS_PREPARING_REQUEST)
+ if self._capabilities is None:
+ emit(STATUS_CHECKING_SERVER)
+ await self.discover()
+ if self._capabilities is None or tier not in self._capabilities.tiers:
+ raise V1ArtifactError(f"Tier '{tier}' is not available in the configured V1 API server", code="tier_unavailable")
+
+ emit(STATUS_SUBMITTING_TASK)
+ parser = MinerUApiParser(
+ api_url=self.base_url,
+ api_key=self.api_key,
+ tier=cast(Tier, tier),
+ include_images=True,
+ include_model_output=True,
+ )
+ emit(STATUS_PROCESSING_ON_SERVER)
+ try:
+ result = await parser.parse_async(path, page_range=page_range)
+ except Exception as exc:
+ emit(f"Failed: {exc}")
+ if isinstance(exc, (FileNotFoundError, V1ArtifactError)):
+ raise
+ raise V1ArtifactError(str(exc), code=getattr(exc, "code", "parse_failed")) from exc
+ emit(STATUS_DOWNLOADING_RESULT)
+ return result
+
+ def _headers(self) -> dict[str, str]:
+ """生成 V1 请求鉴权头,不把 API Key 写入日志或持久化状态。"""
+ if not self.api_key:
+ return {}
+ return {"Authorization": f"Bearer {self.api_key}"}
+
+
+def _string_tuple(value: object, field_name: str) -> tuple[str, ...]:
+ """把能力字段严格收敛为字符串元组。"""
+ if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
+ raise V1ArtifactError(f"V1 health response field {field_name} is invalid", code="invalid_response")
+ return tuple(value)
+
+
+def _reserve_local_port() -> int:
+ """在 loopback 上申请一个临时 TCP 端口,供托管 API server 使用。"""
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind(("127.0.0.1", 0))
+ return int(sock.getsockname()[1])
+
+
+class ManagedLocalApiServer:
+ """管理 Gradio 自动启动的独立 V1 API server 子进程。"""
+
+ def __init__(
+ self,
+ *,
+ tier: ServerTier = "standard",
+ no_flash: bool = False,
+ concurrency: int = 1,
+ language: str = "ch",
+ ocr_mode: str = "auto",
+ disable_image_analysis: bool = False,
+ preload_models: bool = False,
+ api_key: str | None = None,
+ ) -> None:
+ """保存显式启动配置,但不在构造阶段创建目录或启动进程。"""
+ if tier not in SERVER_TIERS:
+ raise ValueError(f"Unsupported API server tier: {tier}")
+ if concurrency <= 0:
+ raise ValueError("API server concurrency must be positive")
+ self.tier = tier
+ self.no_flash = no_flash
+ self.concurrency = concurrency
+ self.language = language
+ self.ocr_mode = ocr_mode
+ self.disable_image_analysis = disable_image_analysis
+ self.preload_models = preload_models
+ self.api_key = api_key
+ self.base_url: str | None = None
+ self.process: subprocess.Popen[bytes] | None = None
+ self._control: ManagedProcessControl | None = None
+ self._temp_dir: tempfile.TemporaryDirectory[str] | None = None
+ self._atexit_registered = False
+
+ def start(self) -> str:
+ """启动 `mineru-kit api-server` 并等待 `/v1/health` 返回成功。"""
+ if self.process is not None and self.process.poll() is None:
+ raise RuntimeError("Managed V1 API server is already running")
+ if self.process is not None or self._temp_dir is not None or self._control is not None:
+ self.stop()
+ self._temp_dir = tempfile.TemporaryDirectory(prefix="mineru-kit-gradio-api-")
+ upload_dir = Path(self._temp_dir.name) / "uploads"
+ upload_dir.mkdir(parents=True, exist_ok=True)
+ port = _reserve_local_port()
+ self.base_url = f"http://127.0.0.1:{port}"
+
+ control = ManagedProcessControl.create()
+ control.start_accepting()
+ environment = utf8_subprocess_env()
+ environment.update(control.child_env())
+ command = self._command(port, upload_dir)
+ try:
+ self.process = subprocess.Popen(
+ command,
+ cwd=os.getcwd(),
+ env=environment,
+ stdin=subprocess.DEVNULL,
+ stdout=None,
+ stderr=None,
+ **_new_session_kwargs(),
+ )
+ except Exception:
+ control.close()
+ self._cleanup_temp_dir()
+ raise
+ self._control = control
+ if not self._atexit_registered:
+ atexit.register(self.stop)
+ self._atexit_registered = True
+ try:
+ self._wait_until_ready()
+ except Exception:
+ self.stop()
+ raise
+ return self.base_url
+
+ def stop(self) -> None:
+ """请求子进程优雅退出,并在超时后清理进程和临时目录。"""
+ process = self.process
+ control = self._control
+ self.process = None
+ self._control = None
+ try:
+ if process is not None and process.poll() is None:
+ if control is not None:
+ control.request_shutdown(3.0)
+ try:
+ process.wait(timeout=8.0)
+ except subprocess.TimeoutExpired:
+ process.terminate()
+ try:
+ process.wait(timeout=3.0)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ finally:
+ if control is not None:
+ control.close()
+ if self._atexit_registered:
+ try:
+ atexit.unregister(self.stop)
+ except Exception:
+ pass
+ self._atexit_registered = False
+ self.base_url = None
+ self._cleanup_temp_dir()
+
+ def __enter__(self) -> "ManagedLocalApiServer":
+ """进入上下文时启动本地 API server。"""
+ self.start()
+ return self
+
+ def __exit__(self, *_args: object) -> None:
+ """退出上下文时停止本地 API server。"""
+ self.stop()
+
+ def _command(self, port: int, upload_dir: Path) -> list[str]:
+ """构造不包含 Gradio 参数的正式 API server 子进程命令。"""
+ return [
+ sys.executable,
+ "-m",
+ "mineru.kit.main",
+ "api-server",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(port),
+ "--upload-dir",
+ str(upload_dir),
+ "--tier",
+ self.tier,
+ "--concurrency",
+ str(self.concurrency),
+ "--language",
+ self.language,
+ "--ocr-mode",
+ self.ocr_mode,
+ *(["--no-flash"] if self.no_flash else []),
+ *(["--disable-image-analysis"] if self.disable_image_analysis else []),
+ *(["--preload-models"] if self.preload_models else []),
+ *(["--api-key", self.api_key] if self.api_key else []),
+ ]
+
+ def _wait_until_ready(self) -> None:
+ """轮询本地 health,区分进程提前退出和服务未就绪。"""
+ if self.base_url is None:
+ raise RuntimeError("Managed V1 API server has no base URL")
+ timeout_seconds = _startup_timeout_seconds()
+ deadline = time.monotonic() + timeout_seconds
+ last_error = ""
+ with httpx.Client(timeout=httpx.Timeout(3, connect=1), trust_env=False) as client:
+ while time.monotonic() < deadline:
+ if self.process is not None and self.process.poll() is not None:
+ raise V1ArtifactError("Managed V1 API server exited before becoming ready", code="server_start_failed")
+ try:
+ response = client.get(f"{self.base_url}/v1/health")
+ if response.status_code < 400:
+ return
+ error_code, last_error = _error_detail(response)
+ if response.status_code < 500 or error_code.startswith("model_preload_"):
+ raise V1ArtifactError(last_error, code=error_code)
+ except httpx.HTTPError as exc:
+ last_error = str(exc)
+ time.sleep(0.1)
+ suffix = f": {last_error}" if last_error else ""
+ raise V1ArtifactError(f"Timed out waiting for managed V1 API server{suffix}", code="server_start_timeout")
+
+ def _cleanup_temp_dir(self) -> None:
+ """清理托管 server 的上传临时目录。"""
+ if self._temp_dir is None:
+ return
+ self._temp_dir.cleanup()
+ self._temp_dir = None
+
+
+def _startup_timeout_seconds() -> float:
+ """读取本地 API 启动超时环境变量,并对非法值使用安全默认值。"""
+ raw = os.environ.get("MINERU_LOCAL_API_STARTUP_TIMEOUT_SECONDS", "300")
+ try:
+ value = float(raw)
+ except (TypeError, ValueError):
+ return 300.0
+ return max(1.0, value)
+
+
+def _new_session_kwargs() -> dict[str, Any]:
+ """返回跨平台隔离托管子进程的 Popen 参数。"""
+ if os.name == "nt":
+ creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
+ return {"creationflags": creationflags} if creationflags else {}
+ return {"start_new_session": True}
+
+
+__all__ = [
+ "ManagedLocalApiServer",
+ "STATUS_CHECKING_SERVER",
+ "STATUS_COMPLETED",
+ "STATUS_DOWNLOADING_RESULT",
+ "STATUS_PREPARING_REQUEST",
+ "STATUS_PROCESSING_ON_SERVER",
+ "STATUS_PROCESSING_OUTPUT",
+ "STATUS_SUBMITTING_TASK",
+ "V1ArtifactClient",
+ "V1ArtifactError",
+ "V1ServerCapabilities",
+ "normalize_v1_base_url",
+]
diff --git a/mineru/kit/gradio/preview.py b/mineru/kit/gradio/preview.py
new file mode 100644
index 00000000..94079817
--- /dev/null
+++ b/mineru/kit/gradio/preview.py
@@ -0,0 +1,162 @@
+"""基于 schema 2.0 Middle JSON 的 Gradio 文档预览和布局标注。"""
+
+from __future__ import annotations
+
+from io import BytesIO
+from pathlib import Path
+from typing import Any, Iterable
+
+from pypdf import PageObject, PdfReader, PdfWriter
+from reportlab.pdfgen import canvas
+
+from ...types import BlockBase, BlockType, MiddleJson, PageInfo
+
+_VISUAL_PARENT_TYPES = {
+ BlockType.IMAGE,
+ BlockType.TABLE,
+ BlockType.CHART,
+ BlockType.CODE,
+}
+
+_BLOCK_COLORS: dict[str, tuple[float, float, float]] = {
+ "text": (0.60, 0.05, 0.30),
+ "ref_text": (0.45, 0.20, 0.65),
+ "doc_title": (0.20, 0.20, 0.80),
+ "paragraph_title": (0.20, 0.40, 0.90),
+ "equation": (0.00, 0.60, 0.10),
+ "list": (0.10, 0.60, 0.35),
+ "index": (0.10, 0.60, 0.35),
+ "image_body": (0.30, 0.85, 0.05),
+ "image_caption": (0.10, 0.55, 0.90),
+ "image_footnote": (0.95, 0.45, 0.10),
+ "table_body": (0.80, 0.80, 0.00),
+ "table_caption": (1.00, 0.85, 0.10),
+ "table_footnote": (0.55, 0.90, 0.25),
+ "chart_body": (0.30, 0.85, 0.05),
+ "chart_caption": (0.10, 0.55, 0.90),
+ "chart_footnote": (0.95, 0.45, 0.10),
+ "code_body": (0.40, 0.00, 0.80),
+ "algorithm_body": (0.40, 0.00, 0.80),
+ "code_caption": (0.70, 0.35, 0.95),
+ "code_footnote": (0.85, 0.70, 0.95),
+}
+
+
+def draw_layout_overlay(
+ middle_json: MiddleJson,
+ origin_pdf_path: Path,
+ output_path: Path,
+ *,
+ page_indices: tuple[int, ...] = (),
+) -> None:
+ """将当前 Middle JSON 的语义 bbox 绘制到 origin PDF,生成布局预览。"""
+ if not isinstance(middle_json, MiddleJson):
+ raise TypeError("middle_json must be a MiddleJson instance")
+ if not origin_pdf_path.is_file():
+ raise FileNotFoundError(origin_pdf_path)
+
+ reader = PdfReader(str(origin_pdf_path))
+ writer = PdfWriter()
+ pages_by_original_idx = {page.page_idx: page for page in middle_json.pages}
+ for output_index, source_page in enumerate(reader.pages):
+ middle_page = _page_for_output_index(
+ output_index,
+ pages_by_original_idx,
+ middle_json.pages,
+ page_indices,
+ )
+ overlay = _build_page_overlay(source_page, middle_page)
+ if overlay is not None:
+ page_copy = PageObject.create_blank_page(
+ None,
+ width=float(source_page.cropbox.width),
+ height=float(source_page.cropbox.height),
+ )
+ page_copy.merge_page(source_page)
+ page_copy.merge_page(overlay)
+ writer.add_page(page_copy)
+ else:
+ writer.add_page(source_page)
+
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with output_path.open("wb") as output_file:
+ writer.write(output_file)
+
+
+def _page_for_output_index(
+ output_index: int,
+ pages_by_original_idx: dict[int, PageInfo],
+ pages: list[PageInfo],
+ page_indices: tuple[int, ...],
+) -> PageInfo | None:
+ """按裁页映射优先、页面顺序回退选择 overlay 对应的 Middle 页面。"""
+ if page_indices and output_index < len(page_indices):
+ mapped = pages_by_original_idx.get(page_indices[output_index])
+ if mapped is not None:
+ return mapped
+ if output_index < len(pages):
+ return pages[output_index]
+ return None
+
+
+def _build_page_overlay(page: Any, middle_page: PageInfo | None) -> PageObject | None:
+ """为单个 PDF 页面生成透明 bbox overlay 页面。"""
+ if middle_page is None:
+ return None
+ width = float(page.cropbox.width)
+ height = float(page.cropbox.height)
+ if width <= 0 or height <= 0:
+ return None
+ boxes = list(_iter_overlay_boxes(middle_page.blocks))
+ if not boxes:
+ return None
+
+ packet = BytesIO()
+ painter = canvas.Canvas(packet, pagesize=(width, height))
+ painter.setLineWidth(1.0)
+ for block_type, bbox in boxes:
+ x0, y0, x1, y1 = _normalized_bbox_to_pdf(bbox, width, height)
+ color = _BLOCK_COLORS.get(block_type, (0.90, 0.10, 0.10))
+ painter.setStrokeColorRGB(*color)
+ painter.rect(x0, y0, max(0.5, x1 - x0), max(0.5, y1 - y0), stroke=1, fill=0)
+ painter.save()
+ packet.seek(0)
+ return PdfReader(packet).pages[0]
+
+
+def _iter_overlay_boxes(blocks: Iterable[BlockBase]) -> Iterable[tuple[str, tuple[float, float, float, float]]]:
+ """遍历当前 block 树并为视觉父块选择子块 bbox,避免重复绘制。"""
+ for block in blocks:
+ block_type = _block_type_value(block)
+ if block.bbox is not None and block.type not in _VISUAL_PARENT_TYPES:
+ yield block_type, tuple(float(item) for item in block.bbox)
+ content = getattr(block, "content", None)
+ children = [child for child in content if isinstance(child, BlockBase)] if isinstance(content, list) else []
+ if block.type in _VISUAL_PARENT_TYPES and children:
+ for child in children:
+ if child.bbox is not None:
+ yield _block_type_value(child), tuple(float(item) for item in child.bbox)
+ elif children:
+ yield from _iter_overlay_boxes(children)
+
+
+def _normalized_bbox_to_pdf(
+ bbox: tuple[float, float, float, float],
+ width: float,
+ height: float,
+) -> tuple[float, float, float, float]:
+ """把左上原点的归一化 bbox 转换为 PDF 左下原点坐标。"""
+ x0 = min(max(bbox[0], 0.0), 1.0) * width
+ x1 = min(max(bbox[2], 0.0), 1.0) * width
+ top = min(max(bbox[1], 0.0), 1.0) * height
+ bottom = min(max(bbox[3], 0.0), 1.0) * height
+ return x0, height - bottom, x1, height - top
+
+
+def _block_type_value(block: BlockBase) -> str:
+ """统一读取 Enum 或字符串 block 类型值。"""
+ value = getattr(block.type, "value", block.type)
+ return str(value)
+
+
+__all__ = ["draw_layout_overlay"]
diff --git a/mineru/kit/main.py b/mineru/kit/main.py
index 475f28bf..1779f2ed 100644
--- a/mineru/kit/main.py
+++ b/mineru/kit/main.py
@@ -8,10 +8,11 @@ from typer.core import TyperGroup
from ..cli.version_command import show_version, version_cmd
from ..utils.stdio import configure_standard_streams
-from .commands import api_server, models, parse, router, vlm_server
+from .commands import api_server, gradio, models, parse, router, vlm_server
TOP_LEVEL_COMMAND_ORDER = [
"parse",
+ "gradio",
"api-server",
"vlm-server",
"router",
@@ -19,11 +20,6 @@ TOP_LEVEL_COMMAND_ORDER = [
"version",
]
-FORWARD_CONTEXT_SETTINGS = {
- "ignore_unknown_options": True,
- "allow_extra_args": True,
-}
-
class OrderedRootGroup(TyperGroup):
def list_commands(self, ctx: Context) -> list[str]:
@@ -55,8 +51,9 @@ def root(
app.add_typer(models.app, name="models")
app.command("parse")(parse.parse_cmd)
+app.command("gradio")(gradio.gradio_cmd)
app.command("api-server")(api_server.api_server_cmd)
-app.command("vlm-server", context_settings=FORWARD_CONTEXT_SETTINGS)(vlm_server.vlm_server_cmd)
+app.command("vlm-server", context_settings=vlm_server.FORWARD_CONTEXT_SETTINGS)(vlm_server.vlm_server_cmd)
app.command("router")(router.router_cmd)
app.command("version")(version_cmd)
diff --git a/mineru/kit/router/app.py b/mineru/kit/router/app.py
index 55020fe4..40d15e12 100644
--- a/mineru/kit/router/app.py
+++ b/mineru/kit/router/app.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""独立于 cli_old 的 MinerU V1 Router FastAPI 实现。"""
+"""MinerU V1 Router 的独立 FastAPI 实现。"""
from __future__ import annotations
diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.py
index 04d298af..7e5fd013 100644
--- a/mineru/parser/api_client.py
+++ b/mineru/parser/api_client.py
@@ -282,13 +282,19 @@ class MinerUApiParser(DocumentParser):
upload_headers = resp.get("upload_headers", {})
if upload_url.startswith("/"):
upload_url = f"{self._base_url}{upload_url}"
+ request_headers = _same_origin_upload_headers(
+ self._base_url,
+ upload_url,
+ upload_headers,
+ self._headers(),
+ )
with file_path.open("rb") as fh:
r2 = _request_with_retry(
cli,
"PUT",
upload_url,
stage="upload content",
- headers=upload_headers,
+ headers=request_headers,
content=fh.read(),
)
self._check(r2)
@@ -323,13 +329,19 @@ class MinerUApiParser(DocumentParser):
upload_headers = resp.get("upload_headers", {})
if upload_url.startswith("/"):
upload_url = f"{self._base_url}{upload_url}"
+ request_headers = _same_origin_upload_headers(
+ self._base_url,
+ upload_url,
+ upload_headers,
+ self._headers(),
+ )
data = file_path.read_bytes()
r2 = await _async_request_with_retry(
cli,
"PUT",
upload_url,
stage="upload content",
- headers=upload_headers,
+ headers=request_headers,
content=data,
)
self._check(r2)
@@ -984,6 +996,36 @@ async def _async_download_bytes(parser: MinerUApiParser, ref: dict[str, Any]) ->
return r.content
+def _same_origin_upload_headers(
+ base_url: str,
+ upload_url: str,
+ upload_headers: object,
+ auth_headers: dict[str, str],
+) -> dict[str, str]:
+ """仅为 API 同源上传合并鉴权头,避免向外部预签名地址泄露密钥。"""
+ if not isinstance(upload_headers, dict) or any(
+ not isinstance(key, str) or not isinstance(value, str) for key, value in upload_headers.items()
+ ):
+ raise _V1APIError("invalid_response", "upload_headers must be a string mapping")
+ headers = dict(upload_headers)
+ if _http_origin(base_url) == _http_origin(upload_url):
+ headers.update(auth_headers)
+ return headers
+
+
+def _http_origin(url: str) -> tuple[str, str, int | None]:
+ """将 HTTP URL 规范为 scheme、host、effective-port 三元组。"""
+ parsed = urlparse(url)
+ try:
+ port = parsed.port
+ except ValueError as exc:
+ raise _V1APIError("invalid_response", f"Invalid upload URL: {url}") from exc
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
+ raise _V1APIError("invalid_response", f"Invalid upload URL: {url}")
+ effective_port = port if port is not None else (443 if parsed.scheme == "https" else 80)
+ return parsed.scheme.lower(), parsed.hostname.lower(), effective_port
+
+
def should_trust_env_for_url(url: str) -> bool:
return not _is_local_network_url(url)
diff --git a/pyproject.toml b/pyproject.toml
index 3cd48d2b..8638a18b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -137,7 +137,10 @@ License = "https://github.com/opendatalab/MinerU/blob/master/LICENSE.md"
mineru = "mineru.cli.main:main"
mineru-kit = "mineru.kit.main:main"
mineru-router = "mineru.kit.router.cli:main"
-mineru-gradio = "mineru.cli_old.gradio_app:main"
+mineru-gradio = "mineru.kit.commands.gradio:main"
+mineru-openai-server = "mineru.kit.commands.vlm_server:main"
+mineru-models-download = "mineru.kit.commands.models:download_main"
+mineru-api = "mineru.kit.commands.api_server:main"
[tool.setuptools.dynamic]
version = { attr = "mineru.version.__version__" }
diff --git a/tests/unittest/test_backend_architecture.py b/tests/unittest/test_backend_architecture.py
index 0b5ac169..e9a92b2a 100644
--- a/tests/unittest/test_backend_architecture.py
+++ b/tests/unittest/test_backend_architecture.py
@@ -53,6 +53,7 @@ _CHINESE_DOCSTRING_PATHS = (
_PROJECT_ROOT / "mineru/utils/image.py",
)
_REMOVED_INTERNAL_MODULES = (
+ "mineru.cli_old",
"mineru.backend.local_model_runtime",
"mineru.model.model_types",
"mineru.model.flash.model",
@@ -163,8 +164,6 @@ def test_active_mineru_imports_use_relative_form() -> None:
"""守卫活动生产代码的 MinerU 内部引用统一使用相对 import。"""
offenders: list[str] = []
for path in (_PROJECT_ROOT / "mineru").rglob("*.py"):
- if "cli_old" in path.parts:
- continue
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if (
@@ -311,8 +310,6 @@ def test_removed_private_module_paths_have_no_active_references() -> None:
"""守卫严格迁移后的活动生产代码不再引用旧私有路径。"""
offenders: list[str] = []
for path in (_PROJECT_ROOT / "mineru").rglob("*.py"):
- if "cli_old" in path.parts:
- continue
text = path.read_text(encoding="utf-8")
for module_name in _REMOVED_INTERNAL_MODULES:
if module_name in text:
@@ -320,14 +317,9 @@ def test_removed_private_module_paths_have_no_active_references() -> None:
assert not offenders
-def test_mineru_kit_does_not_depend_on_cli_old() -> None:
- """守卫正式 mineru-kit 命令与服务实现不再依赖待删除的 cli_old。"""
- offenders: dict[str, list[str]] = {}
- for path in (_PROJECT_ROOT / "mineru/kit").rglob("*.py"):
- invalid = sorted(module for module in _resolved_imports(path) if module.startswith("mineru.cli_old"))
- if invalid:
- offenders[str(path.relative_to(_PROJECT_ROOT))] = invalid
- assert not offenders
+def test_legacy_cli_package_is_removed() -> None:
+ """守卫旧 CLI 源码目录不会重新进入发布包。"""
+ assert not (_PROJECT_ROOT / "mineru/cli_old").exists()
def test_removed_private_module_paths_are_not_importable() -> None:
diff --git a/tests/unittest/test_client_side_output.py b/tests/unittest/test_client_side_output.py
deleted file mode 100644
index f0867191..00000000
--- a/tests/unittest/test_client_side_output.py
+++ /dev/null
@@ -1,127 +0,0 @@
-from __future__ import annotations
-
-import importlib.util
-import json
-import sys
-from pathlib import Path
-from types import ModuleType
-from typing import Any
-
-import pytest
-
-from mineru.types import PageInfo
-
-_PROJECT_ROOT = Path(__file__).resolve().parents[2]
-_CLIENT_SIDE_OUTPUT_PATH = _PROJECT_ROOT / "mineru/cli_old/client_side_output.py"
-
-
-class _FakeParseResult:
- """为旧客户端输出测试提供最小 ParseResult 行为。"""
-
- def __init__(
- self,
- pages: list[PageInfo],
- _retained_page_indices: list[int] | None = None,
- _broken_page_indices: list[int] | None = None,
- ) -> None:
- """保存页面和旧客户端会回写的页号元数据。"""
- self.pages = pages
- self._retained_page_indices = _retained_page_indices or []
- self._broken_page_indices = _broken_page_indices or []
-
- @classmethod
- def from_dict(cls, _payload: dict[str, Any]) -> "_FakeParseResult":
- """从测试 middle json 返回一个空页面结果。"""
- return cls([PageInfo(page_idx=0)])
-
- def to_dict(self) -> dict[str, Any]:
- """返回旧客户端写文件所需的最小字典。"""
- return {"pages": [page.model_dump(mode="json") for page in self.pages]}
-
-
-def _load_client_side_output(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
- """隔离旧 parser/render 基线导入,加载本次迁移的客户端输出模块。"""
- parser_package = ModuleType("mineru.parser")
- parser_package.__path__ = [] # type: ignore[attr-defined]
- parser_base = ModuleType("mineru.parser.base")
- parser_base.ParseResult = _FakeParseResult # type: ignore[attr-defined]
- render_module = ModuleType("mineru.render")
- render_module.render_content_list = lambda *_args, **_kwargs: [] # type: ignore[attr-defined]
- render_module.render_markdown = lambda *_args, **_kwargs: "" # type: ignore[attr-defined]
- render_module.render_structured_content = lambda *_args, **_kwargs: {} # type: ignore[attr-defined]
- monkeypatch.setitem(sys.modules, "mineru.parser", parser_package)
- monkeypatch.setitem(sys.modules, "mineru.parser.base", parser_base)
- monkeypatch.setitem(sys.modules, "mineru.render", render_module)
-
- spec = importlib.util.spec_from_file_location("_client_side_output_under_test", _CLIENT_SIDE_OUTPUT_PATH)
- if spec is None or spec.loader is None:
- raise RuntimeError("Unable to load client_side_output.py")
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
-
-
-def _install_fake_finalize_module(monkeypatch: pytest.MonkeyPatch, calls: list[str]) -> None:
- """安装旧客户端动态 import 所需的最小 backend.pdf finalize 模块。"""
- pdf_package = ModuleType("mineru.backend.pdf")
- pdf_package.__path__ = [] # type: ignore[attr-defined]
- finalize_module = ModuleType("mineru.backend.pdf.model_output_to_middle_json")
-
- def finalize_middle_json_from_preproc(_pages: list[PageInfo], effort: str = "medium") -> None:
- """记录旧客户端向动态 finalize 入口转发的 effort。"""
- calls.append(effort)
-
- finalize_module.finalize_middle_json_from_preproc = finalize_middle_json_from_preproc # type: ignore[attr-defined]
- monkeypatch.setitem(sys.modules, "mineru.backend.pdf", pdf_package)
- monkeypatch.setitem(sys.modules, "mineru.backend.pdf.model_output_to_middle_json", finalize_module)
-
-
-def test_finalize_client_side_pages_passes_hybrid_effort(monkeypatch: pytest.MonkeyPatch) -> None:
- """校验迁移后的客户端 Hybrid finalize 继续转发 effort。"""
- module = _load_client_side_output(monkeypatch)
- calls: list[str] = []
- _install_fake_finalize_module(monkeypatch, calls)
-
- module._finalize_client_side_pages([PageInfo(page_idx=0)], "hybrid", effort="high")
-
- assert calls == ["high"]
-
-
-def test_finalize_client_side_pages_rejects_low_effort(monkeypatch: pytest.MonkeyPatch) -> None:
- """校验迁移后的客户端 Hybrid finalize 仍拒绝 low effort。"""
- module = _load_client_side_output(monkeypatch)
- calls: list[str] = []
- _install_fake_finalize_module(monkeypatch, calls)
-
- with pytest.raises(ValueError, match="Unsupported effort 'low'"):
- module._finalize_client_side_pages([PageInfo(page_idx=0)], "hybrid", effort="low")
-
- assert calls == []
-
-
-def test_regenerate_client_side_outputs_forwards_hybrid_effort(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- """校验客户端重建输出时继续把 Hybrid effort 传给迁移后的私有 helper。"""
- module = _load_client_side_output(monkeypatch)
- middle_json_path = tmp_path / "demo_middle.json"
- middle_json_path.write_text(json.dumps({"pages": []}), encoding="utf-8")
- calls: list[tuple[str, str]] = []
- monkeypatch.setattr(
- module,
- "_finalize_client_side_pages",
- lambda _pages, backend, effort="medium": calls.append((backend, effort)),
- )
-
- module.regenerate_client_side_outputs(tmp_path, "demo", "hybrid-engine", effort="high")
-
- assert calls == [("hybrid", "high")]
-
-
-def test_finalize_client_side_pages_uses_explicit_backend(monkeypatch: pytest.MonkeyPatch) -> None:
- """校验迁移后的私有 helper 继续拒绝旧 pipeline backend。"""
- module = _load_client_side_output(monkeypatch)
-
- with pytest.raises(ValueError, match="Unsupported client-side finalize backend 'pipeline'"):
- module._finalize_client_side_pages([PageInfo(page_idx=0)], "pipeline")
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index 378a5940..0b38e94d 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -1,19 +1,16 @@
from __future__ import annotations
-import ast
import asyncio
import json
-import os
-import subprocess
import sys
-import zipfile
-from io import BytesIO
+import tomllib
+from collections.abc import Callable
from pathlib import Path
from types import ModuleType, SimpleNamespace
from typing import Any
-import click
import pytest
+import typer
from fastapi.testclient import TestClient
from typer.main import get_command
from typer.testing import CliRunner
@@ -21,11 +18,10 @@ from typer.testing import CliRunner
import mineru.kit.main as kit_main
from mineru.cli.main import app as mineru_app
from mineru.cli.version_command import version_cmd
-from mineru.kit.commands import api_server, models, parse, router, vlm_server
+from mineru.kit.commands import api_server, gradio, models, parse, router, vlm_server
from mineru.kit.main import app
from mineru.kit.vlm_server import mlx_vlm_server
from mineru.parser.base import ParseResult
-from mineru.types import MiddleJson, PageInfo
from mineru.model.registry import MODEL_COMPLETE_MARKER
from mineru.version import __version__
@@ -33,9 +29,6 @@ runner = CliRunner()
_REMOVED_DISABLE_TABLE_OPTION = "--disable-" + "table"
_REMOVED_DISABLE_FORMULA_OPTION = "--disable-" + "formula"
-_REMOVED_TABLE_ENABLE_PARAM = "table" + "_enable"
-_REMOVED_FORMULA_ENABLE_PARAM = "formula" + "_enable"
-_REMOVED_INLINE_FORMULA_PARAM = "inline_" + _REMOVED_FORMULA_ENABLE_PARAM
def test_kit_main_configures_standard_streams_before_running_app(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -48,6 +41,251 @@ def test_kit_main_configures_standard_streams_before_running_app(monkeypatch: py
assert calls == ["configure", "app"]
+def test_gradio_compatibility_main_runs_modern_command(monkeypatch: pytest.MonkeyPatch) -> None:
+ """校验独立兼容入口复用新版 Gradio 命令且先配置标准流。"""
+ calls: list[object] = []
+ monkeypatch.setattr(gradio, "configure_standard_streams", lambda: calls.append("configure"))
+ monkeypatch.setattr(gradio.typer, "run", lambda command: calls.append(command))
+
+ gradio.main()
+
+ assert calls == ["configure", gradio.gradio_cmd]
+
+
+def test_gradio_console_script_targets_modern_command() -> None:
+ """校验兼容命令不再通过已删除的旧 CLI 包启动。"""
+ project = tomllib.loads((Path(__file__).resolve().parents[2] / "pyproject.toml").read_text(encoding="utf-8"))
+
+ assert project["project"]["scripts"]["mineru-gradio"] == "mineru.kit.commands.gradio:main"
+
+
+def _invoke_standalone_command(
+ monkeypatch: pytest.MonkeyPatch,
+ entrypoint: Callable[[], None],
+ script: str,
+ args: list[str],
+) -> int:
+ """通过真实入口解析命令行参数,并在调用后恢复进程参数。"""
+ with monkeypatch.context() as context:
+ context.setattr(sys, "argv", [script, *args])
+ with pytest.raises(SystemExit) as exc_info:
+ entrypoint()
+ assert isinstance(exc_info.value.code, int)
+ return exc_info.value.code
+
+
+ ("script", "target"),
+ [
+ ("mineru-openai-server", "mineru.kit.commands.vlm_server:main"),
+ ("mineru-models-download", "mineru.kit.commands.models:download_main"),
+ ("mineru-api", "mineru.kit.commands.api_server:main"),
+ ],
+)
+def test_standalone_console_scripts_target_kit_commands(script: str, target: str) -> None:
+ """校验三个独立命令都映射到新版 kit 实现。"""
+ project = tomllib.loads((Path(__file__).resolve().parents[2] / "pyproject.toml").read_text(encoding="utf-8"))
+
+ assert project["project"]["scripts"][script] == target
+
+
+ ("module", "entrypoint", "callback"),
+ [(api_server, api_server.main, api_server.api_server_cmd), (models, models.download_main, models.download_cmd)],
+)
+def test_standalone_main_configures_streams_before_typer_run(
+ monkeypatch: pytest.MonkeyPatch,
+ module: ModuleType,
+ entrypoint: Callable[[], None],
+ callback: Callable[..., None],
+) -> None:
+ """校验 API 和下载入口先配置标准流,再直接复用现有回调。"""
+ calls: list[object] = []
+ monkeypatch.setattr(module, "configure_standard_streams", lambda: calls.append("configure"))
+ monkeypatch.setattr(typer, "run", lambda command: calls.append(command))
+
+ entrypoint()
+
+ assert calls == ["configure", callback]
+
+
+def test_standalone_vlm_main_configures_streams_and_forwards_extra_args(monkeypatch: pytest.MonkeyPatch) -> None:
+ """校验 VLM 独立入口的标准流初始化顺序及共享参数透传配置。"""
+ calls: list[object] = []
+
+ def _record_command(ctx: typer.Context) -> None:
+ """记录单命令应用收到的额外参数。"""
+ calls.append(list(ctx.args))
+
+ monkeypatch.setattr(vlm_server, "configure_standard_streams", lambda: calls.append("configure"))
+ monkeypatch.setattr(vlm_server, "vlm_server_cmd", _record_command)
+ code = _invoke_standalone_command(monkeypatch, vlm_server.main, "mineru-openai-server", ["--port", "30000"])
+ kit_command = next(command for command in app.registered_commands if command.name == "vlm-server")
+
+ assert code == 0
+ assert calls == ["configure", ["--port", "30000"]]
+ assert kit_command.context_settings is vlm_server.FORWARD_CONTEXT_SETTINGS
+
+
+ ("script", "entrypoint", "expected_options"),
+ [
+ ("mineru-openai-server", vlm_server.main, ("--engine",)),
+ ("mineru-models-download", models.download_main, ("--tier", "--stack", "--source", "--verbose")),
+ ("mineru-api", api_server.main, ("--host", "--port", "--tier", "--no-flash", "--preload-models")),
+ ],
+)
+def test_standalone_command_help(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ script: str,
+ entrypoint: Callable[[], None],
+ expected_options: tuple[str, ...],
+) -> None:
+ """校验独立命令直接展示新版参数,且不暴露补全或额外子命令。"""
+ code = _invoke_standalone_command(monkeypatch, entrypoint, script, ["--help"])
+ output = capsys.readouterr().out
+
+ assert code == 0
+ assert script in output
+ for option in expected_options:
+ assert option in output
+ assert "--install-completion" not in output
+ assert "--show-completion" not in output
+ assert "COMMAND [ARGS]" not in output
+
+
[email protected]("exit_code", [0, 7])
+ "args",
+ [[], ["--host", "0.0.0.0", "--port", "18000", "--tier", "basic", "--no-flash", "--preload-models"]],
+)
+def test_standalone_api_matches_kit_arguments_and_exit_code(
+ monkeypatch: pytest.MonkeyPatch, args: list[str], exit_code: int
+) -> None:
+ """校验独立 API 入口与 kit 的默认值、参数转发和退出码一致。"""
+ calls: list[tuple[list[str], str, bool]] = []
+
+ def _fake_main(*, args: list[str], prog_name: str, standalone_mode: bool) -> None:
+ """记录启动参数并模拟底层服务退出,不启动真实服务器。"""
+ calls.append((args, prog_name, standalone_mode))
+ raise SystemExit(exit_code)
+
+ monkeypatch.setattr(api_server.parser_api_server.main, "main", _fake_main)
+ code = _invoke_standalone_command(monkeypatch, api_server.main, "mineru-api", args)
+ kit_result = runner.invoke(app, ["api-server", *args])
+
+ assert code == kit_result.exit_code == exit_code
+ assert len(calls) == 2
+ assert calls[0] == calls[1]
+
+
[email protected]("fails", [False, True])
+ "args",
+ [
+ ["PDF-Extract-Kit-1.0", "--source", "modelscope", "--verbose"],
+ ["--tier", "standard", "--stack", "full", "--source", "huggingface"],
+ ],
+)
+def test_standalone_models_download_matches_kit(monkeypatch: pytest.MonkeyPatch, args: list[str], fails: bool) -> None:
+ """校验下载入口无需子命令,并沿用模型选择、下载参数及失败退出码。"""
+ calls: list[tuple[str, str | None, bool]] = []
+
+ def _fake_download(repo: models.ModelRepo, *, source: str | None = None, local_as_auto: bool = False) -> Path:
+ """记录下载请求或模拟失败,避免网络下载和配置写入。"""
+ calls.append((repo.name, source, local_as_auto))
+ if fails:
+ raise RuntimeError("download unavailable")
+ return Path("/tmp/models") / repo.local_name
+
+ monkeypatch.setattr(models, "download_model_repo", _fake_download)
+ code = _invoke_standalone_command(monkeypatch, models.download_main, "mineru-models-download", args)
+ standalone_calls = calls[:]
+ calls.clear()
+ kit_result = runner.invoke(app, ["models", "download", *args])
+
+ assert code == kit_result.exit_code == int(fails)
+ assert standalone_calls == calls
+ assert calls
+
+
[email protected]("engine", ["vllm", "lmdeploy"])
[email protected]("exit_code", [0, 7])
+def test_standalone_vlm_matches_kit_arguments_and_exit_code(
+ monkeypatch: pytest.MonkeyPatch, engine: str, exit_code: int
+) -> None:
+ """校验两种 argv 引擎的参数透传、退出码和进程参数恢复行为。"""
+ calls: list[list[str]] = []
+
+ def _fake_main() -> None:
+ """记录引擎收到的原始参数并模拟退出,不加载真实推理引擎。"""
+ calls.append(sys.argv[1:])
+ raise SystemExit(exit_code)
+
+ module_name = f"mineru.kit.vlm_server.{engine}_server"
+ fake_server = ModuleType(module_name)
+ fake_server.main = _fake_main
+ monkeypatch.setitem(sys.modules, module_name, fake_server)
+ monkeypatch.setattr(vlm_server, "_module_available", lambda module_name: module_name == engine)
+ extra_args = ["--host", "127.0.0.1", "--port", "30000", "--model=test-model", "--trust-remote-code"]
+ args = ["--engine", engine, *extra_args]
+ original_argv = ["mineru-openai-server", *args]
+ monkeypatch.setattr(sys, "argv", original_argv)
+
+ with pytest.raises(SystemExit) as exc_info:
+ vlm_server.main()
+ assert sys.argv is original_argv
+ kit_result = runner.invoke(app, ["vlm-server", *args])
+
+ assert exc_info.value.code == kit_result.exit_code == exit_code
+ assert calls == [extra_args, extra_args]
+ assert sys.argv is original_argv
+
+
+def test_standalone_vlm_mlx_matches_kit(monkeypatch: pytest.MonkeyPatch) -> None:
+ """校验 MLX 的显式参数调用同样复用新版 kit 路径。"""
+ calls: list[tuple[list[str], str, bool]] = []
+
+ def _fake_main(*, args: list[str], prog_name: str, standalone_mode: bool) -> None:
+ """记录 MLX 启动参数,不加载 MLX 模型或启动服务。"""
+ calls.append((args, prog_name, standalone_mode))
+
+ monkeypatch.setattr(vlm_server, "_mlx_server_available", lambda: True)
+ monkeypatch.setattr(mlx_vlm_server, "main", _fake_main)
+ args = ["--engine", "mlx", "--model", "test-model", "--port", "18080"]
+ code = _invoke_standalone_command(monkeypatch, vlm_server.main, "mineru-openai-server", args)
+ kit_result = runner.invoke(app, ["vlm-server", *args])
+
+ assert code == kit_result.exit_code == 0
+ assert calls == [(args[2:], "mineru-kit vlm-server", False)] * 2
+
+
+ ("script", "entrypoint", "args", "prefix", "exit_code"),
+ [
+ ("mineru-api", api_server.main, ["--backend", "hybrid-engine"], ["api-server"], 2),
+ ("mineru-api", api_server.main, ["--tier", "advanced"], ["api-server"], 1),
+ ("mineru-models-download", models.download_main, [], ["models", "download"], 1),
+ ("mineru-models-download", models.download_main, ["--tier", "flash"], ["models", "download"], 1),
+ ("mineru-openai-server", vlm_server.main, ["--engine", "sglang"], ["vlm-server"], 1),
+ ],
+)
+def test_standalone_invalid_arguments_match_kit(
+ monkeypatch: pytest.MonkeyPatch,
+ script: str,
+ entrypoint: Callable[[], None],
+ args: list[str],
+ prefix: list[str],
+ exit_code: int,
+) -> None:
+ """校验独立入口沿用新版参数校验,不恢复旧参数或默认下载行为。"""
+ code = _invoke_standalone_command(monkeypatch, entrypoint, script, args)
+ kit_result = runner.invoke(app, [*prefix, *args])
+
+ assert code == kit_result.exit_code == exit_code
+
+
def _fake_apply_chat_template(_processor: Any, _config: Any, _prompt: Any, *_args: Any, **_kwargs: Any) -> str:
return "formatted"
@@ -69,6 +307,7 @@ def test_top_level_commands_register_implementation_callbacks_directly() -> None
callbacks = {command.name: command.callback for command in app.registered_commands}
assert callbacks["parse"] is parse.parse_cmd
+ assert callbacks["gradio"] is gradio.gradio_cmd
assert callbacks["api-server"] is api_server.api_server_cmd
assert callbacks["vlm-server"] is vlm_server.vlm_server_cmd
assert callbacks["router"] is router.router_cmd
@@ -79,6 +318,7 @@ def test_top_level_commands_register_implementation_callbacks_directly() -> None
("command", "expected_options"),
[
("parse", ("--output", "--format", "--tier")),
+ ("gradio", ("--api-url", "--server-name", "--api-server-tier")),
("api-server", ("--host", "--port", "--tier", "--no-flash", "--preload-models")),
("vlm-server", ("--engine",)),
("router", ("--host", "--upstream-url", "--local-gpus")),
@@ -107,6 +347,7 @@ def test_kit_root_commands_keep_product_order() -> None:
assert command.list_commands(None) == [
"parse",
+ "gradio",
"api-server",
"vlm-server",
"router",
@@ -155,105 +396,6 @@ def test_kit_root_show_completion_is_not_a_supported_option() -> None:
assert "No such option" in result.output
-def test_kit_main_import_does_not_import_legacy_router() -> None:
- repo_root = Path(__file__).resolve().parents[2]
- code = """
-import importlib.abc
-import sys
-
-
-class BlockLegacyRouterFinder(importlib.abc.MetaPathFinder):
- def find_spec(self, fullname, path=None, target=None):
- if fullname == "mineru.cli_old.router":
- raise ModuleNotFoundError("blocked legacy router import")
- return None
-
-
-sys.meta_path.insert(0, BlockLegacyRouterFinder())
-import mineru.kit.main
-print("ok")
-"""
-
- result = subprocess.run(
- [sys.executable, "-c", code],
- cwd=repo_root,
- capture_output=True,
- text=True,
- check=False,
- )
-
- assert result.returncode == 0, result.stderr
- assert result.stdout.strip() == "ok"
-
-
-def test_kit_vlm_server_import_does_not_import_legacy_vlm_server() -> None:
- repo_root = Path(__file__).resolve().parents[2]
- code = """
-import importlib.abc
-import sys
-
-
-class BlockLegacyVlmServerFinder(importlib.abc.MetaPathFinder):
- def find_spec(self, fullname, path=None, target=None):
- if fullname == "mineru.cli_old.vlm_server":
- raise ModuleNotFoundError("blocked legacy vlm server import")
- return None
-
-
-sys.meta_path.insert(0, BlockLegacyVlmServerFinder())
-import mineru.kit.commands.vlm_server
-print("ok")
-"""
-
- result = subprocess.run(
- [sys.executable, "-c", code],
- cwd=repo_root,
- capture_output=True,
- text=True,
- check=False,
- )
-
- assert result.returncode == 0, result.stderr
- assert result.stdout.strip() == "ok"
-
-
-def test_v1_router_import_does_not_load_cli_old() -> None:
- """校验正式 Router 与 mineru-kit 入口完全不依赖 cli_old。"""
- repo_root = Path(__file__).resolve().parents[2]
- code = """
-import importlib.abc
-import sys
-
-
-class BlockCliOldFinder(importlib.abc.MetaPathFinder):
- def find_spec(self, fullname, path=None, target=None):
- # 阻断整个旧 CLI 包,验证新 Router 的静态依赖边界。
- if fullname == "mineru.cli_old" or fullname.startswith("mineru.cli_old."):
- raise ModuleNotFoundError(f"blocked cli_old import: {fullname}")
- return None
-
-
-sys.meta_path.insert(0, BlockCliOldFinder())
-
-import mineru.kit.main
-from mineru.kit.router import RouterSettings, create_app
-
-create_app(RouterSettings(local_gpus="none"))
-print("ok")
-"""
-
- result = subprocess.run(
- [sys.executable, "-c", code],
- cwd=repo_root,
- capture_output=True,
- text=True,
- check=False,
- )
-
- assert result.returncode == 0, result.stderr
- assert result.stdout.strip() == "ok"
-
-
def test_router_upstream_only_worker_pool_builds_remote_server() -> None:
"""校验新 WorkerPool 从 V1 upstream 发现能力且不创建本地 worker。"""
import httpx
@@ -302,36 +444,6 @@ def test_router_startup_with_no_servers_fails_health_check() -> None:
assert response.json()["error"]["code"] == "upstream_unavailable"
-def test_upload_filename_helper_import_boundary_is_explicit() -> None:
- """校验上传文件名 helper 只由需要的入口直接导入,避免 common.py 继续承担兼容转发。"""
- repo_root = Path(__file__).resolve().parents[2]
- common_tree = ast.parse((repo_root / "mineru/cli_old/common.py").read_text(encoding="utf-8"))
- fast_api_tree = ast.parse((repo_root / "mineru/cli_old/fast_api.py").read_text(encoding="utf-8"))
-
- common_imports = {
- alias.name
- for node in ast.walk(common_tree)
- if isinstance(node, ast.ImportFrom) and node.module == "upload_utils"
- for alias in node.names
- }
- fast_api_common_imports = {
- alias.name
- for node in ast.walk(fast_api_tree)
- if isinstance(node, ast.ImportFrom) and node.module == "mineru.cli_old.common"
- for alias in node.names
- }
- fast_api_upload_imports = {
- alias.name
- for node in ast.walk(fast_api_tree)
- if isinstance(node, ast.ImportFrom) and node.module == "mineru.cli_old.upload_utils"
- for alias in node.names
- }
-
- assert "normalize_upload_filename" not in common_imports
- assert "normalize_upload_filename" not in fast_api_common_imports
- assert "normalize_upload_filename" in fast_api_upload_imports
-
-
def test_models_download_tier_basic(monkeypatch: Any) -> None:
monkeypatch.setattr(models.config.model, "stack", "full")
captured: list[str] = []
@@ -460,17 +572,6 @@ def test_kit_commands_do_not_expose_formula_table_switches() -> None:
assert _REMOVED_DISABLE_FORMULA_OPTION not in output
-def test_cli_old_api_request_models_remove_formula_table_fields() -> None:
- """校验旧 FastAPI 表单参数对象不再保存公式/表格开关。"""
- from mineru.cli_old import api_request as old_api_request
- from mineru.cli_old import fast_api as old_fast_api
-
- for model in (old_api_request.ParseRequestOptions, old_fast_api.ParseRequestOptions, old_fast_api.AsyncParseTask):
- annotations = getattr(model, "__annotations__", {})
- assert _REMOVED_FORMULA_ENABLE_PARAM not in annotations
- assert _REMOVED_TABLE_ENABLE_PARAM not in annotations
-
-
def test_api_server_forwards_single_tier_and_no_flash(monkeypatch: Any) -> None:
seen: dict[str, Any] = {}
@@ -884,7 +985,7 @@ def test_parse_single_file_markdown(monkeypatch: Any, tmp_path: Path) -> None:
assert output.read_text(encoding="utf-8") == "# demo\n"
-def test_parse_forwards_backend_alias_and_tier(monkeypatch: Any, tmp_path: Path) -> None:
+def test_parse_uses_backend_alias_only_to_resolve_tier(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
output = tmp_path / "out.md"
source.write_bytes(b"%PDF-1.7\n")
@@ -921,8 +1022,8 @@ def test_parse_forwards_backend_alias_and_tier(monkeypatch: Any, tmp_path: Path)
)
assert result.exit_code == 0
- assert seen["backend"] == "hybrid-engine"
assert seen["tier"] == "standard"
+ assert "backend" not in seen
assert "effort" not in seen
@@ -973,10 +1074,11 @@ def test_parse_batch_normalizes_office_quality_tier_to_flash(monkeypatch: Any, t
result = runner.invoke(app, ["parse", str(pdf), str(html), "-o", str(output), "--tier", "standard"])
assert result.exit_code == 0
- assert [(call["path"].name, call["tier"], call["backend"]) for call in calls] == [
- ("demo.pdf", "standard", "hybrid-engine"),
- ("page.html", "flash", "flash"),
+ assert [(call["path"].name, call["tier"]) for call in calls] == [
+ ("demo.pdf", "standard"),
+ ("page.html", "flash"),
]
+ assert all("backend" not in call for call in calls)
def test_parse_remote_requests_image_cache(monkeypatch: Any, tmp_path: Path) -> None:
@@ -1043,361 +1145,18 @@ def test_parse_remote_requests_image_cache(monkeypatch: Any, tmp_path: Path) ->
}
-def test_parse_normalizes_hidden_language_alias(monkeypatch: Any, tmp_path: Path) -> None:
[email protected]("language", ["japan", "ch_lite"])
+def test_parse_rejects_removed_language_option(language: str, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
- output = tmp_path / "out.md"
source.write_bytes(b"%PDF-1.7\n")
- seen: dict[str, Any] = {}
- class _Result:
- def markdown(self) -> str:
- """返回用于验证 language 归一化的测试内容。"""
- return "# demo\n"
+ result = runner.invoke(app, ["parse", str(source), "-o", str(tmp_path / "out.md"), "--language", language])
- def to_json(self) -> str:
- """保留 zip 输出所需接口。"""
- return '{"pages":[]}'
+ assert result.exit_code == 2
+ assert "No such option: --language" in " ".join(result.output.split())
- def images(self) -> dict[str, bytes]:
- """本用例不关注图片 sidecar。"""
- return {}
-
- def save(self, writer: Any) -> None:
- """模拟 zip 输出所需的完整保存接口。"""
- writer.write_string("markdown.md", self.markdown())
- writer.write_string("middle_json.json", self.to_json())
-
- def _fake_local_parse(*args: Any, **kwargs: Any) -> _Result:
- """记录 mineru-kit parse 透传给 parser 的语言参数。"""
- seen.update(kwargs)
- return _Result()
-
- monkeypatch.setattr(parse, "local_parse", _fake_local_parse)
-
- result = runner.invoke(app, ["parse", str(source), "-o", str(output), "--language", "japan"])
-
- assert result.exit_code == 0
- assert seen["language"] == "ch"
-
-
-def test_parse_rejects_removed_ch_lite_language(tmp_path: Path) -> None:
- source = tmp_path / "demo.pdf"
- source.write_bytes(b"%PDF-1.7\n")
-
- result = runner.invoke(app, ["parse", str(source), "-o", str(tmp_path / "out.md"), "--language", "ch_lite"])
-
- assert result.exit_code == 1
- assert "Language ch_lite not supported" in result.output
-
-
-def test_gradio_tier_selection_derives_v1_runtime() -> None:
- from mineru.cli_old import gradio_app
-
- assert gradio_app.resolve_gradio_runtime_options("basic").as_kwargs() == {
- "tier": "basic",
- "backend": "hybrid-engine",
- "effort": "medium",
- }
- assert gradio_app.resolve_gradio_runtime_options("standard").as_kwargs() == {
- "tier": "standard",
- "backend": "hybrid-engine",
- "effort": "high",
- }
- assert gradio_app.resolve_gradio_runtime_options("advanced").as_kwargs() == {
- "tier": "advanced",
- "backend": "hybrid-engine",
- "effort": "xhigh",
- }
-
-
-def test_gradio_extracts_supported_tiers_from_v1_tiers_payload() -> None:
- from mineru.cli_old import gradio_app
-
- payload = {
- "data": [
- {"id": "flash"},
- {"id": "advanced"},
- {"id": "experimental"},
- {"id": "basic"},
- {"id": "standard"},
- {"id": "advanced"},
- ]
- }
-
- assert gradio_app.extract_v1_tier_choices(payload) == ("flash", "advanced", "basic", "standard")
- assert gradio_app.default_v1_gradio_tier(("flash", "advanced", "basic", "standard")) == "standard"
-
-
-def test_gradio_rejects_v1_tiers_payload_without_supported_tiers() -> None:
- from mineru.cli_old import gradio_app
-
- with pytest.raises(click.ClickException, match="did not advertise any supported tier"):
- gradio_app.extract_v1_tier_choices({"data": [{"id": "experimental"}]})
-
-
-def test_gradio_persists_page_ranged_origin_pdf_for_v1_preview(tmp_path: Path) -> None:
- from pypdf import PdfReader, PdfWriter
-
- from mineru.cli_old import gradio_app
-
- pdf_writer = PdfWriter()
- pdf_writer.add_blank_page(width=100, height=100)
- pdf_writer.add_blank_page(width=200, height=200)
- pdf_writer.add_blank_page(width=300, height=300)
- source_pdf = BytesIO()
- pdf_writer.write(source_pdf)
-
- parse_result = ParseResult(
- middle_json=MiddleJson(
- pages=[
- PageInfo(page_idx=0),
- PageInfo(page_idx=1),
- ],
- file_suffix="pdf",
- effort="medium",
- parse_mode="txt",
- mineru_version=__version__,
- )
- )
- source = tmp_path / "demo.pdf"
- source.write_bytes(source_pdf.getvalue())
- extract_root = tmp_path / "extract"
- archive_zip_path = tmp_path / "archive.zip"
-
- output = gradio_app.persist_v1_gradio_result(
- parse_result=parse_result,
- file_path=str(source),
- extract_root=extract_root,
- archive_zip_path=archive_zip_path,
- backend="hybrid-engine",
- effort="medium",
- page_range="1~2",
- )
-
- origin_pdf_path = output.local_md_dir / "demo_origin.pdf"
- origin_reader = PdfReader(str(origin_pdf_path))
- assert len(origin_reader.pages) == 2
- assert [float(page.cropbox[2]) for page in origin_reader.pages] == [100.0, 200.0]
-
- layout_pdf_path = output.local_md_dir / "demo_layout.pdf"
- layout_reader = PdfReader(str(layout_pdf_path))
- assert output.preview_pdf_path == layout_pdf_path
- assert len(layout_reader.pages) == 2
-
- with zipfile.ZipFile(archive_zip_path) as archive:
- assert "demo_layout.pdf" in archive.namelist()
- assert "demo_model_output.json" not in archive.namelist()
- zipped_origin_reader = PdfReader(BytesIO(archive.read("demo_origin.pdf")))
- zipped_layout_reader = PdfReader(BytesIO(archive.read("demo_layout.pdf")))
- assert len(zipped_origin_reader.pages) == 2
- assert len(zipped_layout_reader.pages) == 2
- assert [float(page.cropbox[2]) for page in zipped_origin_reader.pages] == [100.0, 200.0]
-
-
-def test_gradio_persists_image_origin_as_pdf_for_v1_preview(tmp_path: Path) -> None:
- from PIL import Image
- from pypdf import PdfReader
-
- from mineru.cli_old import gradio_app
-
- source = tmp_path / "ref-merge.png"
- Image.new("RGB", (64, 48), "white").save(source)
- parse_result = ParseResult(
- middle_json=MiddleJson(
- pages=[PageInfo(page_idx=0)],
- file_suffix="pdf",
- effort="medium",
- parse_mode="txt",
- mineru_version=__version__,
- )
- )
- extract_root = tmp_path / "extract"
- archive_zip_path = tmp_path / "archive.zip"
-
- output = gradio_app.persist_v1_gradio_result(
- parse_result=parse_result,
- file_path=str(source),
- extract_root=extract_root,
- archive_zip_path=archive_zip_path,
- backend="hybrid-engine",
- effort="medium",
- page_range="",
- )
-
- origin_pdf_path = output.local_md_dir / "ref-merge_origin.pdf"
- layout_pdf_path = output.local_md_dir / "ref-merge_layout.pdf"
- assert origin_pdf_path.read_bytes().startswith(b"%PDF")
- assert len(PdfReader(str(origin_pdf_path)).pages) == 1
- assert layout_pdf_path.is_file()
- assert output.preview_pdf_path == layout_pdf_path
- assert len(PdfReader(str(layout_pdf_path)).pages) == 1
-
- with zipfile.ZipFile(archive_zip_path) as archive:
- assert archive.read("ref-merge_origin.pdf").startswith(b"%PDF")
- assert "ref-merge_layout.pdf" in archive.namelist()
- assert len(PdfReader(BytesIO(archive.read("ref-merge_origin.pdf"))).pages) == 1
- assert len(PdfReader(BytesIO(archive.read("ref-merge_layout.pdf"))).pages) == 1
-
-
-def test_gradio_v1_job_reuses_page_range_for_api_and_origin_pdf(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- from mineru.cli_old import gradio_app
-
- source = tmp_path / "demo.pdf"
- source.write_bytes(b"%PDF-1.7\n")
- calls: dict[str, Any] = {}
-
- class _FakeParser:
- def __init__(self, *, api_url: str, tier: str, include_images: bool, include_model_output: bool) -> None:
- calls["parser_api_url"] = api_url
- calls["parser_tier"] = tier
- calls["include_images"] = include_images
- calls["include_model_output"] = include_model_output
-
- async def parse_async(self, file_path: str, *, page_range: str) -> ParseResult:
- calls["api_page_range"] = page_range
- return ParseResult(
- middle_json=MiddleJson(
- pages=[PageInfo(page_idx=0)],
- file_suffix="pdf",
- effort="medium",
- parse_mode="txt",
- mineru_version=__version__,
- )
- )
-
- async def _fake_server_health(_http_client: Any, api_url: str | None) -> Any:
- """模拟 v1 server 健康检查,只保留 Gradio 任务需要的字段。"""
- return SimpleNamespace(base_url=api_url or "http://127.0.0.1:30000/api", max_concurrent_requests=1)
-
- def _fake_persist(**kwargs: Any) -> Any:
- """记录本地持久化收到的 page_range,避免联动测试访问真实 PDFium。"""
- calls["persist_page_range"] = kwargs["page_range"]
- local_md_dir = tmp_path / "persisted"
- local_md_dir.mkdir()
- (local_md_dir / "demo.md").write_text("markdown", encoding="utf-8")
- archive_zip_path = tmp_path / "demo.zip"
- archive_zip_path.write_bytes(b"zip")
- return SimpleNamespace(
- file_name="demo",
- local_md_dir=local_md_dir,
- archive_zip_path=archive_zip_path,
- preview_pdf_path=local_md_dir / "demo_origin.pdf",
- )
-
- monkeypatch.setattr(gradio_app, "MinerUApiParser", _FakeParser)
- monkeypatch.setattr(gradio_app, "resolve_v1_server_health", _fake_server_health)
- monkeypatch.setattr(gradio_app, "persist_v1_gradio_result", _fake_persist)
-
- asyncio.run(gradio_app._run_to_markdown_job(str(source), end_pages=2, api_url="http://example.test/api"))
-
- assert calls["api_page_range"] == "1~2"
- assert calls["include_model_output"] is True
- assert calls["include_images"] is True
- assert calls["persist_page_range"] == "1~2"
-
-
-def test_gradio_run_paths_are_absolute(tmp_path: Path) -> None:
- from mineru.cli_old import gradio_app
-
- source = tmp_path / "demo.pdf"
- source.write_bytes(b"%PDF-1.7\n")
-
- default_run_root, default_extract_root, default_archive_zip_path = gradio_app.create_gradio_run_paths(str(source))
- assert default_run_root.is_absolute()
- assert default_extract_root.is_absolute()
- assert default_archive_zip_path.is_absolute()
-
- run_root, extract_root, archive_zip_path = gradio_app.create_gradio_run_paths(
- str(source),
- output_root=str(tmp_path / "output"),
- )
- assert run_root.is_absolute()
- assert extract_root.is_absolute()
- assert archive_zip_path.is_absolute()
- assert extract_root.parent == run_root
- assert archive_zip_path.parent == run_root
-
-
-def test_gradio_frontend_uses_v1_only_tier_visibility() -> None:
- js_text = Path("mineru/resources/gradio_app.js").read_text(encoding="utf-8")
-
- assert ".mineru-remote-server-toggle" not in js_text
- assert ".mineru-advanced-popover" not in js_text
- assert "getUseRemoteServer" not in js_text
- assert "getBackendValue" not in js_text
- assert "getEffortValue" not in js_text
- assert ".mineru-backend-select" not in js_text
- assert ".mineru-hybrid-effort" not in js_text
- assert 'input[type="radio"]' not in js_text
- assert "mineru-show-client-options" not in js_text
- assert "mineru-show-image-analysis" not in js_text
- assert "mineru-show-ocr-language" not in js_text
- assert "mineru-hide-force-ocr" not in js_text
-
-
-def test_gradio_header_model_and_paper_links_use_popovers() -> None:
- """校验 Gradio header 的模型和论文入口使用可悬浮展开的多链接菜单。"""
- header_text = Path("mineru/resources/gradio_header.html").read_text(encoding="utf-8")
- gradio_text = Path("mineru/cli_old/gradio_app.py").read_text(encoding="utf-8")
-
- assert 'class="link-block mineru-header-menu mineru-model-menu"' in header_text
- assert 'class="link-block mineru-header-menu mineru-paper-menu"' in header_text
- assert "mineru-header-popover mineru-model-popover" in header_text
- assert "mineru-header-popover mineru-paper-popover" in header_text
- assert "https://huggingface.co/opendatalab/MinerU2.5-Pro-2605-1.2B" in header_text
- assert "https://modelscope.cn/models/OpenDataLab/MinerU2.5-Pro-2605-1.2B" in header_text
- assert "https://arxiv.org/abs/2409.18839" in header_text
- assert "https://arxiv.org/abs/2509.22186" in header_text
- assert "https://arxiv.org/abs/2604.04771" in header_text
- assert ".block.mineru-header-html" in header_text
- assert ".mineru-demo-header .external-link {\n font-size: 14px !important;" in header_text
- assert 'gr.HTML(render_header_html(i18n), elem_classes=["mineru-header-html"])' in gradio_text
-
- for placeholder, translation_key in {
- "{{HEADER_MODEL_HUGGINGFACE_LINK}}": "header_model_huggingface_link",
- "{{HEADER_MODEL_MODELSCOPE_LINK}}": "header_model_modelscope_link",
- "{{HEADER_PAPER_MINERU_REPORT}}": "header_paper_mineru_report",
- "{{HEADER_PAPER_MINERU25_REPORT}}": "header_paper_mineru25_report",
- "{{HEADER_PAPER_MINERU25PRO_REPORT}}": "header_paper_mineru25pro_report",
- }.items():
- assert placeholder in header_text
- assert f'"{placeholder}": "{translation_key}"' in gradio_text
- assert f'"{translation_key}"' in gradio_text
-
-
-def test_gradio_submit_inputs_are_v1_only() -> None:
- """校验 Gradio 公开控制面只保留 v1 API 支持的单次任务输入。"""
- gradio_text = Path("mineru/cli_old/gradio_app.py").read_text(encoding="utf-8")
-
- backend_block_idx = gradio_text.index('elem_classes=["mineru-backend-options-block"]')
- tier_idx = gradio_text.index("tier = gr.Dropdown(")
- max_pages_idx = gradio_text.index("max_pages = gr.Slider(")
-
- assert "backend = gr.Dropdown(" not in gradio_text
- assert "effort = gr.Dropdown(" not in gradio_text
- assert "effort = gr.Radio(" not in gradio_text
- assert "Hybrid effort" not in gradio_text
- assert "解析强度" not in gradio_text
- assert "use_remote_server = gr.Checkbox(" not in gradio_text
- assert "url = gr.Textbox(" not in gradio_text
- assert 'elem_classes=["mineru-client-options"]' not in gradio_text
- assert 'elem_classes=["mineru-advanced-popover"]' not in gradio_text
- assert "is_ocr = gr.Checkbox(" not in gradio_text
- assert _REMOVED_FORMULA_ENABLE_PARAM + " = gr.Checkbox(" not in gradio_text
- assert _REMOVED_TABLE_ENABLE_PARAM + " = gr.Checkbox(" not in gradio_text
- assert "image_analysis = gr.Checkbox(" not in gradio_text
- assert "language = gr.Dropdown(" not in gradio_text
- assert "use_remote_server=use_remote_server" not in gradio_text
- assert "tier=tier" in gradio_text
- assert "inputs=[input_file, max_pages, tier]" in gradio_text
- assert backend_block_idx < tier_idx < max_pages_idx
-
-
-def test_parse_forwards_flash_backend(monkeypatch: Any, tmp_path: Path) -> None:
+def test_parse_uses_flash_backend_to_resolve_flash_tier(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
output = tmp_path / "out.md"
source.write_bytes(b"%PDF-1.7\n")
@@ -1432,216 +1191,10 @@ def test_parse_forwards_flash_backend(monkeypatch: Any, tmp_path: Path) -> None:
assert result.exit_code == 0
assert seen["tier"] == "flash"
- assert seen["backend"] == "flash"
+ assert "backend" not in seen
assert output.read_text(encoding="utf-8") == "# demo\n"
-def test_cli_old_legacy_vlm_branch_maps_to_hybrid_xhigh(monkeypatch: Any, tmp_path: Path) -> None:
- from mineru.cli_old import common
-
- seen: dict[str, Any] = {}
-
- monkeypatch.setattr(common, "_process_office_doc", lambda *args, **kwargs: [])
- monkeypatch.setattr(
- common,
- "_prepare_pdf_inputs",
- lambda pdfs, start, end: [
- SimpleNamespace(pdf_bytes=pdf, retained_page_indices=None, broken_page_indices=None) for pdf in pdfs
- ],
- )
- monkeypatch.setattr(common, "ensure_backend_dependencies", lambda backend: None)
- monkeypatch.setattr(common, "get_vlm_engine", lambda inference_engine="auto", is_async=False: "vllm-engine")
-
- def _fake_process_hybrid(*args: Any, **kwargs: Any) -> None:
- """记录 legacy VLM 输入最终进入 Hybrid advanced 分支。"""
- seen["backend"] = args[3]
- seen["hybrid_backend"] = args[5]
- seen["kwargs"] = kwargs
-
- monkeypatch.setattr(common, "_process_hybrid", _fake_process_hybrid)
-
- common.do_parse(
- output_dir=str(tmp_path),
- pdf_file_names=["demo.pdf"],
- pdf_bytes_list=[b"%PDF-1.7\n"],
- p_lang_list=["ch"],
- backend="vlm-engine",
- effort="high",
- )
-
- assert seen["hybrid_backend"] == "vllm-engine"
- assert seen["kwargs"]["effort"] == "xhigh"
- assert seen["kwargs"]["image_analysis"] is True
- assert not hasattr(common, "_process_vlm")
-
-
-def test_cli_old_hybrid_branch_keeps_effort(monkeypatch: Any, tmp_path: Path) -> None:
- from mineru.cli_old import common
-
- seen: dict[str, Any] = {}
-
- monkeypatch.setattr(common, "_process_office_doc", lambda *args, **kwargs: [])
- monkeypatch.setattr(
- common,
- "_prepare_pdf_inputs",
- lambda pdfs, start, end: [
- SimpleNamespace(pdf_bytes=pdf, retained_page_indices=None, broken_page_indices=None) for pdf in pdfs
- ],
- )
- monkeypatch.setattr(common, "ensure_backend_dependencies", lambda backend: None)
- monkeypatch.setattr(common, "get_vlm_engine", lambda inference_engine="auto", is_async=False: "vllm-engine")
-
- def _fake_process_hybrid(*args: Any, **kwargs: Any) -> None:
- """记录 Hybrid 分支收到的 kwargs,确认 effort 仍传给 hybrid analyzer。"""
- seen["backend"] = args[5]
- seen["kwargs"] = kwargs
-
- monkeypatch.setattr(common, "_process_hybrid", _fake_process_hybrid)
- monkeypatch.setenv("MINERU_VLM_FORMULA_ENABLE", "sentinel-formula")
- monkeypatch.setenv("MINERU_VLM_TABLE_ENABLE", "sentinel-table")
-
- common.do_parse(
- output_dir=str(tmp_path),
- pdf_file_names=["demo.pdf"],
- pdf_bytes_list=[b"%PDF-1.7\n"],
- p_lang_list=["ch"],
- backend="hybrid-engine",
- effort="high",
- )
-
- assert seen["backend"] == "vllm-engine"
- assert seen["kwargs"]["effort"] == "high"
- assert os.environ["MINERU_VLM_FORMULA_ENABLE"] == "sentinel-formula"
- assert os.environ["MINERU_VLM_TABLE_ENABLE"] == "sentinel-table"
-
-
-def test_cli_old_hybrid_medium_skips_vlm_engine_resolution(monkeypatch: Any, tmp_path: Path) -> None:
- from mineru.cli_old import common
-
- seen: dict[str, Any] = {}
-
- monkeypatch.setattr(common, "_process_office_doc", lambda *args, **kwargs: [])
- monkeypatch.setattr(
- common,
- "_prepare_pdf_inputs",
- lambda pdfs, start, end: [
- SimpleNamespace(pdf_bytes=pdf, retained_page_indices=None, broken_page_indices=None) for pdf in pdfs
- ],
- )
- monkeypatch.setattr(common, "ensure_backend_dependencies", lambda backend: None)
-
- def fail_get_vlm_engine(*_args: Any, **_kwargs: Any) -> str:
- """Hybrid basic 不应触发 VLM engine 解析。"""
- raise AssertionError("medium effort should not resolve VLM engine")
-
- def _fake_process_hybrid(*args: Any, **kwargs: Any) -> None:
- """记录 Hybrid basic 仍进入 Hybrid 处理分支。"""
- seen["backend"] = args[5]
- seen["langs"] = list(args[3])
- seen["pdf_count"] = len(args[2])
- seen["kwargs"] = kwargs
-
- monkeypatch.setattr(common, "get_vlm_engine", fail_get_vlm_engine)
- monkeypatch.setattr(common, "_process_hybrid", _fake_process_hybrid)
-
- common.do_parse(
- output_dir=str(tmp_path),
- pdf_file_names=["a.pdf", "b.pdf"],
- pdf_bytes_list=[b"%PDF-1.7\n", b"%PDF-1.7\n"],
- p_lang_list=["en", "en"],
- backend="hybrid-engine",
- effort="medium",
- )
-
- assert seen["backend"] == "engine"
- assert seen["langs"] == ["en", "en"]
- assert seen["pdf_count"] == 2
- assert seen["kwargs"]["effort"] == "medium"
-
-
-def test_cli_old_async_legacy_vlm_branch_maps_to_hybrid_xhigh(monkeypatch: Any, tmp_path: Path) -> None:
- from mineru.cli_old import common
-
- seen: dict[str, Any] = {}
-
- monkeypatch.setattr(common, "_process_office_doc", lambda *args, **kwargs: [])
- monkeypatch.setattr(
- common,
- "_prepare_pdf_inputs",
- lambda pdfs, start, end: [
- SimpleNamespace(pdf_bytes=pdf, retained_page_indices=None, broken_page_indices=None) for pdf in pdfs
- ],
- )
- monkeypatch.setattr(common, "ensure_backend_dependencies", lambda backend: None)
- monkeypatch.setattr(common, "get_vlm_engine", lambda inference_engine="auto", is_async=True: "vllm-async-engine")
-
- async def _fake_async_process_hybrid(*args: Any, **kwargs: Any) -> None:
- """记录异步 legacy VLM 输入最终进入 Hybrid advanced 分支。"""
- seen["backend"] = args[3]
- seen["hybrid_backend"] = args[5]
- seen["kwargs"] = kwargs
-
- monkeypatch.setattr(common, "_async_process_hybrid", _fake_async_process_hybrid)
-
- asyncio.run(
- common.aio_do_parse(
- output_dir=str(tmp_path),
- pdf_file_names=["demo.pdf"],
- pdf_bytes_list=[b"%PDF-1.7\n"],
- p_lang_list=["ch"],
- backend="vlm-engine",
- effort="high",
- )
- )
-
- assert seen["hybrid_backend"] == "vllm-async-engine"
- assert seen["kwargs"]["effort"] == "xhigh"
- assert seen["kwargs"]["image_analysis"] is True
- assert not hasattr(common, "_async_process_vlm")
-
-
-def test_cli_old_async_hybrid_branch_keeps_effort(monkeypatch: Any, tmp_path: Path) -> None:
- from mineru.cli_old import common
-
- seen: dict[str, Any] = {}
-
- monkeypatch.setattr(common, "_process_office_doc", lambda *args, **kwargs: [])
- monkeypatch.setattr(
- common,
- "_prepare_pdf_inputs",
- lambda pdfs, start, end: [
- SimpleNamespace(pdf_bytes=pdf, retained_page_indices=None, broken_page_indices=None) for pdf in pdfs
- ],
- )
- monkeypatch.setattr(common, "ensure_backend_dependencies", lambda backend: None)
- monkeypatch.setattr(common, "get_vlm_engine", lambda inference_engine="auto", is_async=True: "vllm-async-engine")
-
- async def _fake_async_process_hybrid(*args: Any, **kwargs: Any) -> None:
- """记录异步 Hybrid 分支收到的 kwargs,确认 effort 仍传给 hybrid analyzer。"""
- seen["backend"] = args[5]
- seen["kwargs"] = kwargs
-
- monkeypatch.setattr(common, "_async_process_hybrid", _fake_async_process_hybrid)
- monkeypatch.setenv("MINERU_VLM_FORMULA_ENABLE", "sentinel-formula")
- monkeypatch.setenv("MINERU_VLM_TABLE_ENABLE", "sentinel-table")
-
- asyncio.run(
- common.aio_do_parse(
- output_dir=str(tmp_path),
- pdf_file_names=["demo.pdf"],
- pdf_bytes_list=[b"%PDF-1.7\n"],
- p_lang_list=["ch"],
- backend="hybrid-engine",
- effort="high",
- )
- )
-
- assert seen["backend"] == "vllm-async-engine"
- assert seen["kwargs"]["effort"] == "high"
- assert os.environ["MINERU_VLM_FORMULA_ENABLE"] == "sentinel-formula"
- assert os.environ["MINERU_VLM_TABLE_ENABLE"] == "sentinel-table"
-
-
def test_parse_output_replaces_surrogate_chars(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
output = tmp_path / "out.md"
diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.py
new file mode 100644
index 00000000..b015cac0
--- /dev/null
+++ b/tests/unittest/test_kit_gradio.py
@@ -0,0 +1,822 @@
+from __future__ import annotations
+
+import asyncio
+import io
+import subprocess
+import sys
+import zipfile
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import httpx
+import pytest
+from fastapi.testclient import TestClient
+from PIL import Image, ImageStat
+from pypdf import PdfReader, PdfWriter
+from reportlab.pdfgen import canvas
+
+from mineru.filetypes import PARSEABLE_EXTENSIONS
+from mineru.kit.commands import gradio as gradio_command
+from mineru.kit.gradio import app as gradio_app
+from mineru.kit.gradio import client as gradio_client
+from mineru.kit.gradio.app import build_gradio_app
+from mineru.kit.gradio.artifacts import create_run_artifacts, persist_parse_result, render_download
+from mineru.kit.gradio.client import (
+ ManagedLocalApiServer,
+ STATUS_DOWNLOADING_RESULT,
+ V1ArtifactClient,
+ V1ArtifactError,
+ V1ServerCapabilities,
+ normalize_v1_base_url,
+)
+from mineru.kit.main import app
+from mineru.parser import api_client as parser_api_client
+from mineru.parser import api_server as parser_api_server
+from mineru.parser.base import ParseResult
+from mineru.types import BlockType, ImageBlock, ImageBodyBlock, MiddleJson, PageInfo, TextBlock, TextSpan
+from mineru.version import __version__
+from typer.testing import CliRunner
+
+runner = CliRunner()
+
+
+def _pdf_bytes(page_count: int = 1) -> bytes:
+ """生成测试所需的最小多页 PDF。"""
+ writer = PdfWriter()
+ for _ in range(page_count):
+ writer.add_blank_page(width=200, height=300)
+ output = io.BytesIO()
+ writer.write(output)
+ return output.getvalue()
+
+
+def _colored_pdf_bytes(colors: list[tuple[float, float, float]]) -> bytes:
+ """生成每页使用不同纯色背景的 PDF,用于验证裁页映射。"""
+ output = io.BytesIO()
+ painter = canvas.Canvas(output, pagesize=(120, 160))
+ for red, green, blue in colors:
+ painter.setFillColorRGB(red, green, blue)
+ painter.rect(0, 0, 120, 160, stroke=0, fill=1)
+ painter.showPage()
+ painter.save()
+ return output.getvalue()
+
+
+def _middle_json(
+ *,
+ with_image: bool = True,
+ file_suffix: str = "pdf",
+ page_indices: tuple[int, ...] = (0,),
+) -> MiddleJson:
+ """构造包含文字和可选视觉块的严格 Middle JSON。"""
+ pages: list[PageInfo] = []
+ for page_idx in page_indices:
+ blocks: list[Any] = [
+ TextBlock(
+ type=BlockType.TEXT,
+ index=page_idx * 10,
+ bbox=(0.1, 0.1, 0.8, 0.2) if file_suffix == "pdf" else None,
+ content=[TextSpan(type="text", content=f"hello-{page_idx}")],
+ )
+ ]
+ if with_image:
+ image_index = page_idx * 10 + 1
+ image_body = ImageBodyBlock(
+ type=BlockType.IMAGE_BODY,
+ index=image_index,
+ bbox=(0.1, 0.3, 0.8, 0.8) if file_suffix == "pdf" else None,
+ content="",
+ )
+ blocks.append(
+ ImageBlock(
+ type=BlockType.IMAGE,
+ index=image_index,
+ bbox=(0.1, 0.3, 0.8, 0.8) if file_suffix == "pdf" else None,
+ content=[image_body],
+ )
+ )
+ pages.append(PageInfo(page_idx=page_idx, blocks=blocks))
+ return MiddleJson(
+ pages=pages,
+ is_full_document=page_indices == tuple(range(len(page_indices))),
+ file_suffix=file_suffix, # type: ignore[arg-type]
+ effort="flash",
+ parse_mode="txt",
+ mineru_version=__version__,
+ )
+
+
+def _httpx_proxy_for_test_client(
+ test_client: TestClient,
+ request_log: list[tuple[str, str, str | None]],
+) -> SimpleNamespace:
+ """把异步 httpx 调用桥接到已启动 lifespan 的 FastAPI TestClient。"""
+
+ class AsyncClientAdapter:
+ """为 V1 async client 提供最小的 TestClient 异步适配层。"""
+
+ def __init__(self, *_args: object, **_kwargs: object) -> None:
+ """忽略真实网络参数并复用当前 TestClient。"""
+
+ async def __aenter__(self) -> "AsyncClientAdapter":
+ """进入异步上下文。"""
+ return self
+
+ async def __aexit__(self, *_args: object) -> None:
+ """退出异步上下文,不关闭外层 TestClient。"""
+
+ async def get(self, url: str, **kwargs: Any) -> httpx.Response:
+ """通过 TestClient 执行 GET。"""
+ return self._request("GET", url, **kwargs)
+
+ async def post(self, url: str, **kwargs: Any) -> httpx.Response:
+ """通过 TestClient 执行 POST。"""
+ return self._request("POST", url, **kwargs)
+
+ async def put(self, url: str, **kwargs: Any) -> httpx.Response:
+ """通过 TestClient 执行 PUT。"""
+ return self._request("PUT", url, **kwargs)
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
+ """记录鉴权信息并把绝对 URL 转换为 ASGI 路径。"""
+ headers = kwargs.get("headers") or {}
+ parsed = httpx.URL(url)
+ request_log.append((method, parsed.path, headers.get("Authorization")))
+ return test_client.request(method, parsed.raw_path.decode("ascii"), **kwargs)
+
+ return SimpleNamespace(
+ AsyncClient=AsyncClientAdapter,
+ Client=httpx.Client,
+ HTTPError=httpx.HTTPError,
+ InvalidURL=httpx.InvalidURL,
+ Response=httpx.Response,
+ Timeout=httpx.Timeout,
+ TimeoutException=httpx.TimeoutException,
+ TransportError=httpx.TransportError,
+ URL=httpx.URL,
+ )
+
+
+def test_gradio_command_is_registered_and_help_is_available() -> None:
+ """验证 mineru-kit 根命令注册 Gradio 且帮助不启动服务。"""
+ result = runner.invoke(app, ["--help"])
+ gradio_result = runner.invoke(app, ["gradio", "--help"])
+ assert result.exit_code == 0
+ assert gradio_result.exit_code == 0
+ assert "gradio" in result.output
+ assert "--api-url" in gradio_result.output
+ assert "--api-server-tier" in gradio_result.output
+
+
+def test_importing_kit_cli_does_not_import_optional_gradio_runtime() -> None:
+ """验证查看通用 CLI 时不会提前导入 Gradio 或 gradio-pdf。"""
+ completed = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "import sys; import mineru.kit.main; assert 'gradio' not in sys.modules; assert 'gradio_pdf' not in sys.modules",
+ ],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ assert completed.returncode == 0, completed.stderr
+
+
+def test_gradio_command_reports_optional_dependency_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证未安装 Gradio 时命令给出可执行安装建议。"""
+ original_find_spec = gradio_command.importlib.util.find_spec
+
+ def fake_find_spec(name: str) -> Any:
+ """只模拟 Gradio 相关模块缺失,保留其他模块探测。"""
+ if name in {"gradio", "gradio_pdf"}:
+ return None
+ return original_find_spec(name)
+
+ monkeypatch.setattr(gradio_command.importlib.util, "find_spec", fake_find_spec)
+ result = runner.invoke(app, ["gradio"])
+ assert result.exit_code == 1
+ assert "mineru[gradio]" in result.output
+
+
+def test_gradio_url_normalization_and_capability_dataclass() -> None:
+ """验证 V1 base URL 规范化及能力快照字段。"""
+ assert normalize_v1_base_url("127.0.0.1:8000/") == "http://127.0.0.1:8000"
+ with pytest.raises(V1ArtifactError, match="must not be empty"):
+ normalize_v1_base_url(" ")
+ with pytest.raises(V1ArtifactError, match="credentials, query, or fragment"):
+ normalize_v1_base_url("https://user:[email protected]/api")
+ with pytest.raises(V1ArtifactError, match="Invalid V1 API URL"):
+ normalize_v1_base_url("http://example.test:not-a-port")
+ capabilities = V1ServerCapabilities("http://example.test", ("flash",), ("zip",), ("file_id",))
+ assert capabilities.tiers == ("flash",)
+ assert capabilities.output_formats == ("zip",)
+
+
+def test_v1_client_uses_environment_api_key_when_cli_value_is_omitted(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 API Key 的环境变量回退不会要求页面输入密钥。"""
+ monkeypatch.setenv("MINERU_API_KEY", "from-env")
+ client = V1ArtifactClient(api_url="http://example.test")
+ assert client.api_key == "from-env"
+
+
+def test_v1_client_discovers_health_and_tiers_and_sends_api_key() -> None:
+ """验证能力发现只访问新的 V1 endpoint,并携带 Bearer API Key。"""
+ requests: list[tuple[str, str]] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ """返回最小健康和 tier 响应。"""
+ requests.append((request.method, request.url.path))
+ assert request.headers["authorization"] == "Bearer secret"
+ if request.url.path == "/api/v1/health":
+ return httpx.Response(
+ 200,
+ json={
+ "status": "ok",
+ "features": {
+ "output_formats": ["markdown", "zip"],
+ "sources": ["file_id", "inline"],
+ },
+ },
+ request=request,
+ )
+ if request.url.path == "/api/v1/tiers":
+ return httpx.Response(200, json={"data": [{"id": "flash"}]}, request=request)
+ return httpx.Response(404, request=request)
+
+ client = V1ArtifactClient(
+ api_url="http://example.test/api",
+ api_key="secret",
+ transport=httpx.MockTransport(handler),
+ )
+ capabilities = asyncio.run(client.discover())
+ assert capabilities.base_url == "http://example.test/api"
+ assert capabilities.tiers == ("flash",)
+ assert requests == [("GET", "/api/v1/health"), ("GET", "/api/v1/tiers")]
+
+
+def test_v1_client_rejects_server_without_zip() -> None:
+ """验证缺少 ZIP 能力时在 UI 启动前给出稳定错误。"""
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ """返回没有 ZIP 的健康 payload。"""
+ if request.url.path.endswith("/health"):
+ return httpx.Response(
+ 200,
+ json={"status": "ok", "features": {"output_formats": ["middle_json"], "sources": ["file_id"]}},
+ request=request,
+ )
+ return httpx.Response(200, json={"data": [{"id": "flash"}]}, request=request)
+
+ client = V1ArtifactClient(api_url="http://example.test", transport=httpx.MockTransport(handler))
+ with pytest.raises(V1ArtifactError, match="does not advertise zip"):
+ asyncio.run(client.discover())
+
+
+ ("sources", "tiers", "error_code"),
+ [
+ (("inline", "url"), ("flash",), "unsupported_source"),
+ (("file_id",), ("experimental",), "tier_unavailable"),
+ ],
+)
+def test_v1_client_rejects_missing_upload_or_tier_capability(
+ sources: tuple[str, ...],
+ tiers: tuple[str, ...],
+ error_code: str,
+) -> None:
+ """验证能力发现会拒绝无法完成上传或没有受支持 tier 的服务。"""
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ """返回参数化的最小 V1 能力响应。"""
+ if request.url.path.endswith("/health"):
+ return httpx.Response(
+ 200,
+ json={"status": "ok", "features": {"output_formats": ["zip"], "sources": list(sources)}},
+ request=request,
+ )
+ return httpx.Response(200, json={"data": [{"id": tier} for tier in tiers]}, request=request)
+
+ client = V1ArtifactClient(api_url="http://example.test", transport=httpx.MockTransport(handler))
+ with pytest.raises(V1ArtifactError) as error:
+ asyncio.run(client.discover())
+ assert error.value.code == error_code
+
+
+def test_v1_client_checks_requested_tier_after_first_discovery(tmp_path: Path) -> None:
+ """验证首次 discover 后也会立即拒绝服务未提供的请求 tier。"""
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(_pdf_bytes())
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ """只声明 Flash tier。"""
+ if request.url.path.endswith("/health"):
+ return httpx.Response(
+ 200,
+ json={"status": "ok", "features": {"output_formats": ["zip"], "sources": ["file_id"]}},
+ request=request,
+ )
+ return httpx.Response(200, json={"data": [{"id": "flash"}]}, request=request)
+
+ client = V1ArtifactClient(api_url="http://example.test", transport=httpx.MockTransport(handler))
+ with pytest.raises(V1ArtifactError) as error:
+ asyncio.run(client.parse_file(source, tier="standard", page_range=""))
+ assert error.value.code == "tier_unavailable"
+
+
+def test_v1_client_full_asgi_upload_job_poll_and_zip(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """通过真实 V1 ASGI 路由验证上传、任务、轮询、ZIP 与 API Key 链路。"""
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(_pdf_bytes())
+ parse_calls: list[dict[str, Any]] = []
+
+ async def fake_parse_async(path: str, **kwargs: Any) -> ParseResult:
+ """替代模型推理,同时保留 server 的真实 job 和打包流程。"""
+ parse_calls.append({"path": path, **kwargs})
+ return ParseResult(middle_json=_middle_json(with_image=False), _model_output={"raw": "model"})
+
+ monkeypatch.setattr(parser_api_server, "parse_async", fake_parse_async)
+ api = parser_api_server.create_app(
+ upload_dir=str(tmp_path / "api"),
+ tier="flash",
+ api_key="secret",
+ )
+ request_log: list[tuple[str, str, str | None]] = []
+ with TestClient(api, base_url="http://testserver") as test_client:
+ proxy = _httpx_proxy_for_test_client(test_client, request_log)
+ monkeypatch.setattr(gradio_client, "httpx", proxy)
+ monkeypatch.setattr(parser_api_client, "httpx", proxy)
+ client = V1ArtifactClient(api_url="http://testserver", api_key="secret")
+ result = asyncio.run(client.parse_file(source, tier="flash", page_range="1"))
+
+ paths = [path for _method, path, _authorization in request_log]
+ assert "/v1/health" in paths
+ assert "/v1/tiers" in paths
+ assert "/v1/uploads" in paths
+ assert any(path.startswith("/v1/uploads/upload_") and path.endswith("/content") for path in paths)
+ assert "/v1/parse/jobs" in paths
+ assert any(path.startswith("/v1/files/file-") and path.endswith("/content") for path in paths)
+ protected_requests = [item for item in request_log if item[1] not in {"/v1/health", "/v1/tiers"}]
+ assert protected_requests and all(authorization == "Bearer secret" for _method, _path, authorization in protected_requests)
+ assert result._model_output == {"raw": "model"}
+ assert parse_calls[0]["page_range"] == "1"
+
+
+def test_api_client_upload_auth_is_limited_to_same_origin() -> None:
+ """验证 Bearer Key 会用于同源上传,但不会泄露给外部预签名地址。"""
+ same_origin = parser_api_client._same_origin_upload_headers(
+ "https://api.example.test/base",
+ "https://api.example.test/v1/uploads/1/content",
+ {"Content-Type": "application/pdf"},
+ {"Authorization": "Bearer secret"},
+ )
+ external = parser_api_client._same_origin_upload_headers(
+ "https://api.example.test/base",
+ "https://storage.example.test/upload",
+ {"Content-Type": "application/pdf"},
+ {"Authorization": "Bearer secret"},
+ )
+ assert same_origin["Authorization"] == "Bearer secret"
+ assert "Authorization" not in external
+
+
+def test_v1_client_preserves_v1_error_code(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """验证 V1 error envelope 会保留错误码并清晰传给 UI。"""
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(_pdf_bytes())
+
+ class FailingParser:
+ """模拟 API parser 返回带错误码的失败。"""
+
+ def __init__(self, **_kwargs: Any) -> None:
+ """忽略构造参数。"""
+
+ async def parse_async(self, _path: Path, *, page_range: str) -> ParseResult:
+ """抛出与正式 API client 一致的错误形态。"""
+ error = RuntimeError(f"bad range: {page_range}")
+ error.code = "invalid_page_range" # type: ignore[attr-defined]
+ raise error
+
+ monkeypatch.setattr(gradio_client, "MinerUApiParser", FailingParser)
+ client = V1ArtifactClient(api_url="http://example.test")
+ client._capabilities = V1ServerCapabilities("http://example.test", ("flash",), ("zip",), ("file_id",))
+ with pytest.raises(V1ArtifactError) as error:
+ asyncio.run(client.parse_file(source, tier="flash", page_range="bad"))
+ assert error.value.code == "invalid_page_range"
+
+
+def test_v1_client_parse_uses_api_parser_zip_contract(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """验证 Gradio client 固定请求带图片和模型输出的 V1 ZIP 结果。"""
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(_pdf_bytes())
+ calls: dict[str, Any] = {}
+
+ class FakeParser:
+ """记录 V1 parser 构造和页码参数。"""
+
+ def __init__(self, **kwargs: Any) -> None:
+ """保存构造参数,供断言 V1 ZIP 契约。"""
+ calls.update(kwargs)
+
+ async def parse_async(self, path: Path, *, page_range: str) -> ParseResult:
+ """返回最小解析结果。"""
+ calls["path"] = path
+ calls["page_range"] = page_range
+ return ParseResult(middle_json=_middle_json(with_image=False))
+
+ monkeypatch.setattr("mineru.kit.gradio.client.MinerUApiParser", FakeParser)
+ client = V1ArtifactClient(api_url="http://example.test")
+ client._capabilities = V1ServerCapabilities(
+ "http://example.test",
+ ("standard",),
+ ("zip",),
+ ("file_id",),
+ )
+ statuses: list[str] = []
+ result = asyncio.run(client.parse_file(source, tier="standard", page_range="1~2", status_callback=statuses.append))
+ assert isinstance(result, ParseResult)
+ assert calls["include_images"] is True
+ assert calls["include_model_output"] is True
+ assert calls["tier"] == "standard"
+ assert calls["page_range"] == "1~2"
+ assert statuses[0] == "Preparing request..."
+ assert statuses[-1] == STATUS_DOWNLOADING_RESULT
+
+
+def test_managed_local_api_command_uses_kit_entrypoint() -> None:
+ """验证托管 server 使用正式 mineru-kit api-server 命令。"""
+ server = ManagedLocalApiServer(
+ tier="standard",
+ no_flash=True,
+ concurrency=3,
+ language="en",
+ ocr_mode="ocr",
+ disable_image_analysis=True,
+ preload_models=True,
+ api_key="secret",
+ )
+ command = server._command(8123, Path("/tmp/mineru-upload"))
+ assert command[:4] == [server._command(8123, Path("/tmp/mineru-upload"))[0], "-m", "mineru.kit.main", "api-server"]
+ assert "--tier" in command and command[command.index("--tier") + 1] == "standard"
+ assert "--no-flash" in command
+ assert "--preload-models" in command
+ assert command[command.index("--api-key") + 1] == "secret"
+
+
+def test_managed_local_api_server_cleans_process_control_and_temp_dir(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证托管 server 启停会使用控制通道并清理上传临时目录。"""
+ captured: dict[str, Any] = {}
+
+ class FakeControl:
+ """记录 ManagedProcessControl 生命周期。"""
+
+ def start_accepting(self) -> None:
+ """记录控制通道开始监听。"""
+ captured["accepting"] = True
+
+ def child_env(self) -> dict[str, str]:
+ """返回测试专用子进程环境。"""
+ return {"MINERU_PROCESS_CONTROL": "test"}
+
+ def request_shutdown(self, timeout_sec: float) -> bool:
+ """记录优雅关闭请求。"""
+ captured["shutdown_timeout"] = timeout_sec
+ return True
+
+ def close(self) -> None:
+ """记录控制通道关闭。"""
+ captured["closed"] = True
+
+ class FakeProcess:
+ """模拟能被优雅关闭的 API server 子进程。"""
+
+ def __init__(self) -> None:
+ """初始化运行态。"""
+ self.returncode: int | None = None
+
+ def poll(self) -> int | None:
+ """返回当前进程状态。"""
+ return self.returncode
+
+ def wait(self, timeout: float | None = None) -> int:
+ """记录等待并结束模拟进程。"""
+ captured["wait_timeout"] = timeout
+ self.returncode = 0
+ return 0
+
+ def terminate(self) -> None:
+ """记录降级终止。"""
+ captured["terminated"] = True
+
+ def kill(self) -> None:
+ """记录强制终止。"""
+ captured["killed"] = True
+
+ fake_control = FakeControl()
+
+ def fake_popen(command: list[str], **kwargs: Any) -> FakeProcess:
+ """记录托管子进程命令和环境。"""
+ captured["command"] = command
+ captured["popen_kwargs"] = kwargs
+ return FakeProcess()
+
+ def fake_create_control() -> FakeControl:
+ """返回测试控制通道。"""
+ return fake_control
+
+ def fake_wait_until_ready(_server: ManagedLocalApiServer) -> None:
+ """跳过真实 HTTP 健康检查。"""
+
+ monkeypatch.setattr(gradio_client.ManagedProcessControl, "create", fake_create_control)
+ monkeypatch.setattr(gradio_client.subprocess, "Popen", fake_popen)
+ monkeypatch.setattr(ManagedLocalApiServer, "_wait_until_ready", fake_wait_until_ready)
+
+ server = ManagedLocalApiServer(tier="flash")
+ server.start()
+ assert server._temp_dir is not None
+ temp_root = Path(server._temp_dir.name)
+ assert temp_root.is_dir()
+ assert "--allow-local-source" not in captured["command"]
+ assert captured["accepting"] is True
+
+ server.stop()
+
+ assert not temp_root.exists()
+ assert captured["closed"] is True
+ assert captured["shutdown_timeout"] == 3.0
+ assert "terminated" not in captured
+
+
+def test_persist_and_render_all_gradio_download_formats(tmp_path: Path) -> None:
+ """验证严格 Middle JSON、布局 PDF 和六种下载产物。"""
+ source = tmp_path / "报告.pdf"
+ source.write_bytes(_pdf_bytes())
+ result = ParseResult(middle_json=_middle_json(), _model_output={"raw": "model"})
+ artifacts = persist_parse_result(result, source, output_root=tmp_path / "output", page_range="")
+
+ assert artifacts.middle_json_path.read_text(encoding="utf-8").find('"schema_version": "2.0"') >= 0
+ assert artifacts.origin_pdf_path == artifacts.root / "origin.pdf"
+ assert artifacts.layout_pdf_path == artifacts.root / "layout.pdf"
+ assert artifacts.origin_pdf_path is not None and artifacts.origin_pdf_path.is_file()
+ assert artifacts.layout_pdf_path is not None and artifacts.layout_pdf_path.is_file()
+ assert artifacts.bundle_zip_path.is_file()
+ assert list((artifacts.root / "images").glob("*.jpg"))
+ with zipfile.ZipFile(artifacts.bundle_zip_path) as archive:
+ assert {
+ "source.pdf",
+ "middle_json.json",
+ "markdown.md",
+ "structured_content.json",
+ "model_output.json",
+ "origin.pdf",
+ "layout.pdf",
+ }.issubset(archive.namelist())
+
+ html_path = Path(render_download(artifacts.as_state(), "html", allowed_root=tmp_path / "output"))
+ docx_path = Path(render_download(artifacts.as_state(), "docx", allowed_root=tmp_path / "output"))
+ latex_path = Path(render_download(artifacts.as_state(), "latex", allowed_root=tmp_path / "output"))
+ epub_path = Path(render_download(artifacts.as_state(), "epub", allowed_root=tmp_path / "output"))
+ pdf_path = Path(render_download(artifacts.as_state(), "pdf", allowed_root=tmp_path / "output"))
+ assert "<!doctype html>" in html_path.read_text(encoding="utf-8").lower()
+ assert "data:image/jpeg;base64," in html_path.read_text(encoding="utf-8")
+ assert docx_path.read_bytes().startswith(b"PK")
+ assert epub_path.read_bytes().startswith(b"PK")
+ assert pdf_path.read_bytes().startswith(b"%PDF")
+ with zipfile.ZipFile(latex_path) as archive:
+ assert f"{artifacts.stem}.tex" in archive.namelist()
+ assert any(name.startswith("images/") for name in archive.namelist())
+ layout_page = PdfReader(str(artifacts.layout_pdf_path)).pages[0]
+ layout_stream = layout_page.get_contents()
+ assert layout_stream is not None
+ layout_commands = layout_stream.get_data()
+ assert b"20 240 140 30 re" in layout_commands
+ assert b"20 60 140 150 re" in layout_commands
+
+
+def test_persist_image_input_creates_real_origin_and_layout_pdfs(tmp_path: Path) -> None:
+ """验证图片输入会生成可读取的 origin/layout PDF,而不是伪装扩展名。"""
+ source = tmp_path / "scan.png"
+ Image.new("RGB", (64, 48), "white").save(source)
+ artifacts = persist_parse_result(
+ ParseResult(middle_json=_middle_json(with_image=False)),
+ source,
+ output_root=tmp_path / "output",
+ page_range="",
+ )
+ assert artifacts.origin_pdf_path is not None
+ assert artifacts.layout_pdf_path is not None
+ assert artifacts.origin_pdf_path.read_bytes().startswith(b"%PDF")
+ assert artifacts.layout_pdf_path.read_bytes().startswith(b"%PDF")
+ assert len(PdfReader(str(artifacts.origin_pdf_path)).pages) == 1
+ assert len(PdfReader(str(artifacts.layout_pdf_path)).pages) == 1
+
+
+def test_page_range_image_crops_follow_original_page_indices(tmp_path: Path) -> None:
+ """验证抽页后视觉块仍从对应原始页裁图,而不是错位到相邻页。"""
+ source = tmp_path / "colors.pdf"
+ source.write_bytes(_colored_pdf_bytes([(1, 0, 0), (0, 1, 0), (0, 0, 1)]))
+ artifacts = persist_parse_result(
+ ParseResult(middle_json=_middle_json(page_indices=(1, 2))),
+ source,
+ output_root=tmp_path / "output",
+ page_range="2~3",
+ )
+ images = sorted((artifacts.root / "images").glob("*.jpg"))
+ assert len(images) == 2
+ with Image.open(images[0]) as first_image, Image.open(images[1]) as second_image:
+ first_mean = ImageStat.Stat(first_image.convert("RGB")).mean
+ second_mean = ImageStat.Stat(second_image.convert("RGB")).mean
+ assert first_mean[1] > first_mean[0] + 100 and first_mean[1] > first_mean[2] + 100
+ assert second_mean[2] > second_mean[0] + 100 and second_mean[2] > second_mean[1] + 100
+
+
+def test_persist_page_range_keeps_cropped_origin_page_order(tmp_path: Path) -> None:
+ """验证任意 V1 page_range 会同步应用到 origin 和 layout PDF。"""
+ source = tmp_path / "three-pages.pdf"
+ source.write_bytes(_pdf_bytes(page_count=3))
+ artifacts = persist_parse_result(
+ ParseResult(middle_json=_middle_json(with_image=False, page_indices=(1, 2))),
+ source,
+ output_root=tmp_path / "output",
+ page_range="2~3",
+ )
+ assert artifacts.page_indices == (1, 2)
+ assert artifacts.origin_pdf_path is not None
+ assert len(PdfReader(str(artifacts.origin_pdf_path)).pages) == 2
+ assert artifacts.layout_pdf_path is not None
+ assert len(PdfReader(str(artifacts.layout_pdf_path)).pages) == 2
+
+
+def test_run_artifact_paths_are_absolute_and_inside_output_root(tmp_path: Path) -> None:
+ """验证每次任务使用独立绝对目录并固定核心产物命名。"""
+ source = tmp_path / "复杂 文件名.pdf"
+ first = create_run_artifacts(source, tmp_path / "output")
+ second = create_run_artifacts(source, tmp_path / "output")
+ assert first.root != second.root
+ assert first.root.is_absolute()
+ assert first.source_path.name == "source.pdf"
+ assert first.middle_json_path.name == "middle_json.json"
+ assert first.markdown_path.name == "markdown.md"
+ assert first.structured_content_path.name == "structured_content.json"
+ for path in (
+ first.source_path,
+ first.middle_json_path,
+ first.markdown_path,
+ first.structured_content_path,
+ first.bundle_zip_path,
+ first.downloads_dir,
+ ):
+ assert path.is_absolute()
+ assert path.is_relative_to(first.root)
+
+
+def test_render_download_rejects_state_outside_allowed_root(tmp_path: Path) -> None:
+ """验证浏览器可控 State 不能读取 output root 之外的文件。"""
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(_pdf_bytes())
+ artifacts = persist_parse_result(
+ ParseResult(middle_json=_middle_json(with_image=False)),
+ source,
+ output_root=tmp_path / "output",
+ page_range="",
+ )
+ state = artifacts.as_state()
+ state["root"] = str(tmp_path / "outside")
+ with pytest.raises(ValueError, match="escapes output root"):
+ render_download(state, "pdf", allowed_root=tmp_path / "output")
+
+ state = artifacts.as_state()
+ state["stem"] = "../../escaped"
+ with pytest.raises(ValueError, match="Invalid Gradio artifact stem"):
+ render_download(state, "html", allowed_root=tmp_path / "output")
+ assert not (tmp_path / "escaped.html").exists()
+
+
+def test_gradio_file_types_page_range_and_header_follow_new_contract() -> None:
+ """验证完整扩展名、PDF-only 页码规则和复用后的 Header。"""
+ assert set(gradio_app._supported_file_types()) == {f".{extension}" for extension in PARSEABLE_EXTENSIONS}
+ assert gradio_app._effective_page_range("report.PDF", " 1~3,-1 ") == "1~3,-1"
+ assert gradio_app._effective_page_range("report.docx", "1~3") == ""
+ header = gradio_app._render_header(gradio_major_version=6)
+ assert "mineru-gradio6-header" in header
+ assert "mineru-header-popover mineru-model-popover" in header
+ assert "mineru-header-popover mineru-paper-popover" in header
+ assert "{{HEADER_" not in header
+
+
+def test_build_gradio_app_exposes_three_tabs_and_download_menu(tmp_path: Path) -> None:
+ """验证新 UI 不引入旧 backend 控件,并注册三个标签和下载事件。"""
+ capabilities = V1ServerCapabilities(
+ "http://127.0.0.1:1",
+ ("flash", "basic", "standard", "advanced"),
+ ("markdown", "middle_json", "structured_content", "zip"),
+ ("file_id", "url", "inline"),
+ )
+ app = build_gradio_app(
+ V1ArtifactClient(api_url=capabilities.base_url),
+ capabilities,
+ output_root=tmp_path,
+ enable_example=False,
+ )
+ tab_labels = [component.label for component in app.blocks.values() if component.__class__.__name__ == "Tab"]
+ assert tab_labels == ["Markdown 渲染", "Markdown 源码", "Structured Content 源码"]
+ download_labels = [component.label for component in app.blocks.values() if component.__class__.__name__ == "DownloadButton"]
+ assert download_labels == ["ZIP", "HTML", "DOCX", "LaTeX bundle", "EPUB", "PDF"]
+ download_buttons = [component for component in app.blocks.values() if component.__class__.__name__ == "DownloadButton"]
+ assert all(component.interactive is False for component in download_buttons)
+ file_inputs = [component for component in app.blocks.values() if component.__class__.__name__ == "File"]
+ assert len(file_inputs) == 1
+ assert file_inputs[0].file_count == "single"
+ assert set(file_inputs[0].file_types) == {f".{extension}" for extension in PARSEABLE_EXTENSIONS}
+ preview_handler = next(fn.fn for fn in app.fns.values() if fn.name == "update_file_preview")
+ assert preview_handler("report.pdf")[0]["interactive"] is True
+ non_pdf_page_update = preview_handler("report.docx")[0]
+ assert non_pdf_page_update["interactive"] is False
+ assert non_pdf_page_update["value"] == ""
+ assert sum(1 for dependency in app.config["dependencies"] if dependency.get("queue") is True) >= 7
+
+
+def test_gradio_conversion_forwards_page_range_and_enables_fresh_downloads(tmp_path: Path) -> None:
+ """验证转换事件透传 PDF page_range,并只在新结果完成后启用下载。"""
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(_pdf_bytes())
+
+ class FakeClient:
+ """记录 UI 传给 V1 client 的请求。"""
+
+ def __init__(self) -> None:
+ """初始化调用记录。"""
+ self.calls: list[tuple[Path, str, str]] = []
+
+ async def parse_file(
+ self,
+ path: Path,
+ *,
+ tier: str,
+ page_range: str,
+ status_callback: Any = None,
+ ) -> ParseResult:
+ """返回最小解析结果并记录页码。"""
+ self.calls.append((path, tier, page_range))
+ if status_callback is not None:
+ status_callback("Processing on server...")
+ return ParseResult(middle_json=_middle_json(with_image=False))
+
+ async def collect_updates(handler: Any) -> list[tuple[Any, ...]]:
+ """收集 Gradio 异步生成器的全部增量输出。"""
+ return [update async for update in handler(str(source), "flash", " 1 ")]
+
+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash",), ("zip",), ("file_id",))
+ client = FakeClient()
+ demo = build_gradio_app(
+ client, # type: ignore[arg-type]
+ capabilities,
+ output_root=tmp_path / "output",
+ enable_example=False,
+ )
+ convert_handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")
+ updates = asyncio.run(collect_updates(convert_handler))
+
+ assert client.calls == [(source.resolve(), "flash", "1")]
+ assert len(updates[-1]) == 15
+ assert updates[-1][8] is not None
+ assert all(update["interactive"] is True and update["value"] is None for update in updates[-1][-6:])
+ assert all(update["interactive"] is False and update["value"] is None for update in updates[0][-6:])
+
+
+def test_gradio_conversion_failure_clears_previous_downloads(tmp_path: Path) -> None:
+ """验证解析失败会清空结果 State 并禁用所有旧下载按钮。"""
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(_pdf_bytes())
+
+ class FailingClient:
+ """模拟 V1 解析失败。"""
+
+ async def parse_file(self, *_args: Any, **_kwargs: Any) -> ParseResult:
+ """抛出稳定的测试错误。"""
+ raise V1ArtifactError("boom", code="parse_failed")
+
+ async def final_update(handler: Any) -> tuple[Any, ...]:
+ """返回 Gradio 异步生成器的最后一次更新。"""
+ updates = [update async for update in handler(str(source), "flash", "")]
+ return updates[-1]
+
+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash",), ("zip",), ("file_id",))
+ demo = build_gradio_app(
+ FailingClient(), # type: ignore[arg-type]
+ capabilities,
+ output_root=tmp_path / "output",
+ enable_example=False,
+ )
+ convert_handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")
+ update = asyncio.run(final_update(convert_handler))
+
+ assert "Failed: boom" in update[0]
+ assert update[8] is None
+ assert all(item["interactive"] is False and item["value"] is None for item in update[-6:])
diff --git a/tests/unittest/test_v1_router.py b/tests/unittest/test_v1_router.py
index d8843690..f384fa31 100644
--- a/tests/unittest/test_v1_router.py
+++ b/tests/unittest/test_v1_router.py
@@ -862,7 +862,6 @@ def test_managed_router_worker_builds_new_api_server_command(tmp_path: Path) ->
assert ["--tier", "basic"] == command[command.index("--tier") : command.index("--tier") + 2]
assert ["--concurrency", "3"] == command[command.index("--concurrency") : command.index("--concurrency") + 2]
assert "--preload-models" in command
- assert "mineru.cli_old" not in " ".join(command)
@pytest.mark.parametrize(
@@ -1056,7 +1055,7 @@ def test_local_worker_replacement_invalidates_previous_generation_routes() -> No
def test_router_console_script_points_to_new_cli() -> None:
- """校验过渡 mineru-router console script 不再指向 cli_old。"""
+ """校验过渡 mineru-router console script 指向正式 Router CLI。"""
repo_root = Path(__file__).resolve().parents[2]
pyproject = tomllib.loads((repo_root / "pyproject.toml").read_text(encoding="utf-8"))