Skip to content

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

feat: update backend references from pipeline to hybrid and adjust related documentation

myhloliec8c462d1572
diff --git a/README.md b/README.md
index d758ae20..54d30644 100644
--- a/README.md
+++ b/README.md
@@ -71,7 +71,7 @@ MCP Server · LangChain / Dify / FastGPT native integration · 10+ domestic AI c
| Inference Backend | Best For |
|------------------|---------|
-| pipeline | Fast & stable, no hallucination, runs on CPU or GPU |
+| hybrid-engine --effort low | Fast local parsing, no VLM calls, runs on CPU or GPU |
| hybrid-engine | High accuracy, native text extraction, low hallucination, supports VLM acceleration ecosystem |
Domestic AI chips: Ascend · Cambricon · Enflame · MetaX · Moore Threads · Kunlunxin · Iluvatar · Hygon · Biren · T-Head
@@ -213,7 +213,7 @@ A WebUI developed based on Gradio, with a simple interface and only core parsing
<thead>
<tr>
<th rowspan="2">Parsing Backend</th>
- <th rowspan="2">pipeline</th>
+ <th rowspan="2">hybrid low</th>
<th colspan="2">*-engine</th>
<th colspan="2">*-http-client</th>
</tr>
@@ -325,9 +325,9 @@ If your device meets the GPU acceleration requirements in the table above, you c
```bash
mineru -p <input_path> -o <output_path>
```
-If your device does not meet the GPU acceleration requirements, you can specify the backend as `pipeline` to run in a pure CPU environment:
+If your device does not meet the GPU acceleration requirements, you can use Hybrid low to run without VLM calls:
```bash
-mineru -p <input_path> -o <output_path> -b pipeline
+mineru -p <input_path> -o <output_path> -b hybrid-engine --effort low
```
`mineru` currently supports local `PDF`, image, `DOCX`, `PPTX`, and `XLSX` file or directory inputs, and can be used for document parsing through the CLI, API, WebUI, and `mineru-router`. For detailed instructions, please refer to the [Usage Guide](https://opendatalab.github.io/MinerU/usage/).
diff --git a/README_zh-CN.md b/README_zh-CN.md
index c8489574..10ccdbba 100644
--- a/README_zh-CN.md
+++ b/README_zh-CN.md
@@ -69,7 +69,7 @@ MCP Server · LangChain / Dify / FastGPT 原生集成 · 10+ 国产算力适配
| 推理后端 | 适用场景 |
|--------------|-----------------------------|
-| pipeline | 快速稳定,无幻觉,CPU / GPU 均可运行 |
+| hybrid-engine --effort low | 本地快速解析,不调用 VLM,CPU / GPU 均可运行 |
| hybrid-engine| 高精度,原生文本提取,低幻觉,支持 VLM 加速生态 |
国产算力:昇腾 · 寒武纪 · 燧原 · 沐曦 · 摩尔线程 · 昆仑芯 · 天数智芯 · 瀚博 · 太初元碁 · 海光 · 平头哥
@@ -211,7 +211,7 @@ https://github.com/user-attachments/assets/4bea02c9-6d54-4cd6-97ed-dff14340982c
<thead>
<tr>
<th rowspan="2">解析后端</th>
- <th rowspan="2">pipeline</th>
+ <th rowspan="2">hybrid low</th>
<th colspan="2">*-engine</th>
<th colspan="2">*-http-client</th>
</tr>
@@ -331,9 +331,9 @@ MinerU提供了便捷的docker部署方式,这有助于快速搭建环境并
```bash
mineru -p <input_path> -o <output_path>
```
-如果您的设备不满足GPU加速条件,可以指定后端为`pipeline`,以在纯CPU环境下运行:
+如果您的设备不满足GPU加速条件,可以使用 Hybrid low,以在不调用 VLM 的模式下运行:
```bash
-mineru -p <input_path> -o <output_path> -b pipeline
+mineru -p <input_path> -o <output_path> -b hybrid-engine --effort low
```
当前 `mineru` 支持本地 `PDF / 图片 / DOCX / PPTX / XLSX` 文件或目录输入,并可通过命令行、API、WebUI、`mineru-router` 等多种方式进行文档解析,具体使用方法请参考[使用指南](https://opendatalab.github.io/MinerU/zh/usage/)。
diff --git a/docs/en/quick_start/index.md b/docs/en/quick_start/index.md
index fdc5dbd6..45b92daa 100644
--- a/docs/en/quick_start/index.md
+++ b/docs/en/quick_start/index.md
@@ -32,7 +32,7 @@ A WebUI developed based on Gradio, with a simple interface and only core parsing
<thead>
<tr>
<th rowspan="2" style="text-align:center; vertical-align:middle;">Parsing Backend</th>
- <th rowspan="2" style="text-align:center; vertical-align:middle;">pipeline</th>
+ <th rowspan="2" style="text-align:center; vertical-align:middle;">hybrid low</th>
<th colspan="2" style="text-align:center;">*-engine</th>
<th colspan="2" style="text-align:center;">*-http-client</th>
</tr>
@@ -143,9 +143,9 @@ If your device meets the GPU acceleration requirements in the table above, you c
```bash
mineru -p <input_path> -o <output_path>
```
-If your device does not meet the GPU acceleration requirements, you can specify the backend as `pipeline` to run in a pure CPU environment:
+If your device does not meet the GPU acceleration requirements, you can use Hybrid low to run without VLM calls:
```bash
-mineru -p <input_path> -o <output_path> -b pipeline
+mineru -p <input_path> -o <output_path> -b hybrid-engine --effort low
```
`mineru` currently supports local `PDF`, image, `DOCX`, `PPTX`, and `XLSX` file or directory inputs.
diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.md
index 5d3b50bb..9265139f 100644
--- a/docs/en/reference/output_files.md
+++ b/docs/en/reference/output_files.md
@@ -35,7 +35,7 @@ The following sections provide detailed descriptions of each file's purpose and
### Text Spans File (span.pdf)
> [!NOTE]
-> Only applicable to pipeline backend
+> Only generated when span visualization is explicitly enabled.
**File naming format**: `{original_filename}_span.pdf`
@@ -55,9 +55,9 @@ The following sections provide detailed descriptions of each file's purpose and
## Structured Data Files
> [!IMPORTANT]
-> The VLM backend output has significant changes in version 2.5 and is not backward-compatible with the pipeline backend. If you plan to build secondary development on structured outputs, please read this document carefully.
+> The current structured output contract uses `hybrid` and `office` backends. Legacy middle-json files marked with `_backend: "pipeline"` are no longer accepted by current readers.
-### Pipeline Backend Output Results
+### Hybrid Local Model Output Results
#### Model Inference Results (model.json)
@@ -115,7 +115,7 @@ The following sections provide detailed descriptions of each file's purpose and
| Field Name | Type | Description |
|------------|------|-------------|
| `pdf_info` | `list[dict]` | Array of parsing results for each page |
-| `_backend` | `string` | Parsing mode: `pipeline`, `vlm`, or `office` |
+| `_backend` | `string` | Parsing mode: `hybrid` or `office` |
| `_version_name` | `string` | MinerU version number |
##### Page Information Structure (pdf_info)
@@ -284,7 +284,7 @@ Level 1 blocks (table | image | chart)
]
}
],
- "_backend": "pipeline",
+ "_backend": "hybrid",
"_version_name": "0.6.1"
}
```
@@ -469,7 +469,7 @@ exact styles are represented by the child `text` spans.
]
```
-### VLM Backend Output Results
+### Hybrid Multimodal Output Results
#### Model Inference Results (model.json)
@@ -543,7 +543,7 @@ exact styles are represented by the child `text` spans.
**File naming format**: `{original_filename}_middle.json`
-Structure is broadly similar to the pipeline backend, but with these differences:
+Hybrid multimodal `middle.json` includes these extensions over the base block structure:
- `list` becomes a second‑level block, a new field `sub_type` distinguishes list categories:
* `text`: ordinary list
@@ -661,7 +661,7 @@ Structure is broadly similar to the pipeline backend, but with these differences
**File naming format**: `{original_filename}_content_list.json`
-Based on the pipeline format, with these VLM-specific extensions:
+Hybrid multimodal `content_list.json` includes these extensions:
- New `code` type with `sub_type` (`code` | `algorithm`):
* Fields: `code_body` (string), optional `code_caption` (list of strings)
@@ -672,7 +672,7 @@ Based on the pipeline format, with these VLM-specific extensions:
- All `discarded_blocks` entries are also output (e.g., headers, footers, page numbers, margin notes, page footnotes).
- Existing types (`image`, `table`, `text`, `equation`) remain unchanged.
- `bbox` still uses the 0–1000 normalized coordinate mapping.
-- Starting with 3.0, the VLM backend also emits `*_structured_content.json`; see the Structured Content section above for the shared structure.
+- Starting with 3.0, Hybrid multimodal output also emits `*_structured_content.json`; see the Structured Content section above for the shared structure.
##### Examples
diff --git a/docs/en/usage/advanced_cli_parameters.md b/docs/en/usage/advanced_cli_parameters.md
index 203543df..31e8bceb 100644
--- a/docs/en/usage/advanced_cli_parameters.md
+++ b/docs/en/usage/advanced_cli_parameters.md
@@ -17,7 +17,7 @@
> ```bash
> CUDA_VISIBLE_DEVICES=1 mineru -p <input_path> -o <output_path>
> ```
-> - This method works for all command-line invocations, including `mineru`, `mineru-openai-server`, `mineru-gradio`, `mineru-api`, and `mineru-router`, and it applies to both the `pipeline` and `vlm` backends.
+> - This method works for all command-line invocations, including `mineru`, `mineru-openai-server`, `mineru-gradio`, `mineru-api`, and `mineru-router`, and it applies to local Hybrid execution.
### Common Device Configuration Examples
> [!TIP]
diff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.md
index bf1cee14..2bd1c867 100644
--- a/docs/en/usage/cli_tools.md
+++ b/docs/en/usage/cli_tools.md
@@ -11,12 +11,12 @@ Options:
-p, --path PATH Input file path or directory (required)
-o, --output PATH Output directory (required)
--api-url TEXT MinerU FastAPI base URL; if omitted, `mineru` starts a temporary local `mineru-api`
- -m, --method [auto|txt|ocr] Parsing method: auto (default), txt, ocr (pipeline and hybrid* backend only)
- -b, --backend [pipeline|hybrid-engine|hybrid-http-client]
+ -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 [low|medium|high] Hybrid parsing effort (default: medium)
-l, --lang [ch|ch_server|korean|ta|te|ka|th|el|arabic|east_slavic|cyrillic|devanagari]
- Specify document language (improves OCR accuracy, pipeline and hybrid* backend only)
+ 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)
@@ -118,7 +118,7 @@ Here are the environment variables and their descriptions:
- `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 `pipeline` backend.
+ * Only effective for local Hybrid model execution.
- `MINERU_TABLE_ENABLE`:
* Used to enable table parsing
diff --git a/docs/en/usage/quick_usage.md b/docs/en/usage/quick_usage.md
index 5af0fc1a..7ffd8896 100644
--- a/docs/en/usage/quick_usage.md
+++ b/docs/en/usage/quick_usage.md
@@ -154,5 +154,5 @@ Here are some available configuration options:
- `models-dir`:
* Used to specify local model storage directory
- * Please specify model directories for `pipeline` and `vlm` backends separately.
+ * 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`.
diff --git a/docs/next/glossary.md b/docs/next/glossary.md
index f3b4bc37..ff7d6618 100644
--- a/docs/next/glossary.md
+++ b/docs/next/glossary.md
@@ -82,7 +82,7 @@
- 对普通用户显示 `tier`,不要把 `backend` 作为主选择项。
- `backend` 只应暴露在 kit 或核心开发层,例如 `mineru-kit parse --backend`。
- Tool SDK 的直接 parser 可以接受专家 `backend` 参数;API-backed parser、Doclib SDK、doclib server API 和 v1 API 不应要求用户理解或选择 `backend`。
-- `mineru-kit api-server` 启动参数应优先使用 `--tier`;也可以暴露高级 `--backend` 覆盖,用于选择该进程内部加载的 parser backend。`--backend` 使用 `pipeline`、`vlm-*` 或 `hybrid-*`,不使用裸 `vlm` / `hybrid`。启动后的 HTTP API 只暴露 `tier`。
+- `mineru-kit api-server` 启动参数应优先使用 `--tier`;也可以暴露高级 `--backend` 覆盖,用于选择该进程内部加载的 parser backend。`--backend` 公开使用 `hybrid-*`,旧 `pipeline` / `vlm-*` 仅作为隐藏兼容输入。启动后的 HTTP API 只暴露 `tier`。
- Middle JSON 中 `_meta.backend` 表示产物来源实现,不表示用户请求的 `tier`。
- `backend` 不应承担隐私语义;隐私由 `privacy` / `remote` / `via` 描述。
@@ -108,7 +108,7 @@
|--------|------|
| `parse()` | Tool SDK 的便捷函数 |
| `DocumentParser` | Parser 抽象接口 |
-| `PdfPipelineParser` | 调用 pipeline backend 的 parser |
+| `PdfPipelineParser` | 旧 SDK 兼容类,内部委托 Hybrid low |
| `PdfVlmParser` | 调用 VLM backend 的 parser |
| `PdfHybridParser` | 调用 hybrid backend 的 parser |
| `DocxParser` / `PptxParser` / `XlsxParser` | Office parser |
diff --git a/docs/next/middle-json/envelope.md b/docs/next/middle-json/envelope.md
index 6db138ea..532a666a 100644
--- a/docs/next/middle-json/envelope.md
+++ b/docs/next/middle-json/envelope.md
@@ -24,7 +24,7 @@
"pages": [],
"_meta": {
"mineru_version": "2.x",
- "backend": "pipeline",
+ "backend": "hybrid",
"tier": "standard",
"file": {
"sha256": "...",
@@ -63,7 +63,7 @@
| 字段 | 类型 | 必带 | 说明 |
|------|------|:--:|------|
| `mineru_version` | string | 是 | 生成该结果的 MinerU 版本。 |
-| `backend` | string | 是 | `pipeline`、`vlm`、`hybrid`、`office`、`html`、`flash`。 |
+| `backend` | string | 是 | `hybrid`、`office`、`html`、`flash`。 |
| `tier` | string 或 null | 是 | `flash`、`standard`、`pro` 的解析结果语义;未经过 tier 解析的工具层结果可为 `null`。 |
| `file` | object | 是 | 文件级信息。 |
| `features` | object | 是 | 本次解析启用的能力。 |
@@ -143,11 +143,13 @@ models 也是开放字典。字段粒度可以随 backend 增加。
```json
{
"pdf_info": [],
- "_backend": "pipeline",
+ "_backend": "hybrid",
"_version_name": "2.x"
}
```
+旧产物中的 `_backend: "pipeline"` 不再属于当前兼容输入。
+
历史文件的离线 migration 可转换为:
- `pages = pdf_info`
diff --git a/docs/next/middle-json/structured-content-schema.md b/docs/next/middle-json/structured-content-schema.md
index 3b91abe1..35734904 100644
--- a/docs/next/middle-json/structured-content-schema.md
+++ b/docs/next/middle-json/structured-content-schema.md
@@ -71,7 +71,7 @@ Structured Content 是从 Middle JSON render 得到的结构化内容 JSON。它
```json
{
"tier": "standard",
- "backend": "pipeline",
+ "backend": "hybrid",
"version": "3.1.14"
}
```
diff --git a/docs/next/sdk/parser.md b/docs/next/sdk/parser.md
index 39728e79..cdee4b00 100644
--- a/docs/next/sdk/parser.md
+++ b/docs/next/sdk/parser.md
@@ -33,7 +33,7 @@
| `DocumentParser` | abstract class | 所有 parser 的统一接口。 |
| `ParseResult` | dataclass | 解析结果对象。 |
| `PdfFlashParser` | class | CPU-only PDF/image 快速解析。 |
-| `PdfPipelineParser` | class | pipeline backend。 |
+| `PdfPipelineParser` | class | 旧 SDK 兼容类,内部委托 Hybrid low。 |
| `PdfVlmParser` | class | VLM backend。 |
| `PdfHybridParser` | class | hybrid backend。 |
| `DocxParser` | class | DOCX parser。 |
@@ -105,9 +105,9 @@ class DocumentParser:
| Parser | 输入 | 主要 backend | 说明 |
|--------|------|--------------|------|
| `PdfFlashParser` | PDF/image | flash | CPU-only,快速但质量最低,主要用于发现和索引。 |
-| `PdfPipelineParser` | PDF/image | pipeline | 本地 pipeline 解析。 |
+| `PdfPipelineParser` | PDF/image | hybrid low | 旧 SDK 兼容类,等价于 `PdfHybridParser(effort="low")`。 |
| `PdfVlmParser` | PDF/image | VLM | VLM 解析,可通过 server URL 委托。 |
-| `PdfHybridParser` | PDF/image | hybrid | pipeline + VLM 混合解析。 |
+| `PdfHybridParser` | PDF/image | hybrid | 本地小模型 + VLM 混合解析。 |
| `DocxParser` | DOCX | office | Office 文档解析。 |
| `PptxParser` | PPTX | office | Office 文档解析。 |
| `XlsxParser` | XLSX | office | Office 文档解析。 |
@@ -120,7 +120,7 @@ class DocumentParser:
| Tier | 默认 backend | 说明 |
|------|--------------|------|
| `flash` | `flash` | 快速 CPU-only。 |
-| `standard` | `pipeline` | 消费级硬件可用的模型/规则组合。 |
+| `standard` | `hybrid-engine` + `effort="low"` | 消费级硬件可用的本地小模型组合。 |
| `pro` | hybrid 默认高质量 backend | 最高质量。 |
`tier=None` 表示使用默认选择策略,选择可用的最高非 `flash` tier。只有用户显式请求 `tier="flash"` 或 `backend="flash"` 时,才返回 flash 结果。
@@ -132,7 +132,7 @@ class DocumentParser:
目标:
- `from mineru.parser import parse, ParseResult` 应足够轻。
-- `PdfPipelineParser` 只在执行 pipeline 时加载 pipeline backend。
+- `PdfPipelineParser` 仅作为旧 SDK 类名保留,内部走 Hybrid low,不再加载独立 pipeline backend。
- `PdfVlmParser` / `PdfHybridParser` 只在执行 VLM/hybrid 时加载对应 backend。
- Office parser 可以在构造时绑定 analyze function,但不应在模块 import 时加载重依赖。
@@ -148,9 +148,9 @@ print(result.markdown())
高级用法:
```python
-from mineru.parser import PdfPipelineParser
+from mineru.parser import PdfHybridParser
-with PdfPipelineParser(method="txt", lang="ch") as parser:
+with PdfHybridParser(method="txt", lang="ch", effort="low") as parser:
result = parser.parse("report.pdf", page_range="1~10")
images = result.images()
```
diff --git a/docs/next/sdk/tiers-errors.md b/docs/next/sdk/tiers-errors.md
index 59816dd9..cd17a7ff 100644
--- a/docs/next/sdk/tiers-errors.md
+++ b/docs/next/sdk/tiers-errors.md
@@ -44,7 +44,7 @@ SDK 中未指定 tier,或 Python 调用传 `tier=None` 时,必须遵循:
| Tier | Backend |
|------|---------|
| `flash` | `flash` |
-| `standard` | `pipeline` |
+| `standard` | `hybrid-engine` + `effort="low"` |
| `pro` | hybrid 默认高质量 backend |
`tier=None` 使用默认选择策略,结果为 `pro` 或 `standard`。
diff --git a/docs/next/tiers.md b/docs/next/tiers.md
index 1373338e..a9b32bf2 100644
--- a/docs/next/tiers.md
+++ b/docs/next/tiers.md
@@ -76,13 +76,13 @@ P0 不做基于启发式的自动提示或自动排队升级。watch 使用 `fla
## 5. Standard
-`standard` 是本地主力解析 tier,当前使用 `pipeline` 后端。`pipeline` 是一系列小模型串联的解析方案,不加载大的 VLM 模型。
+`standard` 是本地主力解析 tier,当前使用 `hybrid-engine` 的 `low` effort。它是一系列本地小模型串联的解析方案,不加载大的 VLM 模型。
这类用户可能拥有 GPU 或加速器,但显存和算力有限。它们不一定完全跑不动 `pro`,但运行 `pro` 通常会很慢。因此 `standard` 是一个算力消耗较低、质量中等、仍然基于模型的解析方案。
`standard` 的核心价值是本地隐私解析:当用户不接受把文档发送到远端解析,同时硬件又不是特别高端时,`standard` 应成为本地可用的最佳默认方案。
-`standard` 的最低硬件基线按 `pipeline` 后端定义:
+`standard` 的最低硬件基线按 Hybrid low 本地小模型执行定义:
| 平台 | 最低硬件基线 |
|------|--------------|
diff --git a/docs/next/workflows.md b/docs/next/workflows.md
index 1526919e..7d2b523d 100644
--- a/docs/next/workflows.md
+++ b/docs/next/workflows.md
@@ -439,9 +439,9 @@ result = parse("report.pdf", tier="standard")
或使用具体 parser:
```python
-from mineru.parser import PdfPipelineParser
+from mineru.parser import PdfHybridParser
-with PdfPipelineParser() as parser:
+with PdfHybridParser(effort="low") as parser:
result = parser.parse("report.pdf")
```
diff --git a/docs/zh/quick_start/index.md b/docs/zh/quick_start/index.md
index 358b17d6..21d571bb 100644
--- a/docs/zh/quick_start/index.md
+++ b/docs/zh/quick_start/index.md
@@ -32,7 +32,7 @@
<thead>
<tr>
<th rowspan="2" style="text-align:center; vertical-align:middle;">解析后端</th>
- <th rowspan="2" style="text-align:center; vertical-align:middle;">pipeline</th>
+ <th rowspan="2" style="text-align:center; vertical-align:middle;">hybrid low</th>
<th colspan="2" style="text-align:center;">*-engine</th>
<th colspan="2" style="text-align:center;">*-http-client</th>
</tr>
@@ -154,9 +154,9 @@ MinerU提供了便捷的docker部署方式,这有助于快速搭建环境并
```bash
mineru -p <input_path> -o <output_path>
```
-如果您的设备不满足GPU加速条件,可以指定后端为`pipeline`,以在纯CPU环境下运行:
+如果您的设备不满足GPU加速条件,可以使用 Hybrid low,以在不调用 VLM 的模式下运行:
```bash
-mineru -p <input_path> -o <output_path> -b pipeline
+mineru -p <input_path> -o <output_path> -b hybrid-engine --effort low
```
当前 `mineru` 支持本地 `PDF / 图片 / DOCX / PPTX / XLSX` 文件或目录输入。
diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.md
index a02a9eb8..a88c049e 100644
--- a/docs/zh/reference/output_files.md
+++ b/docs/zh/reference/output_files.md
@@ -35,7 +35,7 @@
### 文本片段文件 (span.pdf)
> [!NOTE]
-> 仅适用于 pipeline 后端
+> 仅在显式启用 span 可视化时生成。
**文件命名格式**:`{原文件名}_span.pdf`
@@ -55,9 +55,9 @@
## 结构化数据文件
> [!IMPORTANT]
-> 2.5版本vlm后端的输出存在较大变化,与pipeline版本存在不兼容情况,如需基于结构化输出进行二次开发,请仔细阅读本文档内容。
+> 当前结构化输出合约仅使用 `hybrid` 和 `office` 后端。旧 middle-json 中标记 `_backend: "pipeline"` 的产物不再被当前读取逻辑兼容。
-### pipeline 后端 输出结果
+### Hybrid 本地模型输出结果
#### 模型推理结果 (model.json)
@@ -115,7 +115,7 @@
| 字段名 | 类型 | 说明 |
|--------|------|------|
| `pdf_info` | `list[dict]` | 每一页的解析结果数组 |
-| `_backend` | `string` | 解析模式:`pipeline`、`vlm` 或 `office` |
+| `_backend` | `string` | 解析模式:`hybrid` 或 `office` |
| `_version_name` | `string` | MinerU 版本号 |
##### 页面信息结构 (pdf_info)
@@ -284,7 +284,7 @@
]
}
],
- "_backend": "pipeline",
+ "_backend": "hybrid",
"_version_name": "0.6.1"
}
```
@@ -478,7 +478,7 @@
]
```
-### VLM 后端 输出结果
+### Hybrid 多模态输出结果
#### 模型推理结果 (model.json)
@@ -486,7 +486,7 @@
##### 文件格式说明
-- 该文件为 VLM 模型的原始输出结果,包含两层嵌套list,外层表示页面,内层表示该页的内容块
+- 该文件为 Hybrid 多模态模型的原始输出结果,包含两层嵌套list,外层表示页面,内层表示该页的内容块
- 每个内容块都是一个dict,包含 `type`、`bbox`、`angle`、`content` 字段
@@ -569,7 +569,7 @@
**文件命名格式**:`{原文件名}_middle.json`
##### 文件格式说明
-vlm 后端的 middle.json 文件结构与 pipeline 后端类似,但存在以下差异:
+Hybrid 多模态 `middle.json` 在基础块结构上包含以下扩展:
- list变成二级block,增加`sub_type`字段区分list类型:
* `text`(文本类型)
@@ -760,7 +760,7 @@ vlm 后端的 middle.json 文件结构与 pipeline 后端类似,但存在以
**文件命名格式**:`{原文件名}_content_list.json`
##### 文件格式说明
-vlm 后端的 content_list.json 文件结构与 pipeline 后端类似,伴随本次middle.json的变化,做了以下调整:
+Hybrid 多模态 `content_list.json` 包含以下扩展:
- 新增`code`类型,code类型包含两种"sub_type":
* 分别是`code`和`algorithm`
@@ -779,7 +779,7 @@ vlm 后端的 content_list.json 文件结构与 pipeline 后端类似,伴随
* `page_number`
* `aside_text`
* `page_footnote`
-- 3.0 起,vlm 后端也会同时输出 `*_structured_content.json`,其通用结构见上文“通用结构化内容”。
+- 3.0 起,Hybrid 多模态输出也会同时输出 `*_structured_content.json`,其通用结构见上文“通用结构化内容”。
##### 示例数据
- code 类型 content
diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.md
index 99442d66..53a5e5e4 100644
--- a/docs/zh/usage/cli_tools.md
+++ b/docs/zh/usage/cli_tools.md
@@ -11,12 +11,12 @@ Options:
-p, --path PATH 输入文件路径或目录(必填)
-o, --output PATH 输出目录(必填)
--api-url TEXT MinerU FastAPI 服务地址;不传时自动拉起本地临时 mineru-api
- -m, --method [auto|txt|ocr] 解析方法:auto(默认)、txt、ocr(仅用于 pipeline 与 hybrid* 后端)
- -b, --backend [pipeline|hybrid-engine|hybrid-http-client]
+ -m, --method [auto|txt|ocr] 解析方法:auto(默认)、txt、ocr(仅用于 hybrid* 后端)
+ -b, --backend [hybrid-engine|hybrid-http-client]
解析后端(默认为 hybrid-engine)
--effort [low|medium|high] Hybrid 解析强度(默认:medium)
-l, --lang [ch|ch_server|korean|ta|te|ka|th|el|arabic|east_slavic|cyrillic|devanagari]
- 指定文档语言(可提升 OCR 准确率,仅用于 pipeline 与 hybrid* 后端)
+ 指定文档语言(可提升 OCR 准确率,仅用于 hybrid* 后端)
-u, --url TEXT 当使用 http-client 时,传给服务端后端的 OpenAI 兼容地址
-s, --start INTEGER 开始解析的页码(从 0 开始)
-e, --end INTEGER 结束解析的页码(从 0 开始)
@@ -109,7 +109,7 @@ MinerU命令行工具的某些参数存在相同功能的环境变量配置,
- `MINERU_FORMULA_CH_SUPPORT`:
* 用于启用中文公式解析优化(实验性功能)
* 默认为`false`,可通过环境变量设置为`true`来启用中文公式解析优化。
- * 仅对`pipeline`后端生效。
+ * 仅对本地 Hybrid 模型执行生效。
- `MINERU_TABLE_ENABLE`:
* 用于启用表格解析
diff --git a/docs/zh/usage/quick_usage.md b/docs/zh/usage/quick_usage.md
index f214ff76..0fc4ff3e 100644
--- a/docs/zh/usage/quick_usage.md
+++ b/docs/zh/usage/quick_usage.md
@@ -153,5 +153,5 @@ MinerU 现已实现开箱即用,但也支持通过配置文件扩展功能。
```
- `models-dir`:
- * 用于指定本地模型存储目录,请为`pipeline`和`vlm`后端分别指定模型目录,
+ * 用于指定本地模型存储目录,请分别指定本地小模型 bundle(`models-dir.pipeline`)和 VLM bundle(`models-dir.vlm`)的模型目录,
* 指定目录后您可通过配置环境变量`export MINERU_MODEL_SOURCE=local`来使用本地模型。
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 01398218..35ade568 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -35,14 +35,14 @@ from ...utils.pdf_document import PDFDocument
from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_bytes_range
from ...utils.bbox_utils import normalize_to_int_bbox
from ...utils.pdf_image_tools import get_crop_np_img
-from ..pipeline.model_init import (
+from ..local_model_runtime import (
+ AtomicModel,
HybridModelSingleton,
MineruHybridModel,
run_layout_inference,
run_mfr_inference,
run_ocr_inference,
)
-from ..pipeline.model_list import AtomicModel
from ..utils.boxbase import calculate_overlap_area_2_minbox_area_ratio
from ..utils.middle_json_utils import append_pages
from ..utils.runtime_utils import exclude_progress_bar_idle_time
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index d3f0e50e..5e97b926 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -12,7 +12,7 @@ from ...utils.image_payload import ImagePayloadCache
from ...utils.pdf_document import PDFPage
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ...utils.backend_options import validate_effort
-from ..pipeline.model_init import MineruHybridModel
+from ..local_model_runtime import MineruHybridModel
from ..utils.formula_number import optimize_hybrid_formula_number_blocks
from ..utils.middle_json_utils import apply_post_ocr
from ..utils.para_block_utils import (
@@ -148,7 +148,7 @@ def _normalize_split_title_blocks(pages: list[PageInfo]) -> None:
def apply_server_side_postprocess(
pages: list[PageInfo], hybrid_pipeline_model: MineruHybridModel, _ocr_enable: bool, _vlm_ocr_enable: bool
) -> None:
- """执行 Hybrid 只能在服务端完成的 post-OCR,避免客户端依赖 pipeline OCR 模型。"""
+ """执行 Hybrid 只能在服务端完成的 post-OCR,避免客户端依赖本地 OCR 模型。"""
if not (_vlm_ocr_enable or _ocr_enable):
_apply_post_ocr(pages, hybrid_pipeline_model)
diff --git a/mineru/backend/pipeline/model_init.py b/mineru/backend/local_model_runtime.py
similarity index 85%
rename from mineru/backend/pipeline/model_init.py
rename to mineru/backend/local_model_runtime.py
index f10c527e..15e41ff6 100644
--- a/mineru/backend/pipeline/model_init.py
+++ b/mineru/backend/local_model_runtime.py
@@ -1,3 +1,5 @@
+"""Hybrid 与本地小模型共享的运行时初始化模块。"""
+
# Copyright (c) Opendatalab. All rights reserved.
from __future__ import annotations
@@ -9,34 +11,46 @@ from typing import Any
import torch
from loguru import logger
-from ...model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
-from ...model.mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizer
-from ...model.mfr.unimernet.Unimernet import UnimernetModel
-from ...model.ocr.pytorch_paddle import PytorchPaddleOCR
-from ...model.table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel
-from ...model.table.cls.paddle_table_cls import PaddleTableClsModel
-from ...model.table.rec.slanet_plus.main import PaddleTableModel
-from ...model.table.rec.unet_table.main import UnetTableModel
-from ...utils.config_reader import get_device
-from ...utils.enum_class import ModelPath
-from ...utils.models_download_utils import auto_download_and_get_model_root_path
-from ...utils.ocr_language import normalize_ocr_model_lang
-from .model_list import AtomicModel
-
-PIPELINE_MODEL_INIT_LOCK = threading.RLock()
-# 这些锁保护 pipeline 与 hybrid 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。
-PIPELINE_LAYOUT_INFERENCE_LOCK = threading.RLock()
-PIPELINE_MFR_INFERENCE_LOCK = threading.RLock()
-PIPELINE_OCR_INFERENCE_LOCK = threading.RLock()
-# 临时关闭 pipeline/hybrid 共享推理阶段锁;需要回滚实验时可通过环境变量重新打开。
-PIPELINE_INFERENCE_LOCKS_ENABLED = os.getenv("MINERU_ENABLE_PIPELINE_INFERENCE_LOCKS", "False").lower() in ["true", "1", "yes"]
+from ..model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
+from ..model.mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizer
+from ..model.mfr.unimernet.Unimernet import UnimernetModel
+from ..model.ocr.pytorch_paddle import PytorchPaddleOCR
+from ..model.table.cls.mineru_table_ori_cls import MineruTableOrientationClsModel
+from ..model.table.cls.paddle_table_cls import PaddleTableClsModel
+from ..model.table.rec.slanet_plus.main import PaddleTableModel
+from ..model.table.rec.unet_table.main import UnetTableModel
+from ..utils.config_reader import get_device
+from ..utils.enum_class import ModelPath
+from ..utils.models_download_utils import auto_download_and_get_model_root_path
+from ..utils.ocr_language import normalize_ocr_model_lang
+
+
+class AtomicModel:
+ """本地原子模型名称集合,供 Hybrid low 和共享模型单例统一索引。"""
+
+ Layout = "layout"
+ MFD = "mfd"
+ MFR = "mfr"
+ OCR = "ocr"
+ WirelessTable = "wireless_table"
+ WiredTable = "wired_table"
+ TableCls = "table_cls"
+ TableOrientationCls = "table_ori_cls"
+
+LOCAL_MODEL_INIT_LOCK = threading.RLock()
+# 这些锁保护 Hybrid low/medium/high 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。
+LOCAL_MODEL_LAYOUT_INFERENCE_LOCK = threading.RLock()
+LOCAL_MODEL_MFR_INFERENCE_LOCK = threading.RLock()
+LOCAL_MODEL_OCR_INFERENCE_LOCK = threading.RLock()
+# 临时关闭共享推理阶段锁;保留旧环境变量名,避免已有部署配置失效。
+LOCAL_MODEL_INFERENCE_LOCKS_ENABLED = os.getenv("MINERU_ENABLE_PIPELINE_INFERENCE_LOCKS", "False").lower() in ["true", "1", "yes"]
def _run_with_inference_lock(
inference_lock: threading.RLock, inference_callable: Callable[..., Any], *args: Any, **kwargs: Any
) -> object:
"""按实验开关决定是否在指定推理锁内执行真实 native 模型调用。"""
- if not PIPELINE_INFERENCE_LOCKS_ENABLED:
+ if not LOCAL_MODEL_INFERENCE_LOCKS_ENABLED:
return inference_callable(*args, **kwargs)
with inference_lock:
@@ -45,17 +59,17 @@ def _run_with_inference_lock(
def run_layout_inference(inference_callable: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""按实验开关执行共享 Layout 模型调用。"""
- return _run_with_inference_lock(PIPELINE_LAYOUT_INFERENCE_LOCK, inference_callable, *args, **kwargs)
+ return _run_with_inference_lock(LOCAL_MODEL_LAYOUT_INFERENCE_LOCK, inference_callable, *args, **kwargs)
def run_mfr_inference(inference_callable: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""按实验开关执行共享 MFR 模型调用。"""
- return _run_with_inference_lock(PIPELINE_MFR_INFERENCE_LOCK, inference_callable, *args, **kwargs)
+ return _run_with_inference_lock(LOCAL_MODEL_MFR_INFERENCE_LOCK, inference_callable, *args, **kwargs)
def run_ocr_inference(inference_callable: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""按实验开关执行共享 OCR native 模型调用。"""
- return _run_with_inference_lock(PIPELINE_OCR_INFERENCE_LOCK, inference_callable, *args, **kwargs)
+ return _run_with_inference_lock(LOCAL_MODEL_OCR_INFERENCE_LOCK, inference_callable, *args, **kwargs)
MFR_MODEL = os.getenv("MINERU_FORMULA_CH_SUPPORT", "False")
@@ -139,7 +153,7 @@ def ocr_model_init(
class AtomModelSingleton:
_instance: AtomModelSingleton | None = None
_models: dict[object, object] = {}
- _lock: threading.RLock = PIPELINE_MODEL_INIT_LOCK
+ _lock: threading.RLock = LOCAL_MODEL_INIT_LOCK
def __new__(cls, *args: Any, **kwargs: Any) -> AtomModelSingleton:
with cls._lock:
@@ -272,7 +286,7 @@ class MineruPipelineModel:
class HybridModelSingleton:
_instance: HybridModelSingleton | None = None
_models: dict[object, object] = {}
- _lock: threading.RLock = PIPELINE_MODEL_INIT_LOCK
+ _lock: threading.RLock = LOCAL_MODEL_INIT_LOCK
def __new__(cls, *args: Any, **kwargs: Any) -> HybridModelSingleton:
with cls._lock:
diff --git a/mineru/backend/pipeline/__init__.py b/mineru/backend/pipeline/__init__.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/backend/pipeline/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/backend/pipeline/batch_analyze.py b/mineru/backend/pipeline/batch_analyze.py
deleted file mode 100644
index b3baee05..00000000
--- a/mineru/backend/pipeline/batch_analyze.py
+++ /dev/null
@@ -1,975 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import base64
-import html
-import re
-from collections import defaultdict
-from typing import Any
-
-import cv2
-import numpy as np
-from loguru import logger
-from PIL import Image
-from tqdm import tqdm
-
-from ...types import BBox
-from ...utils.bbox_utils import normalize_to_int_bbox
-from ...utils.config_reader import (
- get_formula_enable,
- get_ocr_det_mask_inline_formula_enable,
- get_table_enable,
-)
-from ...utils.model_utils import clean_vram, crop_img, get_res_list_from_layout_res
-from ...utils.ocr_utils import (
- OcrConfidence,
- get_adjusted_mfdetrec_res,
- get_ocr_result_list,
- get_rotate_crop_image_for_text_rec,
- mask_formula_regions_for_ocr_det,
- merge_det_boxes,
- sorted_boxes,
- update_det_boxes,
-)
-from ...utils.pdf_image_tools import get_crop_np_img
-from .model_init import (
- AtomModelSingleton,
- run_layout_inference,
- run_mfr_inference,
- run_ocr_inference,
-)
-from .model_list import AtomicModel
-from .pipeline_analyze import ModelSingleton
-
-LAYOUT_BASE_BATCH_SIZE = 1
-MFR_BASE_BATCH_SIZE = 16
-OCR_DET_BASE_BATCH_SIZE = 8
-TABLE_Wired_Wireless_CLS_BATCH_SIZE = 16
-TABLE_OCR_REC_SINGLE_CHAR_REPLACEMENTS = {
- "香": "否",
- "哦樂": "哦",
-}
-TABLE_OCR_REC_REGEX_REPLACEMENTS = (
- # 仅规范化完整的“单个数字 + 號”,避免影响“10號”“第6號”等普通文本。
- (re.compile(r"^([0-9])號$"), r"\1"),
-)
-
-
-class BatchAnalyze:
- def __init__(
- self,
- model_manager: ModelSingleton,
- batch_ratio: int,
- formula_enable: bool,
- table_enable: bool,
- enable_ocr_det_batch: bool = True,
- table_ori_cls_batch_enabled: bool | None = None,
- text_ocr_det_batch_enabled: bool | None = None,
- table_ocr_det_batch_enabled: bool | None = None,
- mask_inline_formula_for_ocr_det: bool = True,
- ) -> None:
- self.batch_ratio = batch_ratio
- self.formula_enable = get_formula_enable(formula_enable)
- self.table_enable = get_table_enable(table_enable)
- self.model_manager = model_manager
- self.enable_ocr_det_batch = enable_ocr_det_batch
- self.table_ori_cls_batch_enabled = (
- enable_ocr_det_batch if table_ori_cls_batch_enabled is None else table_ori_cls_batch_enabled
- )
- self.text_ocr_det_batch_enabled = (
- enable_ocr_det_batch if text_ocr_det_batch_enabled is None else text_ocr_det_batch_enabled
- )
- self.table_ocr_det_batch_enabled = (
- enable_ocr_det_batch if table_ocr_det_batch_enabled is None else table_ocr_det_batch_enabled
- )
- self.mask_inline_formula_for_ocr_det = get_ocr_det_mask_inline_formula_enable(mask_inline_formula_for_ocr_det)
-
- @staticmethod
- def _apply_mask_boxes_to_image(
- bgr_image: np.ndarray,
- mask_boxes: list[dict[str, Any]] | None,
- ) -> np.ndarray:
- return mask_formula_regions_for_ocr_det(bgr_image, mask_boxes)
-
- def _get_masked_det_image(
- self,
- bgr_image: np.ndarray,
- mask_boxes: list[dict[str, Any]] | None,
- ) -> np.ndarray:
- if not self.mask_inline_formula_for_ocr_det:
- return bgr_image
- return self._apply_mask_boxes_to_image(bgr_image, mask_boxes)
-
- def _build_table_ocr_det_items(
- self,
- table_res_list_all_page: list[dict[str, Any]],
- ) -> list[dict[str, Any]]:
- """构造表格 OCR-det 输入项,保留原图、遮罩图和回填所需元数据。"""
- table_det_items = []
- for index, table_res_dict in enumerate(table_res_list_all_page):
- bgr_image = cv2.cvtColor(table_res_dict["table_img"], cv2.COLOR_RGB2BGR)
- table_inline_objects = (
- table_res_dict.get("table_inline_objects", [])
- if self._table_supports_inline_objects(table_res_dict)
- else []
- )
- inline_mask_boxes = [
- {"bbox": inline_object["table_rel_mask_bbox"]}
- for inline_object in table_inline_objects
- ]
- formula_mask_boxes = [
- {"bbox": inline_object["table_rel_mask_bbox"]}
- for inline_object in table_inline_objects
- if inline_object["kind"] == "formula"
- ]
- det_image = (
- self._apply_mask_boxes_to_image(bgr_image, inline_mask_boxes)
- if inline_mask_boxes
- else bgr_image
- )
- table_det_items.append(
- {
- "bgr_image": bgr_image,
- "det_image": det_image,
- "formula_mask_boxes": formula_mask_boxes,
- "lang": table_res_dict["lang"],
- "table_id": index,
- }
- )
- return table_det_items
-
- def _append_table_ocr_det_result(
- self,
- table_det_item: dict[str, Any],
- dt_boxes: Any,
- rec_img_lang_group: dict[str, list[dict[str, Any]]],
- ) -> None:
- """将单表 OCR-det 结果整理为 OCR-rec 输入,并保持表格回填顺序。"""
- if dt_boxes is None or len(dt_boxes) == 0:
- return
-
- ocr_result = dt_boxes
- formula_mask_boxes = table_det_item["formula_mask_boxes"]
- if formula_mask_boxes:
- ocr_result = update_det_boxes(ocr_result, formula_mask_boxes)
- if not ocr_result:
- return
-
- ocr_result = sorted_boxes(ocr_result)
- for dt_box in ocr_result:
- dt_box_array = np.asarray(dt_box, dtype=np.float32)
- rec_img_lang_group.setdefault(table_det_item["lang"], []).append(
- {
- "cropped_img": get_rotate_crop_image_for_text_rec(
- table_det_item["bgr_image"],
- dt_box_array.copy(),
- ),
- "dt_box": dt_box_array.copy(),
- "table_id": table_det_item["table_id"],
- }
- )
-
- def _collect_table_ocr_rec_inputs(
- self,
- atom_model_manager: Any,
- table_res_list_all_page: list[dict[str, Any]],
- ) -> dict[str, list[dict[str, Any]]]:
- """执行表格 OCR-det,并按语言收集后续 OCR-rec 所需的裁剪图片。"""
- rec_img_lang_group: dict[str, list[dict[str, Any]]] = defaultdict(list)
- det_ocr_engine = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- det_db_box_thresh=0.5,
- det_db_unclip_ratio=1.6,
- enable_merge_det_boxes=False,
- )
- table_det_items = self._build_table_ocr_det_items(table_res_list_all_page)
-
- if self.table_ocr_det_batch_enabled:
- det_images = [table_det_item["det_image"] for table_det_item in table_det_items]
- if det_images:
- det_batch_size = max(
- 1,
- min(len(det_images), self.batch_ratio * OCR_DET_BASE_BATCH_SIZE),
- )
- batch_results = run_ocr_inference(
- det_ocr_engine.text_detector.batch_predict,
- det_images,
- det_batch_size,
- tqdm_enable=True,
- tqdm_desc="Table-ocr det",
- )
- if len(batch_results) != len(table_det_items):
- raise ValueError("Table OCR det batch result count mismatch")
- for table_det_item, (dt_boxes, _) in zip(table_det_items, batch_results):
- self._append_table_ocr_det_result(table_det_item, dt_boxes, rec_img_lang_group)
- else:
- for table_det_item in tqdm(table_det_items, desc="Table-ocr det"):
- ocr_result = run_ocr_inference(
- det_ocr_engine.ocr,
- table_det_item["det_image"],
- rec=False,
- )[0]
- self._append_table_ocr_det_result(table_det_item, ocr_result, rec_img_lang_group)
-
- return rec_img_lang_group
-
- @staticmethod
- def _prune_empty_ocr_text_blocks(layout_res: list[dict[str, Any]], ocr_enable: bool) -> None:
- if not ocr_enable or not layout_res:
- return
-
- def keep_item(item: dict[str, Any]) -> bool:
- if item.get("label") != "ocr_text":
- return True
-
- text = item.get("text")
- if isinstance(text, str):
- return bool(text.strip())
- return bool(text)
-
- layout_res[:] = [item for item in layout_res if keep_item(item)]
-
- @staticmethod
- def _bbox_center(bbox: BBox) -> tuple[float, float]:
- return (float(bbox[0] + bbox[2]) / 2.0, float(bbox[1] + bbox[3]) / 2.0)
-
- @staticmethod
- def _is_point_in_bbox(point: tuple[float, float], bbox: BBox) -> bool:
- x, y = point
- return bbox[0] <= x <= bbox[2] and bbox[1] <= y <= bbox[3]
-
- @staticmethod
- def _bbox_intersection(bbox1: BBox, bbox2: BBox) -> BBox | None:
- x0 = max(float(bbox1[0]), float(bbox2[0]))
- y0 = max(float(bbox1[1]), float(bbox2[1]))
- x1 = min(float(bbox1[2]), float(bbox2[2]))
- y1 = min(float(bbox1[3]), float(bbox2[3]))
- if x1 <= x0 or y1 <= y0:
- return None
- return (x0, y0, x1, y1)
-
- @classmethod
- def _bbox_intersection_area(cls, bbox1: BBox, bbox2: BBox) -> float:
- overlap_bbox = cls._bbox_intersection(bbox1, bbox2)
- if overlap_bbox is None:
- return 0.0
- return float(overlap_bbox[2] - overlap_bbox[0]) * float(overlap_bbox[3] - overlap_bbox[1])
-
- @staticmethod
- def _bbox_to_relative_bbox(bbox: BBox, base_bbox: BBox) -> BBox:
- return (
- float(bbox[0]) - float(base_bbox[0]),
- float(bbox[1]) - float(base_bbox[1]),
- float(bbox[2]) - float(base_bbox[0]),
- float(bbox[3]) - float(base_bbox[1]),
- )
-
- @staticmethod
- def _bbox_to_quad(bbox: BBox) -> np.ndarray:
- x0, y0, x1, y1 = bbox
- return np.asarray([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.float32)
-
- @staticmethod
- def _encode_table_inline_image(np_img: np.ndarray, bbox: BBox) -> str:
- image_h, image_w = np_img.shape[:2]
- image_bbox = normalize_to_int_bbox(bbox, image_size=(image_h, image_w))
- if image_bbox is None:
- return ""
-
- x0, y0, x1, y1 = image_bbox
- if x1 <= x0 or y1 <= y0:
- return ""
-
- crop_rgb = np_img[y0:y1, x0:x1]
- if crop_rgb.size == 0:
- return ""
-
- crop_bgr = cv2.cvtColor(crop_rgb, cv2.COLOR_RGB2BGR)
- success, encoded = cv2.imencode(".jpg", crop_bgr)
- if not success:
- return ""
-
- b64_str = base64.b64encode(encoded.tobytes()).decode("ascii")
- return f"data:image/jpg;base64,{b64_str}"
-
- @staticmethod
- def _get_virtual_image_bbox(bbox: BBox, box_size: float = 10.0) -> BBox:
- center_x, center_y = BatchAnalyze._bbox_center(bbox)
- half_size = box_size / 2.0
- return (
- center_x - half_size,
- center_y - half_size,
- center_x + half_size,
- center_y + half_size,
- )
-
- @staticmethod
- def _table_supports_inline_objects(table_res_dict: dict[str, Any]) -> bool:
- return str(table_res_dict.get("rotate_label", "0")) == "0"
-
- @staticmethod
- def _apply_table_rotate_label(table_res_dict: dict[str, Any], rotate_label: str) -> None:
- """根据方向预测结果写回标签,并同步旋转无线和有线表格图片。"""
- rotate_label = str(rotate_label or "0")
- table_res_dict["rotate_label"] = rotate_label
-
- if rotate_label == "270":
- rotate_code = cv2.ROTATE_90_CLOCKWISE
- elif rotate_label == "90":
- rotate_code = cv2.ROTATE_90_COUNTERCLOCKWISE
- else:
- return
-
- table_res_dict["table_img"] = cv2.rotate(
- np.asarray(table_res_dict["table_img"]),
- rotate_code,
- )
- table_res_dict["wired_table_img"] = cv2.rotate(
- np.asarray(table_res_dict["wired_table_img"]),
- rotate_code,
- )
-
- @staticmethod
- def _sort_table_ocr_result(ocr_result: list[list]) -> None:
- if not ocr_result:
- return
-
- sorted_result = sorted(
- ocr_result,
- key=lambda item: (float(np.asarray(item[0])[0][1]), float(np.asarray(item[0])[0][0])),
- )
-
- for i in range(len(sorted_result) - 1):
- for j in range(i, -1, -1):
- cur_box = np.asarray(sorted_result[j][0], dtype=np.float32)
- next_box = np.asarray(sorted_result[j + 1][0], dtype=np.float32)
- if abs(float(next_box[0][1]) - float(cur_box[0][1])) < 10 and float(next_box[0][0]) < float(cur_box[0][0]):
- sorted_result[j], sorted_result[j + 1] = sorted_result[j + 1], sorted_result[j]
- else:
- break
-
- ocr_result[:] = sorted_result
-
- @staticmethod
- def _normalize_table_ocr_rec_text(text: str) -> str:
- """规范化表格 OCR rec 的已知误识别,避免后续表格模型消费错误文本。"""
- if not isinstance(text, str):
- return text
- if text in TABLE_OCR_REC_SINGLE_CHAR_REPLACEMENTS:
- return TABLE_OCR_REC_SINGLE_CHAR_REPLACEMENTS[text]
- for pattern, replacement in TABLE_OCR_REC_REGEX_REPLACEMENTS:
- match = pattern.fullmatch(text)
- if match:
- return match.expand(replacement)
- return text
-
- @classmethod
- def _extract_table_inline_objects(
- cls,
- layout_res: list[dict[str, Any]],
- np_img: np.ndarray,
- formula_enable: bool,
- ) -> dict[int, list[dict[str, Any]]]:
- image_h, image_w = np_img.shape[:2]
- image_size = (image_h, image_w)
-
- tables = []
- for res in layout_res:
- if res.get("label") != "table":
- continue
- table_bbox = normalize_to_int_bbox(res.get("bbox"), image_size=image_size)
- if table_bbox is None:
- continue
- tables.append((res, table_bbox))
-
- if not tables:
- return {}
-
- table_inline_objects = {id(table_res): [] for table_res, _ in tables}
- remove_ids = set()
- candidate_labels = {"image"}
- if formula_enable:
- candidate_labels.update({"inline_formula", "display_formula"})
-
- for layout_item in layout_res:
- label = layout_item.get("label")
- if label not in candidate_labels:
- continue
-
- item_bbox = normalize_to_int_bbox(layout_item.get("bbox"), image_size=image_size)
- if item_bbox is None:
- continue
-
- item_center = cls._bbox_center(item_bbox)
- matched_tables = []
- for table_res, table_bbox in tables:
- if not cls._is_point_in_bbox(item_center, table_bbox):
- continue
- overlap_area = cls._bbox_intersection_area(item_bbox, table_bbox)
- matched_tables.append((overlap_area, table_res, table_bbox))
-
- if not matched_tables:
- continue
-
- matched_tables.sort(key=lambda item: item[0], reverse=True)
- _, table_res, table_bbox = matched_tables[0]
- overlap_bbox = cls._bbox_intersection(item_bbox, table_bbox)
- if overlap_bbox is None:
- continue
-
- rel_overlap_bbox = cls._bbox_to_relative_bbox(overlap_bbox, table_bbox)
- score = float(layout_item.get("score", 1.0))
-
- if label == "image":
- image_src = cls._encode_table_inline_image(np_img, item_bbox)
- if not image_src:
- continue
- content = f'<img src="{image_src}"/>'
- token_bbox = cls._get_virtual_image_bbox(rel_overlap_bbox)
- kind = "image"
- else:
- latex = layout_item.get("latex", "")
- if not latex:
- continue
- content = f"<eq>{html.escape(latex)}</eq>"
- token_bbox = rel_overlap_bbox
- kind = "formula"
-
- table_inline_objects[id(table_res)].append(
- {
- "kind": kind,
- "page_bbox": item_bbox,
- "table_rel_mask_bbox": rel_overlap_bbox,
- "table_token_bbox": token_bbox,
- "content": content,
- "score": score,
- }
- )
- remove_ids.add(id(layout_item))
-
- if remove_ids:
- layout_res[:] = [item for item in layout_res if id(item) not in remove_ids]
-
- return table_inline_objects
-
- def __call__(self, images_with_extra_info: list[tuple[Image.Image, bool, str]]) -> list[list[dict[str, Any]]]:
- if len(images_with_extra_info) == 0:
- return []
-
- images_layout_res = []
-
- self.model = self.model_manager.get_model(
- lang=None,
- formula_enable=self.formula_enable,
- table_enable=self.table_enable,
- )
- atom_model_manager = AtomModelSingleton()
-
- pil_images = [image for image, _, _ in images_with_extra_info]
-
- np_images = [np.asarray(image) for image, _, _ in images_with_extra_info]
-
- # pp-doclayout_v2
- images_layout_res += run_layout_inference(
- self.model.layout_model.batch_predict,
- pil_images,
- batch_size=min(8, self.batch_ratio * LAYOUT_BASE_BATCH_SIZE),
- )
- # 清理显存
- clean_vram(self.model.device, vram_threshold=8)
-
- if self.formula_enable:
- images_mfd_res = []
- for layout_res in images_layout_res:
- page_formula_res = []
- for res in layout_res:
- if res.get("label") in ["display_formula", "inline_formula"]:
- res.setdefault("latex", "")
- page_formula_res.append(res)
- images_mfd_res.append(page_formula_res)
-
- # 公式识别
- images_formula_list = run_mfr_inference(
- self.model.mfr_model.batch_predict,
- images_mfd_res,
- np_images,
- batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,
- )
- mfr_count = 0
- for image_index in range(len(np_images)):
- mfr_count += len(images_formula_list[image_index])
- for formula_res, formula_with_latex in zip(images_mfd_res[image_index], images_formula_list[image_index]):
- formula_res["latex"] = formula_with_latex.get("latex", "")
-
- # 清理显存
- clean_vram(self.model.device, vram_threshold=8)
-
- else:
- for layout_res in images_layout_res:
- # 移除所有的"inline_formula"
- layout_res[:] = [res for res in layout_res if res.get("label") != "inline_formula"]
-
- ocr_res_list_all_page = []
- table_res_list_all_page = []
- for index in range(len(np_images)):
- _, ocr_enable, _lang = images_with_extra_info[index]
- layout_res = images_layout_res[index]
- np_img = np_images[index]
- table_inline_objects = (
- self._extract_table_inline_objects(
- layout_res,
- np_img,
- formula_enable=self.formula_enable,
- )
- if self.table_enable
- else {}
- )
-
- ocr_res_list, table_res_list, single_page_mfdetrec_res = get_res_list_from_layout_res(layout_res)
-
- ocr_res_list_all_page.append(
- {
- "ocr_res_list": ocr_res_list,
- "lang": _lang,
- "ocr_enable": ocr_enable,
- "np_img": np_img,
- "single_page_mfdetrec_res": single_page_mfdetrec_res,
- "layout_res": layout_res,
- }
- )
-
- for table_res in table_res_list:
-
- def get_crop_table_img(scale: float) -> np.ndarray:
- bbox = normalize_to_int_bbox([float(v) / float(scale) for v in table_res["bbox"]])
- if bbox is None:
- return np_img[0:0, 0:0]
- return get_crop_np_img(bbox, np_img, scale=scale)
-
- wireless_table_img = get_crop_table_img(scale=1)
- wired_table_img = get_crop_table_img(scale=10 / 3)
- table_page_bbox = normalize_to_int_bbox(
- table_res.get("bbox"),
- image_size=np_img.shape[:2],
- ) or [0, 0, 0, 0]
-
- table_res_list_all_page.append(
- {
- "table_res": table_res,
- "lang": _lang,
- "table_img": wireless_table_img,
- "wired_table_img": wired_table_img,
- "table_page_bbox": table_page_bbox,
- "table_inline_objects": table_inline_objects.get(id(table_res), []),
- }
- )
-
- # 表格识别 table recognition
- if self.table_enable:
- # 图片旋转批量处理
- table_orientation_cls_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.TableOrientationCls,
- )
- try:
- if self.table_ori_cls_batch_enabled:
- rotate_labels = table_orientation_cls_model.batch_predict(
- table_res_list_all_page,
- det_batch_size=self.batch_ratio * OCR_DET_BASE_BATCH_SIZE,
- )
- if len(rotate_labels) != len(table_res_list_all_page):
- raise ValueError("Table orientation batch prediction result count mismatch")
- for table_res, rotate_label in zip(table_res_list_all_page, rotate_labels):
- self._apply_table_rotate_label(table_res, rotate_label)
- else:
- for table_res in table_res_list_all_page:
- rotate_label = table_orientation_cls_model.predict(table_res["table_img"])
- self._apply_table_rotate_label(table_res, rotate_label)
- except Exception as e:
- logger.warning(f"Table orientation classification failed: {e}, using original image")
-
- # 表格分类
- table_cls_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.TableCls,
- )
- try:
- table_cls_model.batch_predict(table_res_list_all_page, batch_size=TABLE_Wired_Wireless_CLS_BATCH_SIZE)
- except Exception as e:
- logger.warning(f"Table classification failed: {e}, using default model")
-
- # OCR det 过程,默认使用 detector 内部分桶 batch,关闭开关时回退逐表单张路径。
- rec_img_lang_group = self._collect_table_ocr_rec_inputs(atom_model_manager, table_res_list_all_page)
-
- # OCR rec,按照语言分批处理
- for _lang, rec_img_list in rec_img_lang_group.items():
- if not rec_img_list:
- continue
- ocr_engine = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- det_db_box_thresh=0.5,
- det_db_unclip_ratio=1.6,
- lang=_lang,
- enable_merge_det_boxes=False,
- )
- cropped_img_list = [item["cropped_img"] for item in rec_img_list]
- ocr_res_list = run_ocr_inference(
- ocr_engine.ocr,
- cropped_img_list,
- det=False,
- tqdm_enable=True,
- tqdm_desc=f"Table-ocr rec {_lang}",
- )[0]
- # 按照 table_id 将识别结果进行回填
- for img_dict, ocr_res in zip(rec_img_list, ocr_res_list):
- ocr_text = self._normalize_table_ocr_rec_text(ocr_res[0])
- ocr_result_item = [img_dict["dt_box"], html.escape(ocr_text), ocr_res[1]]
- if table_res_list_all_page[img_dict["table_id"]].get("ocr_result"):
- table_res_list_all_page[img_dict["table_id"]]["ocr_result"].append(ocr_result_item)
- else:
- table_res_list_all_page[img_dict["table_id"]]["ocr_result"] = [ocr_result_item]
-
- # 先对所有表格使用无线表格模型,然后对分类为有线的表格使用有线表格模型
- for table_res_dict in table_res_list_all_page:
- if not self._table_supports_inline_objects(table_res_dict):
- continue
-
- table_inline_objects = table_res_dict.get("table_inline_objects", [])
- if not table_inline_objects:
- continue
-
- table_ocr_result = table_res_dict.setdefault("ocr_result", [])
- for inline_object in table_inline_objects:
- table_ocr_result.append(
- [
- self._bbox_to_quad(inline_object["table_token_bbox"]),
- inline_object["content"],
- inline_object["score"],
- ]
- )
-
- self._sort_table_ocr_result(table_ocr_result)
-
- wireless_table_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.WirelessTable,
- )
- wireless_table_model.batch_predict(table_res_list_all_page)
-
- # 单独拿出有线表格进行预测
- wired_table_res_list = []
- for table_res_dict in table_res_list_all_page:
- # logger.debug(f"Table classification result: {table_res_dict["table_res"]["cls_label"]}
- # with confidence {table_res_dict["table_res"]["cls_score"]}")
- if (
- table_res_dict["table_res"]["cls_label"] == AtomicModel.WirelessTable
- and table_res_dict["table_res"]["cls_score"] < 0.9
- ) or table_res_dict["table_res"]["cls_label"] == AtomicModel.WiredTable:
- wired_table_res_list.append(table_res_dict)
- del table_res_dict["table_res"]["cls_label"]
- del table_res_dict["table_res"]["cls_score"]
- if wired_table_res_list:
- for table_res_dict in tqdm(wired_table_res_list, desc="Table-wired Predict"):
- if not table_res_dict.get("ocr_result", None):
- continue
-
- wired_table_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.WiredTable,
- lang=table_res_dict["lang"],
- )
- table_res_dict["table_res"]["html"] = wired_table_model.predict(
- table_res_dict["wired_table_img"],
- table_res_dict["ocr_result"],
- table_res_dict["table_res"].get("html", None),
- )
-
- # 表格格式清理
- for table_res_dict in table_res_list_all_page:
- html_code = table_res_dict["table_res"].get("html", "") or ""
-
- # 检查html_code是否包含'<table>'和'</table>'
- if "<table>" in html_code and "</table>" in html_code:
- # 选用<table>到</table>的内容,放入table_res_dict['table_res']['html']
- start_index = html_code.find("<table>")
- end_index = html_code.rfind("</table>") + len("</table>")
- table_res_dict["table_res"]["html"] = html_code[start_index:end_index]
-
- # OCR det
- if self.text_ocr_det_batch_enabled:
- # 批处理模式 - 按语言和分辨率分组
- # 收集所有需要OCR检测的裁剪图像
- all_cropped_images_info = []
-
- for ocr_res_list_dict in ocr_res_list_all_page:
- _lang = ocr_res_list_dict["lang"]
-
- for res in ocr_res_list_dict["ocr_res_list"]:
- new_image, useful_list = crop_img(res, ocr_res_list_dict["np_img"], crop_paste_x=50, crop_paste_y=50)
- adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
- ocr_res_list_dict["single_page_mfdetrec_res"], useful_list
- )
-
- # BGR转换
- bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore
- det_image = self._get_masked_det_image(
- bgr_image,
- adjusted_mfdetrec_res,
- )
-
- all_cropped_images_info.append(
- (
- bgr_image,
- det_image,
- useful_list,
- ocr_res_list_dict,
- adjusted_mfdetrec_res,
- _lang,
- )
- )
-
- # 按语言分组
- lang_groups = defaultdict(list)
- for crop_info in all_cropped_images_info:
- lang = crop_info[5]
- lang_groups[lang].append(crop_info)
-
- # 对每种语言按分辨率分组并批处理
- for lang, lang_crop_list in lang_groups.items():
- if not lang_crop_list:
- continue
-
- # logger.info(f"Processing OCR detection for language {lang} with {len(lang_crop_list)} images")
-
- # 获取OCR模型
- ocr_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang=lang)
-
- batch_images = [crop_info[1] for crop_info in lang_crop_list]
- det_batch_size = min(len(batch_images), self.batch_ratio * OCR_DET_BASE_BATCH_SIZE)
- batch_results = run_ocr_inference(
- ocr_model.text_detector.batch_predict,
- batch_images,
- det_batch_size,
- tqdm_enable=True,
- tqdm_desc=f"OCR-det {lang}",
- )
-
- for crop_info, (dt_boxes, _) in zip(lang_crop_list, batch_results):
- (
- bgr_image,
- _det_image,
- useful_list,
- ocr_res_list_dict,
- adjusted_mfdetrec_res,
- _lang,
- ) = crop_info
-
- if dt_boxes is not None and len(dt_boxes) > 0:
- # 处理检测框
- dt_boxes_sorted = sorted_boxes(dt_boxes)
- dt_boxes_merged = merge_det_boxes(dt_boxes_sorted) if dt_boxes_sorted else []
-
- # 根据公式位置更新检测框
- dt_boxes_final = (
- update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)
- if dt_boxes_merged and adjusted_mfdetrec_res
- else dt_boxes_merged
- )
-
- if dt_boxes_final:
- ocr_res = [box.tolist() if hasattr(box, "tolist") else box for box in dt_boxes_final]
- ocr_result_list = get_ocr_result_list(
- ocr_res,
- useful_list,
- ocr_res_list_dict["ocr_enable"],
- bgr_image,
- _lang,
- )
- ocr_res_list_dict["layout_res"].extend(ocr_result_list)
-
- # 清理显存
- clean_vram(self.model.device, vram_threshold=8)
-
- else:
- # 原始单张处理模式
- for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):
- # Process each area that requires OCR processing
- _lang = ocr_res_list_dict["lang"]
- # Get OCR results for this language's images
- ocr_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang=_lang)
- for res in ocr_res_list_dict["ocr_res_list"]:
- new_image, useful_list = crop_img(res, ocr_res_list_dict["np_img"], crop_paste_x=50, crop_paste_y=50)
- adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
- ocr_res_list_dict["single_page_mfdetrec_res"], useful_list
- )
- # OCR-det
- bgr_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR) # type: ignore
- det_image = self._get_masked_det_image(
- bgr_image,
- adjusted_mfdetrec_res,
- )
- ocr_res = run_ocr_inference(
- ocr_model.ocr,
- det_image,
- mfd_res=adjusted_mfdetrec_res,
- rec=False,
- )[0]
-
- # Integration results
- if ocr_res:
- ocr_result_list = get_ocr_result_list(
- ocr_res,
- useful_list,
- ocr_res_list_dict["ocr_enable"],
- bgr_image,
- _lang,
- )
-
- ocr_res_list_dict["layout_res"].extend(ocr_result_list)
-
- # OCR rec
- # Create dictionaries to store items by language
- need_ocr_lists_by_lang = {} # Dict of lists for each language
- img_crop_lists_by_lang = {} # Dict of lists for each language
-
- for layout_res in images_layout_res:
- for layout_res_item in layout_res:
- if not layout_res_item.get("_need_ocr_rec"):
- continue
- if "np_img" in layout_res_item and "lang" in layout_res_item:
- lang = layout_res_item["lang"]
-
- # Initialize lists for this language if not exist
- if lang not in need_ocr_lists_by_lang:
- need_ocr_lists_by_lang[lang] = []
- img_crop_lists_by_lang[lang] = []
-
- # Add to the appropriate language-specific lists
- need_ocr_lists_by_lang[lang].append((layout_res, layout_res_item))
- img_crop_lists_by_lang[lang].append(layout_res_item["np_img"])
-
- # Remove temporary fields after collecting
- layout_res_item.pop("np_img", None)
- layout_res_item.pop("lang", None)
- layout_res_item.pop("_need_ocr_rec", None)
-
- if len(img_crop_lists_by_lang) > 0:
- # Process OCR by language
- total_processed = 0
-
- # Process each language separately
- for lang, img_crop_list in img_crop_lists_by_lang.items():
- if len(img_crop_list) > 0:
- # Get OCR results for this language's images
-
- ocr_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.OCR, lang=lang)
- ocr_res_list = run_ocr_inference(ocr_model.ocr, img_crop_list, det=False, tqdm_enable=True)[0]
-
- # Verify we have matching counts
- assert len(ocr_res_list) == len(need_ocr_lists_by_lang[lang]), (
- f"ocr_res_list: {len(ocr_res_list)},"
- f" need_ocr_list: {len(need_ocr_lists_by_lang[lang])} for lang: {lang}"
- )
-
- items_to_remove = []
- # Process OCR results for this language
- for index, (page_layout_res, layout_res_item) in enumerate(need_ocr_lists_by_lang[lang]):
- ocr_text, ocr_score = ocr_res_list[index]
- layout_res_item["text"] = ocr_text
- layout_res_item["score"] = float(f"{ocr_score:.3f}")
- should_remove = False
- if ocr_score < OcrConfidence.min_confidence:
- should_remove = True
- else:
- layout_res_bbox = layout_res_item["bbox"]
- layout_res_width = layout_res_bbox[2] - layout_res_bbox[0]
- layout_res_height = layout_res_bbox[3] - layout_res_bbox[1]
- if (
- ocr_text
- in [
- "(204号",
- "(20",
- "(2",
- "(2号",
- "(20号",
- "号",
- "(204",
- "(cid:)",
- "(ci:)",
- "(cd:1)",
- "cd:)",
- "c)",
- "(cd:)",
- "c",
- "id:)",
- ":)",
- "√:)",
- "√i:)",
- "−i:)",
- "−:",
- "i:)",
- ]
- and ocr_score < 0.8
- and layout_res_width < layout_res_height
- ):
- should_remove = True
-
- if should_remove:
- items_to_remove.append((page_layout_res, layout_res_item))
-
- for page_layout_res, layout_res_item in items_to_remove:
- if layout_res_item in page_layout_res:
- page_layout_res.remove(layout_res_item)
-
- total_processed += len(img_crop_list)
-
- seal_ocr_items = []
- for ocr_res_list_dict in ocr_res_list_all_page:
- for layout_res_item in ocr_res_list_dict["layout_res"]:
- if layout_res_item.get("label") == "seal":
- seal_ocr_items.append((ocr_res_list_dict, layout_res_item))
-
- seal_ocr_model = None
- for ocr_res_list_dict, layout_res_item in tqdm(seal_ocr_items, desc="Seal Predict"):
- np_img = ocr_res_list_dict["np_img"]
- image_h, image_w = np_img.shape[:2]
- layout_res_item["text"] = ""
- seal_bbox = normalize_to_int_bbox(
- layout_res_item.get("bbox"),
- image_size=(image_h, image_w),
- )
- if seal_bbox is None:
- continue
-
- x0, y0, x1, y1 = seal_bbox
- seal_crop_rgb = np_img[y0:y1, x0:x1]
- if seal_crop_rgb.size == 0:
- continue
-
- if seal_ocr_model is None:
- seal_ocr_model = atom_model_manager.get_atom_model(
- atom_model_name=AtomicModel.OCR,
- lang="seal",
- )
-
- seal_crop_bgr = cv2.cvtColor(seal_crop_rgb, cv2.COLOR_RGB2BGR)
- seal_ocr_res = run_ocr_inference(seal_ocr_model.ocr, seal_crop_bgr, det=True, rec=True)[0]
- if not seal_ocr_res:
- continue
-
- seal_texts = []
- for seal_item in seal_ocr_res:
- if not seal_item or len(seal_item) != 2:
- continue
- rec_result = seal_item[1]
- if not rec_result or len(rec_result) < 1:
- continue
- rec_text = rec_result[0]
- if rec_text:
- seal_texts.append(rec_text)
-
- layout_res_item["text"] = seal_texts
-
- for ocr_res_list_dict in ocr_res_list_all_page:
- self._prune_empty_ocr_text_blocks(
- ocr_res_list_dict["layout_res"],
- ocr_res_list_dict["ocr_enable"],
- )
-
- return images_layout_res
diff --git a/mineru/backend/pipeline/model_list.py b/mineru/backend/pipeline/model_list.py
deleted file mode 100644
index c84df863..00000000
--- a/mineru/backend/pipeline/model_list.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-class AtomicModel:
- Layout = "layout"
- MFD = "mfd"
- MFR = "mfr"
- OCR = "ocr"
- WirelessTable = "wireless_table"
- WiredTable = "wired_table"
- TableCls = "table_cls"
- TableOrientationCls = "table_ori_cls"
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
deleted file mode 100644
index beb0b768..00000000
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ /dev/null
@@ -1,139 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from typing import Any
-
-from ...types import BlockType, PageInfo
-from ...utils.hash_utils import bytes_md5
-from ...utils.image_payload import ImagePayloadCache
-from ...utils.page_index import resolve_output_page_idx
-from ...utils.pdf_document import PDFDocument, PDFPage
-from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
-from ..utils.formula_number import optimize_pipeline_formula_number_blocks
-from ..utils.middle_json_utils import append_pages, apply_post_ocr
-from ..utils.runtime_utils import cross_page_table_merge
-from ..utils.visual_span_utils import cut_visual_spans_in_blocks
-from .model_init import AtomModelSingleton
-from .para_split import para_split
-from .pipeline_magic_model import MagicModel
-
-
-def blocks_to_page_info(
- page_model_info: dict[str, Any],
- image_dict: dict[str, Any],
- pdf_page: PDFPage,
- page_index: int,
- ocr_enable: bool = False,
- image_cache: ImagePayloadCache | None = None,
-) -> PageInfo:
- scale = image_dict["scale"]
- page_pil_img = image_dict["img_pil"]
- page_img_md5 = bytes_md5(page_pil_img.tobytes())
- page_w, page_h = map(int, pdf_page.size)
-
- magic_model = MagicModel(page_model_info, pdf_page, scale, page_pil_img, page_w, page_h, ocr_enable)
-
- """从magic_model对象中获取后面会用到的区块信息"""
- preproc_blocks = magic_model.get_preproc_blocks()
- discarded_blocks = magic_model.get_discarded_blocks()
-
- cut_visual_spans_in_blocks(
- [*preproc_blocks, *discarded_blocks],
- page_pil_img,
- page_img_md5,
- page_index,
- scale=scale,
- image_cache=image_cache,
- )
-
- return PageInfo(
- preproc_blocks=preproc_blocks,
- page_idx=page_index,
- page_size=(page_w, page_h),
- discarded_blocks=discarded_blocks,
- _backend="pipeline",
- )
-
-
-def build_page_model_info(page_layout_dets: list[dict[str, Any]], page_index: int, pil_img: Any) -> dict[str, Any]:
- page_info_dict = {"page_no": page_index, "width": pil_img.width, "height": pil_img.height}
- return {"layout_dets": page_layout_dets, "page_info": page_info_dict}
-
-
-def append_batch_results_to_middle_json(
- middle_json: list[PageInfo],
- batch_results: list[list[dict[str, Any]]],
- images_list: list[dict[str, Any]],
- pdf_doc: PDFDocument,
- page_start_index: int = 0,
- ocr_enable: bool = False,
- model_list: list[dict[str, Any]] | None = None,
- page_index_map: list[int] | None = None,
- progress_bar: Any = None,
- image_cache: ImagePayloadCache | None = None,
-) -> None:
- page_model_infos = []
- for offset, (image_dict, page_layout_dets) in enumerate(zip(images_list, batch_results)):
- physical_page_idx = page_start_index + offset
- output_page_idx = resolve_output_page_idx(physical_page_idx, page_index_map)
- page_model_info = build_page_model_info(page_layout_dets, output_page_idx, image_dict["img_pil"])
- page_model_infos.append(page_model_info)
-
- if model_list is not None:
- model_list.extend(page_model_infos)
-
- append_pages(
- middle_json,
- page_model_infos,
- images_list,
- pdf_doc,
- page_cvt_fn=blocks_to_page_info,
- page_start_index=page_start_index,
- page_index_map=page_index_map,
- ocr_enable=ocr_enable,
- progress_bar=progress_bar,
- image_cache=image_cache,
- )
-
-
-def _apply_post_ocr(pages: list[PageInfo], lang: str | None = None) -> None:
- atom_model_manager = AtomModelSingleton()
- ocr_model = atom_model_manager.get_atom_model(
- atom_model_name="ocr",
- det_db_box_thresh=0.3,
- lang=lang,
- )
- apply_post_ocr(pages, ocr_model)
-
-
-def _post_block_process(pages: list[PageInfo]) -> None:
- for page_info in pages:
- for blocks in [page_info.preproc_blocks, page_info.para_blocks]:
- for block in blocks:
- block_type = block.type
- if block_type == BlockType.DOC_TITLE:
- block.type = BlockType.TITLE
- block.level = 1
- elif block_type == BlockType.PARAGRAPH_TITLE:
- block.type = BlockType.TITLE
- block.level = 2
- elif block_type == BlockType.VERTICAL_TEXT:
- block.type = BlockType.TEXT
-
-
-def apply_server_side_postprocess(pages: list[PageInfo], lang: str | None = None) -> None:
- """执行只能在服务端完成的后处理;目前仅包含依赖 OCR 模型的 post-OCR。"""
- _apply_post_ocr(pages, lang=lang)
-
-
-def finalize_middle_json_from_preproc(pages: list[PageInfo]) -> None:
- """从 preproc_blocks 执行确定性 finalize,供服务端完整路径和客户端复用。"""
- optimize_pipeline_formula_number_blocks(pages)
- para_split(pages)
- cross_page_table_merge(pages)
- apply_title_leveling_to_pdf_info(pages)
- _post_block_process(pages)
-
-
-def finalize_middle_json(pages: list[PageInfo], lang: str | None = None) -> None:
- """Apply document-level post processing once all page_info entries are ready."""
- apply_server_side_postprocess(pages, lang=lang)
- finalize_middle_json_from_preproc(pages)
diff --git a/mineru/backend/pipeline/para_split.py b/mineru/backend/pipeline/para_split.py
deleted file mode 100644
index bd14f53d..00000000
--- a/mineru/backend/pipeline/para_split.py
+++ /dev/null
@@ -1,425 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import copy
-
-from ...types import Block, BlockType, ContentType, PageInfo
-from ...utils.language import detect_lang
-
-LINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":", ":", ";", ";")
-LIST_END_FLAG = (".", "。", ";", ";")
-
-
-def __process_blocks(blocks: list[Block]) -> list[list[Block]]:
- # 对所有block预处理
- # 1.通过title和interline_equation将block分组
- # 2.bbox边界根据line信息重置
-
- result: list[list[Block]] = []
- current_group: list[Block] = []
-
- for i in range(len(blocks)):
- current_block = blocks[i]
-
- # 如果当前块是 text 类型
- if current_block.type in [BlockType.TEXT, BlockType.INDEX, BlockType.VERTICAL_TEXT]:
- current_block._bbox_fs = copy.deepcopy(current_block.bbox)
- if current_block.lines:
- current_block._bbox_fs = (
- min([line.bbox[0] for line in current_block.lines]),
- min([line.bbox[1] for line in current_block.lines]),
- max([line.bbox[2] for line in current_block.lines]),
- max([line.bbox[3] for line in current_block.lines]),
- )
- current_group.append(current_block)
-
- # 检查下一个块是否存在
- if i + 1 < len(blocks):
- next_block = blocks[i + 1]
- # 如果下一个块不是 text 类型且是 title 或 interline_equation 类型
- if next_block.type in [
- BlockType.ABSTRACT,
- BlockType.INTERLINE_EQUATION,
- BlockType.DOC_TITLE,
- BlockType.PARAGRAPH_TITLE,
- ]:
- result.append(current_group)
- current_group = []
-
- # 处理最后一个 group
- if current_group:
- result.append(current_group)
-
- return result
-
-
-def __is_list_or_index_block(block: Block) -> str:
- if block.type == BlockType.VERTICAL_TEXT:
- return BlockType.VERTICAL_TEXT
- if block.type == BlockType.INDEX:
- for line in block.lines:
- line._is_list_start = True
- return BlockType.INDEX
- # 一个block如果是list block 应该同时满足以下特征
- # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.block内有多个line 右侧不顶格(狗牙状)
- # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.多个line以endflag结尾
- # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.block内有多个line 左侧不顶格
-
- # index block 是一种特殊的list block
- # 一个block如果是index block 应该同时满足以下特征
- # 1.block内有多个line 2.block 内有多个line两侧均顶格写 3.line的开头或者结尾均为数字
- if len(block.lines) >= 2:
- assert block._bbox_fs is not None
- assert block._page_size is not None
-
- first_line = block.lines[0]
- line_height = first_line.bbox[3] - first_line.bbox[1]
- block_weight = block._bbox_fs[2] - block._bbox_fs[0]
- block_height = block._bbox_fs[3] - block._bbox_fs[1]
- page_weight, page_height = block._page_size
-
- left_close_num = 0
- left_not_close_num = 0
- right_not_close_num = 0
- right_close_num = 0
- lines_text_list = []
- center_close_num = 0
- external_sides_not_close_num = 0
- multiple_para_flag = False
- last_line = block.lines[-1]
-
- if page_weight == 0:
- block_weight_ratio = 0
- else:
- block_weight_ratio = block_weight / page_weight
- # logger.info(f"block_weight_ratio: {block_weight_ratio}")
-
- # 如果首行左边不顶格而右边顶格,末行左边顶格而右边不顶格 (第一行可能可以右边不顶格)
- if (
- first_line.bbox[0] - block._bbox_fs[0] > line_height / 2
- and abs(last_line.bbox[0] - block._bbox_fs[0]) < line_height / 2
- and block._bbox_fs[2] - last_line.bbox[2] > line_height
- ):
- multiple_para_flag = True
-
- block_text = ""
-
- for line in block.lines:
- line_text = ""
-
- for span in line.spans:
- span_type = span.type
- if span_type == ContentType.TEXT:
- line_text += span.content.strip()
- # 添加所有文本,包括空行,保持与block['lines']长度一致
- lines_text_list.append(line_text)
- block_text = "".join(lines_text_list)
-
- block_lang = detect_lang(block_text)
- # logger.info(f"block_lang: {block_lang}")
-
- for line in block.lines:
- line_mid_x = (line.bbox[0] + line.bbox[2]) / 2
- block_mid_x = (block._bbox_fs[0] + block._bbox_fs[2]) / 2
- if line.bbox[0] - block._bbox_fs[0] > 0.7 * line_height and block._bbox_fs[2] - line.bbox[2] > 0.7 * line_height:
- external_sides_not_close_num += 1
- if abs(line_mid_x - block_mid_x) < line_height / 2:
- center_close_num += 1
-
- # 计算line左侧顶格数量是否大于2,是否顶格用abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height/2 来判断
- if abs(block._bbox_fs[0] - line.bbox[0]) < line_height / 2:
- left_close_num += 1
- elif line.bbox[0] - block._bbox_fs[0] > line_height:
- left_not_close_num += 1
-
- # 计算右侧是否顶格
- if abs(block._bbox_fs[2] - line.bbox[2]) < line_height:
- right_close_num += 1
- else:
- # 类中文没有超长单词的情况,可以用统一的阈值
- if block_lang in ["zh", "ja", "ko"]:
- closed_area = 0.26 * block_weight
- else:
- # 右侧不顶格情况下是否有一段距离,拍脑袋用0.3block宽度做阈值
- # block宽的阈值可以小些,block窄的阈值要大
- if block_weight_ratio >= 0.5:
- closed_area = 0.26 * block_weight
- else:
- closed_area = 0.36 * block_weight
- if block._bbox_fs[2] - line.bbox[2] > closed_area:
- right_not_close_num += 1
-
- # 判断lines_text_list中的元素是否有超过80%都以LIST_END_FLAG结尾
- line_end_flag = False
- # 判断lines_text_list中的元素是否有超过80%都以数字开头或都以数字结尾
- line_num_flag = False
- num_start_count = 0
- num_end_count = 0
- flag_end_count = 0
-
- if len(lines_text_list) > 0:
- for line_text in lines_text_list:
- if len(line_text) > 0:
- if line_text[-1] in LIST_END_FLAG:
- flag_end_count += 1
- if line_text[0].isdigit():
- num_start_count += 1
- if line_text[-1].isdigit():
- num_end_count += 1
-
- if num_start_count / len(lines_text_list) >= 0.8 or num_end_count / len(lines_text_list) >= 0.8:
- line_num_flag = True
- if flag_end_count / len(lines_text_list) >= 0.8:
- line_end_flag = True
-
- # 有的目录右侧不贴边, 目前认为左边或者右边有一边全贴边,且符合数字规则极为index
- if (left_close_num / len(block.lines) >= 0.8 or right_close_num / len(block.lines) >= 0.8) and line_num_flag:
- for line in block.lines:
- line._is_list_start = True
- return BlockType.INDEX
-
- # 全部line都居中的特殊list识别,每行都需要换行,特征是多行,且大多数行都前后not_close,每line中点x坐标接近
- # 补充条件block的长宽比有要求
- elif (
- external_sides_not_close_num >= 2
- and center_close_num == len(block.lines)
- and external_sides_not_close_num / len(block.lines) >= 0.5
- and block_height / block_weight > 0.4
- ):
- for line in block.lines:
- line._is_list_start = True
- return BlockType.LIST
-
- elif (
- left_close_num >= 2
- and (right_not_close_num >= 2 or line_end_flag or left_not_close_num >= 2)
- and not multiple_para_flag
- # and block_weight_ratio > 0.27
- ):
- # 处理一种特殊的没有缩进的list,所有行都贴左边,通过右边的空隙判断是否是item尾
- if left_close_num / len(block.lines) > 0.8:
- # 这种是每个item只有一行,且左边都贴边的短item list
- if flag_end_count == 0 and right_close_num / len(block.lines) < 0.5:
- for line in block.lines:
- if abs(block._bbox_fs[0] - line.bbox[0]) < line_height / 2:
- line._is_list_start = True
- # 这种是大部分line item 都有结束标识符的情况,按结束标识符区分不同item
- elif line_end_flag:
- for i, line in enumerate(block.lines):
- if len(lines_text_list[i]) > 0 and lines_text_list[i][-1] in LIST_END_FLAG:
- line._is_list_end = True
- if i + 1 < len(block.lines):
- block.lines[i + 1]._is_list_start = True
- # line item基本没有结束标识符,而且也没有缩进,按右侧空隙判断哪些是item end
- else:
- line_start_flag = False
- for i, line in enumerate(block.lines):
- if line_start_flag:
- line._is_list_start = True
- line_start_flag = False
-
- if abs(block._bbox_fs[2] - line.bbox[2]) > 0.1 * block_weight:
- line._is_list_end = True
- line_start_flag = True
- # 一种有缩进的特殊有序list, start line 左侧不贴边且以数字开头
- # end line 以 IS_LIST_END_FLAG 结尾且数量和 start line 一致
- elif num_start_count >= 2 and num_start_count == flag_end_count:
- for i, line in enumerate(block.lines):
- if len(lines_text_list[i]) > 0:
- if lines_text_list[i][0].isdigit():
- line._is_list_start = True
- if lines_text_list[i][-1] in LIST_END_FLAG:
- line._is_list_end = True
- else:
- # 正常有缩进的list处理
- for line in block.lines:
- if abs(block._bbox_fs[0] - line.bbox[0]) < line_height / 2:
- line._is_list_start = True
- if abs(block._bbox_fs[2] - line.bbox[2]) > line_height:
- line._is_list_end = True
-
- return BlockType.LIST
- else:
- return BlockType.TEXT
- else:
- return BlockType.TEXT
-
-
-def __merge_2_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
- if len(block1.lines) > 0 and len(block2.lines) > 0:
- assert block1._bbox_fs is not None
- assert block2._bbox_fs is not None
-
- first_line = block1.lines[0]
- line_height = first_line.bbox[3] - first_line.bbox[1]
- block1_weight = block1.bbox[2] - block1.bbox[0]
- block2_weight = block2.bbox[2] - block2.bbox[0]
- min_block_weight = min(block1_weight, block2_weight)
- if abs(block1._bbox_fs[0] - first_line.bbox[0]) < line_height / 2:
- last_line = block2.lines[-1]
- if len(last_line.spans) > 0:
- last_span = last_line.spans[-1]
- line_height = last_line.bbox[3] - last_line.bbox[1]
- if len(first_line.spans) > 0:
- first_span = first_line.spans[0]
- if len(first_span.content) > 0:
- span_start_with_num = first_span.content[0].isdigit()
- span_start_with_big_char = first_span.content[0].isupper()
- if (
- # 上一个block的最后一个line的右边界和block的右边界差距不超过line_height
- abs(block2._bbox_fs[2] - last_line.bbox[2]) < line_height
- # 上一个block的最后一个span不是以特定符号结尾
- and not last_span.content.endswith(LINE_STOP_FLAG)
- # 两个block宽度差距超过2倍也不合并
- and abs(block1_weight - block2_weight) < min_block_weight
- # 下一个block的第一个字符是数字
- and not span_start_with_num
- # 下一个block的第一个字符是大写字母
- and not span_start_with_big_char
- # 下一个块的y0要比上一个块的y1小
- and block1.bbox[1] < block2.bbox[3]
- # 两个块任意一个块需要大于1行
- and (len(block1.lines) > 1 or len(block2.lines) > 1)
- ):
- if block1._page_num != block2._page_num:
- for line in block1.lines:
- for span in line.spans:
- span._cross_page = True
- block2.lines.extend(block1.lines)
- block1.lines = []
- block1._lines_deleted = True
-
- return block1, block2
-
-
-def __merge_2_vertical_text_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
- if len(block1.lines) > 0 and len(block2.lines) > 0:
- assert block1._bbox_fs is not None
- assert block2._bbox_fs is not None
-
- first_line = block1.lines[0]
- line_width = first_line.bbox[2] - first_line.bbox[0]
- block1_height = block1.bbox[3] - block1.bbox[1]
- block2_height = block2.bbox[3] - block2.bbox[1]
- min_block_height = min(block1_height, block2_height)
- if line_width > 0 and abs(block1._bbox_fs[1] - first_line.bbox[1]) < line_width / 2:
- last_line = block2.lines[-1]
- if len(last_line.spans) > 0:
- last_span = last_line.spans[-1]
- line_width = last_line.bbox[2] - last_line.bbox[0]
- if line_width > 0 and len(first_line.spans) > 0:
- first_span = first_line.spans[0]
- first_content = first_span.content
- last_content = last_span.content
- if len(first_content) > 0:
- span_start_with_num = first_content[0].isdigit()
- span_start_with_big_char = first_content[0].isupper()
- if (
- abs(block2._bbox_fs[3] - last_line.bbox[3]) < line_width
- and not last_content.endswith(LINE_STOP_FLAG)
- and abs(block1_height - block2_height) < min_block_height
- and not span_start_with_num
- and not span_start_with_big_char
- # 下一个纵排块的右边界要进入上一个纵排块左边界右侧
- and block1.bbox[2] > block2.bbox[0]
- ):
- if block1._page_num != block2._page_num:
- for line in block1.lines:
- for span in line.spans:
- span._cross_page = True
- block2.lines.extend(block1.lines)
- block1.lines = []
- block1._lines_deleted = True
-
- return block1, block2
-
-
-def __merge_2_list_blocks(block1: Block, block2: Block) -> tuple[Block, Block]:
- if block1._page_num != block2._page_num:
- for line in block1.lines:
- for span in line.spans:
- span._cross_page = True
- block2.lines.extend(block1.lines)
- block1.lines = []
- block1._lines_deleted = True
-
- return block1, block2
-
-
-def __is_list_group(text_blocks_group: list[Block]) -> bool:
- # list group的特征是一个group内的所有block都满足以下条件
- # 1.每个block都不超过3行 2. 每个block 的左边界都比较接近(逻辑简单点先不加这个规则)
- for block in text_blocks_group:
- if block.type == BlockType.VERTICAL_TEXT:
- return False
- if len(block.lines) > 3:
- return False
- return True
-
-
-def __para_merge_page(blocks: list[Block]) -> None:
- page_text_blocks_groups = __process_blocks(blocks)
-
- for text_blocks_group in page_text_blocks_groups:
- if len(text_blocks_group) > 0:
- # 需要先在合并前对所有block判断是否为list or index block
- for block in text_blocks_group:
- block_type = __is_list_or_index_block(block)
- block.type = block_type
- # logger.info(f"{block['type']}:{block}")
-
- if len(text_blocks_group) > 1:
- # 在合并前判断这个group 是否是一个 list group
- is_list_group = __is_list_group(text_blocks_group)
-
- # 倒序遍历
- for i in range(len(text_blocks_group) - 1, -1, -1):
- current_block = text_blocks_group[i]
-
- # 检查是否有前一个块
- if i - 1 >= 0:
- prev_block = text_blocks_group[i - 1]
-
- if current_block.type == BlockType.VERTICAL_TEXT and prev_block.type == BlockType.VERTICAL_TEXT:
- __merge_2_vertical_text_blocks(current_block, prev_block)
- elif current_block.type == BlockType.TEXT and prev_block.type == BlockType.TEXT and not is_list_group:
- __merge_2_text_blocks(current_block, prev_block)
- elif (current_block.type == BlockType.LIST and prev_block.type == BlockType.LIST) or (
- current_block.type == BlockType.INDEX and prev_block.type == BlockType.INDEX
- ):
- __merge_2_list_blocks(current_block, prev_block)
-
- else:
- continue
-
-
-def para_split(page_info_list: list[PageInfo]) -> None:
- all_blocks: list[Block] = []
- for page_info in page_info_list:
- blocks = copy.deepcopy(page_info.preproc_blocks)
- for block in blocks:
- block._page_num = page_info.page_idx
- block._page_size = page_info.page_size
- all_blocks.extend(blocks)
-
- __para_merge_page(all_blocks)
-
- for page_info in page_info_list:
- page_info.para_blocks = []
- for block in all_blocks:
- if block._page_num is not None:
- if block._page_num == page_info.page_idx:
- if block.type == BlockType.VERTICAL_TEXT:
- block.type = BlockType.TEXT
- page_info.para_blocks.append(block)
- # 从block中删除不需要的page_num和page_size字段
- block._page_num = None
- block._page_size = None
-
-
-if __name__ == "__main__":
- input_blocks = []
- # 调用函数
- groups = __process_blocks(input_blocks)
- for group_index, group in enumerate(groups):
- print(f"Group {group_index}: {group}")
diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py
deleted file mode 100644
index 94152207..00000000
--- a/mineru/backend/pipeline/pipeline_analyze.py
+++ /dev/null
@@ -1,373 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-import os
-import time
-from collections.abc import Callable
-from typing import Any
-
-from loguru import logger
-from PIL import Image
-from tqdm import tqdm
-
-from ...utils.config_reader import get_device, get_processing_window_size
-from ...utils.enum_class import ImageType
-from ...utils.image_payload import ImagePayloadCache
-from ...utils.model_utils import clean_memory, get_vram
-from ...utils.pdf_document import PDFDocument
-from ...utils.pdf_image_tools import load_images_from_pdf_bytes_range
-from ..utils.runtime_utils import exclude_progress_bar_idle_time
-from .model_init import PIPELINE_MODEL_INIT_LOCK, MineruPipelineModel
-from .model_output_to_middle_json import (
- append_batch_results_to_middle_json,
- apply_server_side_postprocess,
- finalize_middle_json,
-)
-
-os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" # 让mps可以fallback
-
-
-class ModelSingleton:
- _instance = None
- _models = {}
- _lock = PIPELINE_MODEL_INIT_LOCK
-
- def __new__(cls, *args: Any, **kwargs: Any) -> ModelSingleton:
- with cls._lock:
- if cls._instance is None:
- cls._instance = super().__new__(cls)
- return cls._instance
-
- def get_model(
- self,
- lang: str | None = None,
- formula_enable: bool = True,
- table_enable: bool = True,
- ) -> MineruPipelineModel:
- key = (lang, formula_enable, table_enable)
- with self._lock:
- if key not in self._models:
- self._models[key] = custom_model_init(
- lang=lang,
- formula_enable=formula_enable,
- table_enable=table_enable,
- )
- return self._models[key]
-
-
-def custom_model_init(
- lang: str | None = None,
- formula_enable: bool = True,
- table_enable: bool = True,
-) -> MineruPipelineModel:
- model_init_start = time.time()
- # 从配置文件读取model-dir和device
- device = get_device()
-
- formula_config = {"enable": formula_enable}
- table_config = {"enable": table_enable}
-
- model_input = {
- "device": device,
- "table_config": table_config,
- "formula_config": formula_config,
- "lang": lang,
- }
-
- custom_model = MineruPipelineModel(**model_input)
-
- model_init_cost = time.time() - model_init_start
- logger.info(f"model init cost: {model_init_cost}")
-
- return custom_model
-
-
-def _get_ocr_enable(pdf_doc: PDFDocument, parse_method: str) -> bool:
- if parse_method == "auto":
- return pdf_doc.classify() == "ocr"
- if parse_method == "ocr":
- return True
- return False
-
-
-def _close_images(images_list: list[dict[str, Any]]) -> None:
- for image_dict in images_list or []:
- pil_img = image_dict.get("img_pil")
- if pil_img is not None:
- try:
- pil_img.close()
- except Exception:
- pass
-
-
-def _format_doc_slices(batch_slices: list[dict[str, int]]) -> str:
- return ",".join(f"doc{item['doc_index']}:{item['page_start'] + 1}-{item['page_end'] + 1}" for item in batch_slices)
-
-
-def _finalize_processing_window_context(
- context: dict[str, Any],
- on_doc_ready: Callable[..., object],
- client_side_output_generation: bool = False,
-) -> None:
- if context["closed"]:
- return
- if client_side_output_generation:
- apply_server_side_postprocess(context["middle_json"], lang=context["lang"])
- else:
- finalize_middle_json(context["middle_json"], lang=context["lang"])
- logger.debug(f"Pipeline doc ready: doc{context['doc_index']} pages={context['page_count']}")
- on_doc_ready(
- context["doc_index"],
- context["model_list"],
- context["middle_json"],
- context["ocr_enable"],
- )
- context["pdf_doc"].close()
- context["closed"] = True
-
-
-def _emit_zero_page_contexts(
- doc_contexts: list[dict[str, Any]],
- on_doc_ready: Callable[..., object],
- client_side_output_generation: bool = False,
-) -> None:
- for context in doc_contexts:
- if context["page_count"] == 0 and not context["closed"]:
- _finalize_processing_window_context(
- context,
- on_doc_ready,
- client_side_output_generation=client_side_output_generation,
- )
-
-
-def doc_analyze_streaming(
- pdf_bytes_list: list[bytes],
- lang_list: list[str | None],
- on_doc_ready: Callable[..., object],
- parse_method: str = "auto",
- formula_enable: bool = True,
- table_enable: bool = True,
- client_side_output_generation: bool = False,
- page_index_map_list: list[list[int] | None] | None = None,
- image_cache_list: list[ImagePayloadCache] | None = None,
-) -> None:
- if len(pdf_bytes_list) != len(lang_list):
- raise ValueError("pdf_bytes_list and lang_list must have the same length")
- if page_index_map_list is not None and len(page_index_map_list) != len(pdf_bytes_list):
- raise ValueError("page_index_map_list must have the same length as pdf_bytes_list")
- if image_cache_list is not None and len(image_cache_list) != len(pdf_bytes_list):
- raise ValueError("image_cache_list must have the same length as pdf_bytes_list")
-
- doc_contexts = []
- try:
- total_pages = 0
- for doc_index, (pdf_bytes, lang) in enumerate(zip(pdf_bytes_list, lang_list)):
- pdf_doc = PDFDocument(pdf_bytes)
- _ocr_enable = _get_ocr_enable(pdf_doc, parse_method)
- try:
- page_count = pdf_doc.page_count
- context = {
- "doc_index": doc_index,
- "pdf_bytes": pdf_bytes,
- "pdf_doc": pdf_doc,
- "page_count": page_count,
- "next_page_idx": 0,
- "middle_json": [],
- "model_list": [],
- "lang": lang,
- "ocr_enable": _ocr_enable,
- "page_index_map": page_index_map_list[doc_index] if page_index_map_list is not None else None,
- "image_cache": image_cache_list[doc_index] if image_cache_list is not None else None,
- "closed": False,
- }
- except Exception:
- pdf_doc.close()
- raise
- total_pages += page_count
- doc_contexts.append(context)
-
- if total_pages == 0:
- _emit_zero_page_contexts(
- doc_contexts,
- on_doc_ready,
- client_side_output_generation=client_side_output_generation,
- )
- return
-
- window_size = get_processing_window_size(default=64)
- total_batches = (total_pages + window_size - 1) // window_size
- logger.info(
- f"Pipeline processing-window multi-file run. doc_count={len(doc_contexts)}, "
- f"total_pages={total_pages}, window_size={window_size}, total_batches={total_batches}"
- )
-
- _emit_zero_page_contexts(
- doc_contexts,
- on_doc_ready,
- client_side_output_generation=client_side_output_generation,
- )
- processed_pages = 0
- infer_start = time.time()
- progress_bar = None
- last_append_end_time = None
- try:
- batch_index = 0
- while processed_pages < total_pages:
- batch_index += 1
- batch_capacity = window_size
- batch_images = []
- batch_slices = []
- batch_payloads = []
-
- for context in doc_contexts:
- if batch_capacity == 0:
- break
- page_start = context["next_page_idx"]
- if page_start >= context["page_count"]:
- continue
- take_count = min(batch_capacity, context["page_count"] - page_start)
- page_end = page_start + take_count - 1
- images_list = load_images_from_pdf_bytes_range(
- pdf_bytes=context["pdf_bytes"],
- start_page_id=page_start,
- end_page_id=page_end,
- image_type=ImageType.PIL,
- )
- images_with_extra_info = [
- (image_dict["img_pil"], context["ocr_enable"], context["lang"]) for image_dict in images_list
- ]
- batch_images.extend(images_with_extra_info)
- batch_slices.append(
- {
- "doc_index": context["doc_index"],
- "page_start": page_start,
- "page_end": page_end,
- "count": take_count,
- }
- )
- batch_payloads.append((context, images_list, page_start, take_count))
- context["next_page_idx"] = page_end + 1
- batch_capacity -= take_count
-
- logger.info(
- f"Pipeline processing window batch {batch_index}/{total_batches}: "
- f"{processed_pages + len(batch_images)}/{total_pages} pages, "
- f"batch_pages={len(batch_images)}, doc_slices={_format_doc_slices(batch_slices)}"
- )
-
- try:
- batch_results = batch_image_analyze(
- batch_images,
- formula_enable=formula_enable,
- table_enable=table_enable,
- )
- if progress_bar is None:
- progress_bar = tqdm(total=total_pages, desc="Processing pages")
- else:
- exclude_progress_bar_idle_time(
- progress_bar,
- last_append_end_time,
- now=time.time(),
- )
-
- result_offset = 0
- for context, images_list, page_start, take_count in batch_payloads:
- result_slice = batch_results[result_offset : result_offset + take_count]
- append_batch_results_to_middle_json(
- context["middle_json"],
- result_slice,
- images_list,
- context["pdf_doc"],
- page_start_index=page_start,
- ocr_enable=context["ocr_enable"],
- model_list=context["model_list"],
- page_index_map=context["page_index_map"],
- progress_bar=progress_bar,
- image_cache=context["image_cache"],
- )
- result_offset += take_count
-
- if context["next_page_idx"] >= context["page_count"] and not context["closed"]:
- _finalize_processing_window_context(
- context,
- on_doc_ready,
- client_side_output_generation=client_side_output_generation,
- )
- finally:
- for _context, images_list, _page_start, _take_count in batch_payloads:
- _close_images(images_list)
- images_list.clear()
-
- last_append_end_time = time.time()
- processed_pages += len(batch_images)
- finally:
- if progress_bar is not None:
- progress_bar.close()
-
- infer_time = round(time.time() - infer_start, 2)
- if infer_time > 0:
- logger.debug(
- f"processing-window multi-file infer finished, cost: {infer_time}, "
- f"speed: {round(total_pages / infer_time, 3)} page/s"
- )
- finally:
- for context in doc_contexts:
- if not context["closed"]:
- context["pdf_doc"].close()
- context["closed"] = True
-
-
-def batch_image_analyze(
- images_with_extra_info: list[tuple[Image.Image, bool, str]],
- formula_enable: bool = True,
- table_enable: bool = True,
-) -> list[list[dict[str, Any]]]:
- from .batch_analyze import BatchAnalyze
-
- model_manager = ModelSingleton()
-
- device = get_device()
-
- if str(device).startswith("npu"):
- try:
- import torch_npu
-
- if torch_npu.npu.is_available():
- torch_npu.npu.set_compile_mode(jit_compile=False)
- except Exception as e:
- raise RuntimeError(
- "NPU is selected as device, but torch_npu is not available. "
- "Please ensure that the torch_npu package is installed correctly."
- ) from e
-
- gpu_memory = get_vram(device)
- if gpu_memory >= 32:
- batch_ratio = 16
- elif gpu_memory >= 16:
- batch_ratio = 8
- elif gpu_memory >= 8:
- batch_ratio = 4
- elif gpu_memory >= 6:
- batch_ratio = 2
- else:
- batch_ratio = 1
- logger.info(f"GPU Memory: {gpu_memory} GB, Batch Ratio: {batch_ratio}. ")
-
- # 检测torch的版本号
- import torch
- from packaging import version
-
- device_type = os.getenv("MINERU_LMDEPLOY_DEVICE", "")
- if device_type.lower() in ["corex"]:
- enable_ocr_det_batch = False
- else:
- if version.parse(torch.__version__) >= version.parse("2.8.0"):
- os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
- enable_ocr_det_batch = True
-
- batch_model = BatchAnalyze(model_manager, batch_ratio, formula_enable, table_enable, enable_ocr_det_batch)
- results = batch_model(images_with_extra_info)
-
- clean_memory(get_device())
-
- return results
diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.py
deleted file mode 100644
index c41cb129..00000000
--- a/mineru/backend/pipeline/pipeline_magic_model.py
+++ /dev/null
@@ -1,572 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from copy import deepcopy
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
-
-from ...render.merge import _merge_para_text
-from ...types import EMPTY_BBOX, BBox, Block, BlockType, ContentType, Line, Span
-from ...utils.guess_suffix_or_lang import guess_language_by_text
-from ...utils.pdf_document import PDFPage
-from ..utils.boxbase import calculate_overlap_area_2_minbox_area_ratio, calculate_overlap_area_in_bbox1_area_ratio
-from ..utils.span_block_fix import (
- is_vertical_text_block_by_spans,
- line_sort_spans_by_left_to_right,
- merge_spans_to_line,
- merge_spans_to_vertical_line,
- vertical_line_sort_spans_from_top_to_bottom,
-)
-from ..utils.span_pre_proc import SpanBlockMatcher, txt_spans_extract
-from ..utils.visual_magic_model_utils import (
- fallback_inline_caption_fragments,
- fallback_leading_table_continuation_captions,
- find_best_visual_parent,
-)
-
-if TYPE_CHECKING:
- from PIL.Image import Image as PILImage
-
-
-@dataclass(slots=True)
-class PipelineLayoutBlockDraft:
- """Pipeline layout_det 的内部适配层,隔离模型输出字段和 middle_json block。"""
-
- raw_label: str
- type: str
- bbox: BBox
- index: int
- score: float | None = None
- text: str | list[str] = ""
- html: str = ""
- latex: str = ""
- angle: int | None = None
-
- @classmethod
- def from_layout_det(
- cls,
- layout_det: dict[str, Any],
- *,
- block_type: str,
- bbox: BBox,
- index: int,
- score: float | None,
- ) -> PipelineLayoutBlockDraft:
- """显式抽取 layout_det 中允许进入转换阶段的字段,避免 raw dict 直灌 Block。"""
- return cls(
- raw_label=str(layout_det.get("label", "")),
- type=block_type,
- bbox=bbox,
- index=index,
- score=score,
- text=layout_det.get("text", ""),
- html=layout_det.get("html", ""),
- latex=layout_det.get("latex", ""),
- angle=layout_det.get("angle"),
- )
-
- def to_middle_block(self) -> Block:
- """生成 middle_json block 包装,raw 载荷保留在 draft 中按 index 查取。"""
- return Block(
- index=self.index,
- type=self.type,
- bbox=self.bbox,
- score=self.score,
- angle=self.angle,
- )
-
-
-class MagicModel:
- PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES: dict[str, str] = {
- "abstract": BlockType.ABSTRACT,
- "algorithm": BlockType.CODE,
- "aside_text": BlockType.ASIDE_TEXT,
- "chart": BlockType.CHART,
- "content": BlockType.INDEX,
- "display_formula": BlockType.INTERLINE_EQUATION,
- "doc_title": BlockType.DOC_TITLE,
- "figure_title": BlockType.CAPTION,
- "footer": BlockType.FOOTER,
- "footer_image": BlockType.FOOTER,
- "footnote": BlockType.PAGE_FOOTNOTE,
- "formula_number": BlockType.FORMULA_NUMBER,
- "header": BlockType.HEADER,
- "header_image": BlockType.HEADER,
- "image": BlockType.IMAGE,
- "number": BlockType.PAGE_NUMBER,
- "paragraph_title": BlockType.PARAGRAPH_TITLE,
- "reference_content": BlockType.REF_TEXT,
- "seal": BlockType.IMAGE,
- "table": BlockType.TABLE,
- "text": BlockType.TEXT,
- "vertical_text": BlockType.VERTICAL_TEXT,
- "vision_footnote": BlockType.FOOTNOTE,
- }
-
- VISUAL_MAIN_TYPES: set[str] = {
- BlockType.IMAGE,
- BlockType.TABLE,
- BlockType.CHART,
- BlockType.CODE,
- }
- VISUAL_CHILD_TYPES: set[str] = {
- BlockType.CAPTION,
- BlockType.FOOTNOTE,
- }
- VISUAL_TYPE_MAPPING: dict[str, dict[str, str]] = {
- BlockType.IMAGE: {
- "body": BlockType.IMAGE_BODY,
- "caption": BlockType.IMAGE_CAPTION,
- "footnote": BlockType.IMAGE_FOOTNOTE,
- },
- BlockType.TABLE: {
- "body": BlockType.TABLE_BODY,
- "caption": BlockType.TABLE_CAPTION,
- "footnote": BlockType.TABLE_FOOTNOTE,
- },
- BlockType.CHART: {
- "body": BlockType.CHART_BODY,
- "caption": BlockType.CHART_CAPTION,
- "footnote": BlockType.CHART_FOOTNOTE,
- },
- BlockType.CODE: {
- "body": BlockType.CODE_BODY,
- "caption": BlockType.CODE_CAPTION,
- "footnote": BlockType.CODE_FOOTNOTE,
- },
- }
-
- def __init__(
- self,
- page_model_info: dict[str, Any],
- pdf_page: PDFPage,
- scale: float = 1,
- page_pil_img: PILImage | None = None,
- page_w: int = 0,
- page_h: int = 0,
- ocr_enable: bool = False,
- ) -> None:
- self.__page_model_info = page_model_info
- self.page_inline_formula: list[Span] = []
- self.page_ocr_res: list[Span] = []
- self.page_blocks: list[Block] = []
- self.image_groups: list[dict[str, Any]] = []
- self.table_groups: list[dict[str, Any]] = []
- self.chart_groups: list[dict[str, Any]] = []
- self.__layout_draft_by_index: dict[int, PipelineLayoutBlockDraft] = {}
- self.__layout_det_by_index: dict[int, dict[str, Any]] = {}
- self.__scale = scale
- self.__fix_axis() # bbox坐标修正,删除高度或者宽度小于等于0的spans
- self.__post_process() # index重排,填充行内公式和文本span
- if not ocr_enable:
- # Bad code
- virtual_block = (0, 0, page_w, page_h, None, None, None, "text")
- self.page_ocr_res = txt_spans_extract(
- pdf_page,
- self.page_ocr_res,
- page_pil_img,
- scale,
- [virtual_block],
- [],
- )
- self.page_text_inline_formula_spans = self.page_inline_formula + self.page_ocr_res
-
- for layout_det in self.__page_model_info["layout_dets"]:
- if layout_det.get("label") in self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES:
- block_bbox = layout_det["bbox"]
- block_type = self.PP_DOCLAYOUT_V2_LABELS_TO_BLOCK_TYPES[layout_det["label"]]
- block_index = layout_det["index"]
- block_score = layout_det["score"]
- draft = PipelineLayoutBlockDraft.from_layout_det(
- layout_det,
- block_type=block_type,
- bbox=block_bbox,
- index=block_index,
- score=block_score,
- )
- block = draft.to_middle_block()
- self.__layout_draft_by_index[block_index] = draft
- self.__layout_det_by_index[block_index] = layout_det
- if self.__is_seal_layout_block(layout_det):
- block.sub_type = "seal"
- self.page_blocks.append(block)
-
- self.page_blocks.sort(key=lambda x: x.index)
- self.__build_page_blocks()
- fallback_inline_caption_fragments(self.page_blocks, self.VISUAL_MAIN_TYPES)
- fallback_leading_table_continuation_captions(self.page_blocks, self.VISUAL_MAIN_TYPES)
- self.__classify_visual_blocks()
- self.__build_return_blocks()
-
- @staticmethod
- def __fix_text_block(block: Block) -> Block:
- if block.type == BlockType.TEXT and is_vertical_text_block_by_spans(block._fix_spans):
- # layout 偶发会把竖排正文识别为横排 text,这里用旧版 span 高宽比规则兜底。
- block.type = BlockType.VERTICAL_TEXT
-
- if block.type == BlockType.VERTICAL_TEXT:
- # 如果是纵向文本块,则按纵向lines处理
- block_lines = merge_spans_to_vertical_line(block._fix_spans)
- sort_block_lines = vertical_line_sort_spans_from_top_to_bottom(block_lines)
- else:
- block_lines = merge_spans_to_line(block._fix_spans)
- sort_block_lines = line_sort_spans_by_left_to_right(block_lines)
-
- if block.type == BlockType.CODE:
- for line in sort_block_lines:
- line._is_list_start = True
- _temp_block = Block(index=0, type="", bbox=EMPTY_BBOX, lines=sort_block_lines)
- code_content = _merge_para_text(_temp_block, escape_markdown=False, list_line_break="\n")
- guess_lang = guess_language_by_text(code_content)
- if guess_lang not in ["txt", "unknown"]:
- block.sub_type = "code"
- block.guess_lang = guess_lang
-
- block.lines = sort_block_lines
- block._fix_spans = []
- return block
-
- @staticmethod
- def __is_inline_formula_block(layout_det: dict[str, Any]) -> bool:
- return layout_det.get("label") == "inline_formula" or layout_det.get("cls_id") == 15
-
- @staticmethod
- def __is_ocr_text_block(layout_det: dict[str, Any]) -> bool:
- return layout_det.get("label") == "ocr_text"
-
- @staticmethod
- def __is_seal_layout_block(layout_det: dict[str, Any]) -> bool:
- """判断原始 layout 是否为印章,输出层会将其规范为 image 子类型。"""
- return layout_det.get("label") == "seal"
-
- @staticmethod
- def __normalize_seal_text(content: str | list[str]) -> str:
- """将 seal OCR 的列表或字符串结果规范为 VLM 一致的多行字符串。"""
- if isinstance(content, list):
- return "\n".join(str(item) for item in content if str(item).strip())
- if isinstance(content, str):
- return content.strip()
- return ""
-
- def __draft_payload(self, block: Block, field_name: str, default: Any = "") -> Any:
- """从 pipeline draft 读取转换载荷,避免把 raw 字段挂到 middle_json Block。"""
- draft = self.__layout_draft_by_index.get(block.index)
- if draft is None:
- return default
- return getattr(draft, field_name, default)
-
- def __build_return_blocks(self) -> None:
- self.preproc_blocks: list[Block] = []
- self.discarded_blocks: list[Block] = []
- for block in self.page_blocks:
- if block.type in [
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.PAGE_NUMBER,
- BlockType.ASIDE_TEXT,
- BlockType.PAGE_FOOTNOTE,
- ]:
- self.discarded_blocks.append(block)
- else:
- # 单独处理code block
- if block.type in [BlockType.CODE]:
- for sub_block in block.blocks:
- if sub_block.type == BlockType.CODE_BODY:
- block.sub_type = sub_block.sub_type or "algorithm"
- sub_block.sub_type = ""
- if block.sub_type == "code":
- block.guess_lang = sub_block.guess_lang or "txt"
- sub_block.guess_lang = ""
-
- self.preproc_blocks.append(block)
-
- def __build_page_blocks(self) -> None:
- span_type = "unknown"
- span_matcher = SpanBlockMatcher(self.page_text_inline_formula_spans)
- for block in self.page_blocks:
- if block.type in [
- BlockType.ABSTRACT,
- BlockType.CODE,
- BlockType.ASIDE_TEXT,
- BlockType.INDEX,
- BlockType.DOC_TITLE,
- BlockType.CAPTION,
- BlockType.FOOTER,
- BlockType.PAGE_FOOTNOTE,
- BlockType.FORMULA_NUMBER,
- BlockType.HEADER,
- BlockType.PAGE_NUMBER,
- BlockType.PARAGRAPH_TITLE,
- BlockType.REF_TEXT,
- BlockType.TEXT,
- BlockType.VERTICAL_TEXT,
- BlockType.FOOTNOTE,
- ]:
- span_type = ContentType.TEXT
- elif block.type in [BlockType.IMAGE]:
- span_type = ContentType.IMAGE
- elif block.type in [BlockType.TABLE]:
- span_type = ContentType.TABLE
- elif block.type in [BlockType.CHART]:
- span_type = ContentType.CHART
- elif block.type in [BlockType.INTERLINE_EQUATION]:
- span_type = ContentType.INTERLINE_EQUATION
-
- if span_type in [
- ContentType.IMAGE,
- ContentType.TABLE,
- ContentType.CHART,
- ContentType.INTERLINE_EQUATION,
- ]:
- span = Span(type=span_type, bbox=block.bbox)
- if span_type == ContentType.IMAGE and block.sub_type == "seal":
- seal_text = self.__normalize_seal_text(self.__draft_payload(block, "text", ""))
- if seal_text:
- span.content = seal_text
- if span_type == ContentType.TABLE:
- span.content = self.__draft_payload(block, "html", "")
- if span_type == ContentType.INTERLINE_EQUATION:
- span.content = self.__draft_payload(block, "latex", "")
-
- # 构造line对象
- spans = [span]
- line = Line(spans=spans, bbox=block.bbox)
- block.lines = [line]
- else:
- # span填充
- if block.type == BlockType.FORMULA_NUMBER:
- block_spans = span_matcher.collect_for_block(
- block.bbox,
- overlap_ratio_getter=self.__formula_number_overlap_ratio,
- )
- else:
- block_spans = span_matcher.collect_for_block(block.bbox)
-
- block._fix_spans = block_spans
- block = self.__fix_text_block(block)
- self.page_text_inline_formula_spans = span_matcher.remaining_spans()
-
- @staticmethod
- def __formula_number_overlap_ratio(span: Span, block_bbox: BBox) -> float:
- """公式编号框较窄时,沿用最小框重叠比例提高回填召回。"""
- return max(
- calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block_bbox),
- calculate_overlap_area_2_minbox_area_ratio(span.bbox, block_bbox),
- )
-
- def __fix_axis(self) -> None:
- need_remove_list: list[dict[str, Any]] = []
- layout_dets = self.__page_model_info["layout_dets"]
- for layout_det in layout_dets:
- x0, y0, x1, y1 = layout_det["bbox"]
- bbox = [
- int(x0 / self.__scale),
- int(y0 / self.__scale),
- int(x1 / self.__scale),
- int(y1 / self.__scale),
- ]
- layout_det["bbox"] = bbox
- # 删除高度或者宽度小于等于2的spans
- if bbox[2] - bbox[0] <= 2 or bbox[3] - bbox[1] <= 2:
- need_remove_list.append(layout_det)
- for need_remove in need_remove_list:
- layout_dets.remove(need_remove)
-
- def __post_process(self) -> None:
- next_index = 1
- layout_dets = self.__page_model_info["layout_dets"]
- for layout_det in layout_dets:
- if self.__is_inline_formula_block(layout_det):
- layout_det.pop("index", None)
- self.page_inline_formula.append(
- Span(
- type=ContentType.INLINE_EQUATION,
- bbox=layout_det["bbox"],
- content=layout_det["latex"],
- score=layout_det["score"],
- )
- )
- continue
-
- if self.__is_ocr_text_block(layout_det):
- self.page_ocr_res.append(
- Span(
- type=ContentType.TEXT,
- bbox=layout_det["bbox"],
- content=layout_det["text"],
- score=layout_det["score"],
- )
- )
- continue
-
- if "index" in layout_det:
- layout_det["index"] = next_index
- next_index += 1
-
- def __classify_visual_blocks(self) -> None:
- if not self.page_blocks:
- return
-
- ordered_blocks = sorted(self.page_blocks, key=lambda x: x.index)
- original_type_by_index = {block.index: block.type for block in ordered_blocks}
- position_by_index = {block.index: pos for pos, block in enumerate(ordered_blocks)}
- main_blocks = [block for block in ordered_blocks if original_type_by_index[block.index] in self.VISUAL_MAIN_TYPES]
- child_blocks = [block for block in ordered_blocks if original_type_by_index[block.index] in self.VISUAL_CHILD_TYPES]
-
- child_parent_map: dict[int, int | None] = {}
- grouped_children: dict[int, dict[str, list[Block]]] = {
- main_block.index: {"captions": [], "footnotes": []} for main_block in main_blocks
- }
-
- for child_block in child_blocks:
- parent_block = self.__find_best_visual_parent(
- child_block,
- main_blocks,
- ordered_blocks,
- original_type_by_index,
- position_by_index,
- )
- child_parent_map[child_block.index] = None if parent_block is None else parent_block.index
-
- for child_block in child_blocks:
- original_child_type = original_type_by_index[child_block.index]
- parent_index = child_parent_map[child_block.index]
-
- if parent_index is None:
- child_block.type = BlockType.TEXT
- self.__sync_layout_det_type(child_block.index, BlockType.TEXT)
- continue
-
- parent_type = original_type_by_index[parent_index]
- child_kind = self.__child_kind(original_child_type)
- mapped_type = self.VISUAL_TYPE_MAPPING[parent_type][child_kind]
- child_block.type = mapped_type
- self.__sync_layout_det_type(child_block.index, mapped_type)
- grouped_children[parent_index][f"{child_kind}s"].append(child_block)
-
- self.image_groups = []
- self.table_groups = []
- self.chart_groups = []
-
- rebuilt_page_blocks: list[Block] = []
- for block in ordered_blocks:
- original_block_type = original_type_by_index[block.index]
-
- if original_block_type in self.VISUAL_CHILD_TYPES:
- if child_parent_map[block.index] is None:
- rebuilt_page_blocks.append(block)
- continue
-
- if original_block_type not in self.VISUAL_MAIN_TYPES:
- rebuilt_page_blocks.append(block)
- continue
-
- mapping = self.VISUAL_TYPE_MAPPING[original_block_type]
- body_block = self.__make_child_block(block, mapping["body"])
- if original_block_type in [BlockType.IMAGE, BlockType.CHART]:
- body_block.sub_type = ""
- captions = sorted(
- [self.__make_child_block(caption, mapping["caption"]) for caption in grouped_children[block.index]["captions"]],
- key=lambda x: x.index,
- )
- footnotes = sorted(
- [
- self.__make_child_block(footnote, mapping["footnote"])
- for footnote in grouped_children[block.index]["footnotes"]
- ],
- key=lambda x: x.index,
- )
-
- self.__sync_layout_det_type(block.index, mapping["body"])
-
- group_info = {
- f"{original_block_type}_body": body_block,
- f"{original_block_type}_caption_list": captions,
- f"{original_block_type}_footnote_list": footnotes,
- }
- if original_block_type == BlockType.IMAGE:
- self.image_groups.append(group_info)
- elif original_block_type == BlockType.TABLE:
- self.table_groups.append(group_info)
- else:
- self.chart_groups.append(group_info)
-
- two_layer_block = Block(
- index=block.index,
- type=original_block_type,
- bbox=block.bbox,
- blocks=[body_block, *captions, *footnotes],
- score=block.score,
- )
- if original_block_type in [BlockType.IMAGE, BlockType.CHART] and block.sub_type:
- two_layer_block.sub_type = block.sub_type
- # 对blocks按index排序
- two_layer_block.blocks.sort(key=lambda x: x.index)
- rebuilt_page_blocks.append(two_layer_block)
-
- self.page_blocks = rebuilt_page_blocks
-
- def __find_best_visual_parent(
- self,
- child_block: Block,
- main_blocks: list[Block],
- ordered_blocks: list[Block],
- original_type_by_index: dict[int, str],
- position_by_index: dict[int, int],
- ) -> Block | None:
- child_type = original_type_by_index[child_block.index]
- if child_type not in self.VISUAL_CHILD_TYPES:
- return None
-
- return find_best_visual_parent(
- child_block,
- main_blocks,
- ordered_blocks,
- position_by_index,
- main_type_to_visual_type={block_type: block_type for block_type in self.VISUAL_MAIN_TYPES},
- type_by_index=original_type_by_index,
- )
-
- @staticmethod
- def __child_kind(block_type: str) -> str:
- if block_type == BlockType.CAPTION:
- return "caption"
- return "footnote"
-
- @staticmethod
- def __make_child_block(block: Block, block_type: str) -> Block:
- new_block = deepcopy(block)
- new_block.type = block_type
- return new_block
-
- def __sync_layout_det_type(self, block_index: int, block_type: str) -> None:
- layout_det = self.__layout_det_by_index.get(block_index)
- if layout_det is not None:
- layout_det["type"] = block_type
-
- def get_page_blocks(self) -> list[Block]:
- return self.page_blocks
-
- def get_preproc_blocks(self) -> list[Block]:
- return self.preproc_blocks
-
- def get_discarded_blocks(self) -> list[Block]:
- return self.discarded_blocks
-
- def get_imgs(self) -> list[dict[str, Any]]:
- return self.image_groups
-
- def get_tables(self) -> list[dict[str, Any]]:
- return self.table_groups
-
- def get_charts(self) -> list[dict[str, Any]]:
- return self.chart_groups
-
- def get_image_blocks(self) -> list[Block]:
- return [block for block in self.page_blocks if block.type == BlockType.IMAGE]
-
- def get_table_blocks(self) -> list[Block]:
- return [block for block in self.page_blocks if block.type == BlockType.TABLE]
-
- def get_chart_blocks(self) -> list[Block]:
- return [block for block in self.page_blocks if block.type == BlockType.CHART]
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index ebe95f74..bf2c2211 100644
--- a/mineru/backend/utils/middle_json_utils.py
+++ b/mineru/backend/utils/middle_json_utils.py
@@ -1,4 +1,4 @@
-"""Shared middle_json build template for PDF backends (pipeline / vlm / hybrid).
+"""Shared middle_json build template for current PDF backends.
Each backend still owns its ``init``, ``append``, and ``finalize`` helpers;
this module also provides shared post-processing helpers that were duplicated
@@ -16,7 +16,7 @@ from ...utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_needed
from ...utils.page_index import resolve_output_page_idx
from ...utils.pdf_document import PDFDocument, PDFPage
from .span_pre_proc import _clear_post_ocr_fallback, _restore_post_ocr_fallback
-from ..pipeline.model_init import run_ocr_inference
+from ..local_model_runtime import run_ocr_inference
T = TypeVar("T")
diff --git a/mineru/backend/utils/ocr_det_utils.py b/mineru/backend/utils/ocr_det_utils.py
index 9cf76fa0..96d5403a 100644
--- a/mineru/backend/utils/ocr_det_utils.py
+++ b/mineru/backend/utils/ocr_det_utils.py
@@ -15,7 +15,7 @@ OCR_DET_PADDING = 50
def _get_ch_ocr_det_model() -> Any:
"""获取默认中文 OCR 检测模型,当前 ch 已对应轻量 PP-OCRv6 配置。"""
try:
- from ..pipeline.model_init import AtomModelSingleton
+ from ..local_model_runtime import AtomModelSingleton
except Exception as e:
logger.error(
"Failed to import AtomModelSingleton, OCR detection will not work. If you want to use OCR features, "
diff --git a/mineru/backend/utils/para_block_utils.py b/mineru/backend/utils/para_block_utils.py
index c5b30e0a..872ea386 100644
--- a/mineru/backend/utils/para_block_utils.py
+++ b/mineru/backend/utils/para_block_utils.py
@@ -389,7 +389,7 @@ def _last_non_empty_content(lines: list[Line]) -> str:
def _has_mergeable_block_bbox_relation(current_block: Block, previous_block: Block) -> bool:
- """复刻 pipeline text 合并的核心几何条件:当前块上边界进入前块范围。"""
+ """复用本地 Hybrid text 合并的核心几何条件:当前块上边界进入前块范围。"""
return current_block.bbox[1] < previous_block.bbox[3]
@@ -411,7 +411,7 @@ def _can_auto_merge_vertical_text_blocks(
current_metric_lines: list[Line],
previous_metric_lines: list[Line],
) -> bool:
- """复刻 pipeline 纵排文本块合并规则,几何优先使用 OCR det 行。"""
+ """复用本地 Hybrid 纵排文本块合并规则,几何优先使用 OCR det 行。"""
first_metric_line = current_metric_lines[0]
last_metric_line = previous_metric_lines[-1]
first_line_width = _line_width(first_metric_line)
diff --git a/mineru/backend/utils/visual_magic_model_utils.py b/mineru/backend/utils/visual_magic_model_utils.py
index 1b699f32..11be3d97 100644
--- a/mineru/backend/utils/visual_magic_model_utils.py
+++ b/mineru/backend/utils/visual_magic_model_utils.py
@@ -670,7 +670,7 @@ def are_bboxes_overlapping(first_bbox: BBox, second_bbox: BBox) -> bool:
def block_type(block: Block, type_by_index: dict[int, str] | None = None) -> str:
- """读取块类型;pipeline 会传入改写前的原始类型映射。"""
+ """读取块类型;本地 Hybrid 会传入改写前的原始类型映射。"""
if type_by_index is not None:
return type_by_index[block.index]
return block.type
diff --git a/mineru/cli_old/api_request.py b/mineru/cli_old/api_request.py
index 7c91e393..42ca0b70 100644
--- a/mineru/cli_old/api_request.py
+++ b/mineru/cli_old/api_request.py
@@ -10,6 +10,8 @@ from mineru.utils.backend_options import (
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,
@@ -67,11 +69,15 @@ def validate_parse_method(parse_method: str) -> str:
def validate_parse_backend(backend: str) -> str:
- """校验公开 API 允许的解析后端,避免旧入口名进入下游执行链路。"""
+ """校验公开 API 允许的解析后端,保留 hidden alias 供联合解析决定 effort。"""
try:
- return normalize_public_backend(backend)
+ 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:
@@ -83,7 +89,7 @@ def validate_parse_effort(effort: str) -> str:
def resolve_parse_backend_and_effort(backend: str, effort: str) -> tuple[str, str]:
- """联合校验公开解析后端和 effort,确保旧 VLM 值统一落到 Hybrid high。"""
+ """联合校验公开解析后端和 effort,确保旧 pipeline/VLM 值落到对应 Hybrid effort。"""
try:
return resolve_backend_and_effort(backend, effort)
except ValueError as exc:
@@ -118,7 +124,6 @@ async def parse_request_form(
str,
Form(
description="""The backend for parsing:
-- pipeline: More general, supports multiple languages, hallucination-free.
- hybrid-engine: Hybrid parsing via local computing power, supports multiple languages. Use effort to switch low/medium/high behavior.
- hybrid-http-client: Hybrid parsing via remote computing power but requires a little local computing power(client suitable for openai-compatible servers), supports multiple languages. Use effort to switch low/medium/high behavior.""",
json_schema_extra=BACKEND_SCHEMA_EXTRA,
@@ -137,7 +142,7 @@ async def parse_request_form(
parse_method: Annotated[
str,
Form(
- description="""(Adapted only for pipeline and hybrid backend)The method for parsing PDF:
+ 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
diff --git a/mineru/cli_old/client.py b/mineru/cli_old/client.py
index ddeb395a..04b38eab 100644
--- a/mineru/cli_old/client.py
+++ b/mineru/cli_old/client.py
@@ -39,6 +39,7 @@ 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,
@@ -96,13 +97,13 @@ def normalize_backend_option(
param: Optional[click.Parameter],
value: str,
) -> str:
- """校验 CLI backend,legacy VLM 值保留到后续 backend+effort 联合解析。"""
+ """校验 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_VLM_BACKEND_ALIASES:
+ if normalized_value in LEGACY_PIPELINE_BACKEND_ALIASES or normalized_value in LEGACY_VLM_BACKEND_ALIASES:
return normalized_value
return normalized_backend
@@ -405,7 +406,6 @@ def build_visualization_jobs(
backend: str,
parse_method: str,
) -> list[VisualizationJob]:
- draw_span = backend.startswith("pipeline")
return [
VisualizationJob(
document_stem=document.stem,
@@ -418,7 +418,7 @@ def build_visualization_jobs(
parse_method,
is_office=document.suffix in office_suffixes,
),
- draw_span=draw_span,
+ draw_span=False,
)
for document in planned_task.documents
]
@@ -589,54 +589,11 @@ def collect_input_documents(
return collected
-def plan_pipeline_tasks(
- documents: list[InputDocument],
- processing_window_size: int,
-) -> list[PlannedTask]:
- bins: list[PlannedTask] = []
- sorted_docs = sorted(
- documents,
- key=lambda doc: (-doc.effective_pages, doc.order),
- )
-
- for document in sorted_docs:
- if document.effective_pages > processing_window_size:
- bins.append(
- PlannedTask(
- index=len(bins) + 1,
- documents=[document],
- total_pages=document.effective_pages,
- )
- )
- continue
-
- candidates = [task for task in bins if task.total_pages + document.effective_pages <= processing_window_size]
- if candidates:
- selected = min(candidates, key=lambda task: (task.total_pages, task.index))
- selected.documents.append(document)
- selected.total_pages += document.effective_pages
- continue
-
- bins.append(
- PlannedTask(
- index=len(bins) + 1,
- documents=[document],
- total_pages=document.effective_pages,
- )
- )
-
- for index, task in enumerate(bins, start=1):
- task.index = index
- return bins
-
-
def plan_tasks(
documents: list[InputDocument],
backend: str,
processing_window_size: int,
) -> list[PlannedTask]:
- if backend == "pipeline":
- return plan_pipeline_tasks(documents, processing_window_size)
return [
PlannedTask(index=index, documents=[document], total_pages=document.effective_pages)
for index, document in enumerate(documents, start=1)
@@ -949,9 +906,7 @@ async def run_orchestrated_cli(
planned_tasks = plan_tasks(
documents=documents,
backend=backend,
- processing_window_size=server_health.processing_window_size
- if backend == "pipeline"
- else DEFAULT_PROCESSING_WINDOW_SIZE,
+ processing_window_size=DEFAULT_PROCESSING_WINDOW_SIZE,
)
progress = build_task_execution_progress(planned_tasks)
concurrency = resolve_submit_concurrency(
@@ -1047,7 +1002,7 @@ async def run_orchestrated_cli(
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 'pipeline' and 'hybrid-*'.""",
+ Adapted only for the case where the backend is set to 'hybrid-*'.""",
)
@click.option(
"-b",
@@ -1059,7 +1014,6 @@ async def run_orchestrated_cli(
metavar="[" + "|".join(PUBLIC_BACKEND_CHOICES) + "]",
help="""\b
the backend for parsing pdf:
- pipeline: More general.
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.""",
@@ -1090,7 +1044,7 @@ async def run_orchestrated_cli(
help="""
Input the languages in the pdf (if known) to improve OCR accuracy.
Without languages specified, 'ch' will be used by default.
- Adapted only for the case where the backend is set to 'pipeline' and 'hybrid-*'.
+ Adapted only for the case where the backend is set to 'hybrid-*'.
""",
)
@click.option(
diff --git a/mineru/cli_old/client_side_output.py b/mineru/cli_old/client_side_output.py
index 36182f3c..63dc4b56 100644
--- a/mineru/cli_old/client_side_output.py
+++ b/mineru/cli_old/client_side_output.py
@@ -8,11 +8,11 @@ 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
+from mineru.utils.backend_options import DEFAULT_HYBRID_EFFORT, normalize_backend, resolve_backend_and_effort
from mineru.utils.title_level_postprocess import finalize_client_side_pages
from mineru.version import __version__
-PDF_BACKENDS = {"pipeline", "hybrid"}
+PDF_BACKENDS = {"hybrid"}
def _write_json(path: Path, payload: Any) -> None:
@@ -31,8 +31,6 @@ def _normalize_client_side_backend(backend: str) -> str:
backend = normalize_backend(backend)
except ValueError:
pass
- if backend == "pipeline" or backend.startswith("pipeline"):
- return "pipeline"
if backend.startswith("hybrid"):
return "hybrid"
raise ValueError(f"Unsupported middle json backend for client-side output generation: {backend}")
@@ -63,6 +61,7 @@ def regenerate_client_side_outputs(
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
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index 652566c9..8cc45e68 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -6,7 +6,6 @@ import importlib
import importlib.util
import json
import os
-from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Sequence
@@ -20,7 +19,7 @@ from mineru.cli_old.visualization import select_pages_for_pdf_visualization
from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.parser.base import ParseResult
from mineru.render import render_content_list, render_markdown, render_structured_content
-from mineru.utils.backend_options import DEFAULT_HYBRID_EFFORT, resolve_backend_and_effort
+from mineru.utils.backend_options import DEFAULT_BACKEND, DEFAULT_HYBRID_EFFORT, resolve_backend_and_effort
from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
from mineru.utils.engine_utils import get_vlm_engine
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_bytes
@@ -279,7 +278,7 @@ def _process_output(
logger.warning(f"Skipping span bbox visualization for {pdf_file_name}: {exc}")
if f_dump_orig_pdf:
- if process_mode in ["pipeline", "vlm"]:
+ if process_mode in ["hybrid", "vlm"]:
md_writer.write(
f"{pdf_file_name}_origin.pdf",
pdf_bytes,
@@ -351,100 +350,6 @@ def _process_output(
logger.debug(f"local output dir is {local_md_dir}")
-def _process_pipeline(
- output_dir: str,
- pdf_file_names: list[str],
- pdf_bytes_list: list[bytes],
- p_lang_list: list[str],
- parse_method: str,
- p_formula_enable: bool,
- p_table_enable: bool,
- f_draw_layout_bbox: bool,
- f_draw_span_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,
- client_side_output_generation: bool = False,
- page_index_map_list: list[list[int] | None] | None = None,
- broken_page_indices_list: list[list[int] | None] | None = None,
-) -> None:
- """处理pipeline后端逻辑"""
- from mineru.backend.pipeline.pipeline_analyze import doc_analyze_streaming as pipeline_doc_analyze_streaming
-
- md_writer_list = []
- local_output_info = []
- image_cache_list = [ImagePayloadCache() for _ in pdf_bytes_list]
- for idx, pdf_bytes in enumerate(pdf_bytes_list):
- pdf_file_name = pdf_file_names[idx]
- local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
- md_writer = FileBasedDataWriter(local_md_dir)
- md_writer_list.append(md_writer)
- local_output_info.append((pdf_file_name, local_image_dir, local_md_dir))
-
- output_futures = []
-
- def run_output_task(doc_index, middle_json, model_list):
- pdf_file_name, local_image_dir, local_md_dir = local_output_info[doc_index]
- md_writer = md_writer_list[doc_index]
- pdf_bytes = pdf_bytes_list[doc_index]
- retained_page_indices = page_index_map_list[doc_index] if page_index_map_list is not None else None
- broken_page_indices = broken_page_indices_list[doc_index] if broken_page_indices_list is not None else None
- logger.debug(f"Pipeline output start: doc{doc_index}")
- try:
- _process_output(
- middle_json,
- pdf_bytes,
- pdf_file_name,
- local_md_dir,
- local_image_dir,
- md_writer,
- f_draw_layout_bbox,
- f_draw_span_bbox,
- f_dump_orig_pdf,
- f_dump_md,
- f_dump_content_list,
- f_dump_middle_json,
- f_dump_model_output,
- f_make_md_mode,
- model_list,
- process_mode="pipeline",
- backend="pipeline",
- retained_page_indices=retained_page_indices,
- broken_page_indices=broken_page_indices,
- image_cache=image_cache_list[doc_index],
- )
- logger.debug(f"Pipeline output complete: doc{doc_index}")
- except Exception:
- logger.exception(f"Pipeline output failed: doc{doc_index}")
- raise
-
- with ThreadPoolExecutor(max_workers=1) as output_executor:
-
- def on_doc_ready(doc_index, model_list, middle_json: list, ocr_enable):
- logger.debug(f"Pipeline doc ready: doc{doc_index} pages={len(middle_json)} output_submitted=1")
- future = output_executor.submit(run_output_task, doc_index, middle_json, model_list)
- output_futures.append(future)
-
- pipeline_doc_analyze_streaming(
- pdf_bytes_list,
- p_lang_list,
- on_doc_ready,
- parse_method=parse_method,
- formula_enable=p_formula_enable,
- table_enable=p_table_enable,
- client_side_output_generation=client_side_output_generation,
- page_index_map_list=page_index_map_list,
- image_cache_list=image_cache_list,
- )
-
- for future in output_futures:
- future.result()
- return
-
-
def _process_hybrid(
output_dir: str,
pdf_file_names: list[str],
@@ -511,7 +416,7 @@ def _process_hybrid(
f_dump_model_output,
f_make_md_mode,
infer_result,
- process_mode="vlm",
+ 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,
@@ -585,7 +490,7 @@ async def _async_process_hybrid(
f_dump_model_output,
f_make_md_mode,
infer_result,
- process_mode="vlm",
+ 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,
@@ -658,7 +563,7 @@ def do_parse(
pdf_file_names: list[str],
pdf_bytes_list: list[bytes],
p_lang_list: list[str],
- backend: str = "pipeline",
+ backend: str = DEFAULT_BACKEND,
parse_method: str = "auto",
formula_enable: bool = True,
table_enable: bool = True,
@@ -704,15 +609,24 @@ def do_parse(
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 == "pipeline":
- _process_pipeline(
+ if backend.startswith("hybrid-"):
+ ensure_backend_dependencies(backend)
+ backend = backend[7:]
+
+ if backend == "engine" and effort != "low":
+ backend = get_vlm_engine(inference_engine="auto", is_async=False)
+
+ os.environ["MINERU_VLM_TABLE_ENABLE"] = str(table_enable)
+ os.environ["MINERU_VLM_FORMULA_ENABLE"] = "true"
+
+ _process_hybrid(
output_dir,
pdf_file_names,
pdf_bytes_list,
p_lang_list,
parse_method,
formula_enable,
- table_enable,
+ backend,
f_draw_layout_bbox,
f_draw_span_bbox,
f_dump_md,
@@ -721,47 +635,16 @@ def do_parse(
f_dump_orig_pdf,
f_dump_content_list,
f_make_md_mode,
- client_side_output_generation=client_side_output_generation,
+ 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:
- if backend.startswith("hybrid-"):
- ensure_backend_dependencies(backend)
- backend = backend[7:]
-
- if backend == "engine" and effort != "low":
- backend = get_vlm_engine(inference_engine="auto", is_async=False)
-
- os.environ["MINERU_VLM_TABLE_ENABLE"] = str(table_enable)
- os.environ["MINERU_VLM_FORMULA_ENABLE"] = "true"
-
- _process_hybrid(
- output_dir,
- pdf_file_names,
- pdf_bytes_list,
- p_lang_list,
- parse_method,
- formula_enable,
- backend,
- f_draw_layout_bbox,
- f_draw_span_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}'")
+ raise ValueError(f"Unsupported backend '{backend}'")
async def aio_do_parse(
@@ -769,7 +652,7 @@ async def aio_do_parse(
pdf_file_names: list[str],
pdf_bytes_list: list[bytes],
p_lang_list: list[str],
- backend: str = "pipeline",
+ backend: str = DEFAULT_BACKEND,
parse_method: str = "auto",
formula_enable: bool = True,
table_enable: bool = True,
@@ -817,16 +700,24 @@ async def aio_do_parse(
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 == "pipeline":
- # pipeline模式暂不支持异步,使用同步处理方式
- _process_pipeline(
+ if backend.startswith("hybrid-"):
+ ensure_backend_dependencies(backend)
+ backend = backend[7:]
+
+ if backend == "engine" and effort != "low":
+ backend = get_vlm_engine(inference_engine="auto", is_async=True)
+
+ os.environ["MINERU_VLM_TABLE_ENABLE"] = str(table_enable)
+ os.environ["MINERU_VLM_FORMULA_ENABLE"] = "true"
+
+ await _async_process_hybrid(
output_dir,
pdf_file_names,
pdf_bytes_list,
p_lang_list,
parse_method,
formula_enable,
- table_enable,
+ backend,
f_draw_layout_bbox,
f_draw_span_bbox,
f_dump_md,
@@ -835,47 +726,16 @@ async def aio_do_parse(
f_dump_orig_pdf,
f_dump_content_list,
f_make_md_mode,
- client_side_output_generation=client_side_output_generation,
+ 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:
- if backend.startswith("hybrid-"):
- ensure_backend_dependencies(backend)
- backend = backend[7:]
-
- if backend == "engine" and effort != "low":
- backend = get_vlm_engine(inference_engine="auto", is_async=True)
-
- os.environ["MINERU_VLM_TABLE_ENABLE"] = str(table_enable)
- os.environ["MINERU_VLM_FORMULA_ENABLE"] = "true"
-
- await _async_process_hybrid(
- output_dir,
- pdf_file_names,
- pdf_bytes_list,
- p_lang_list,
- parse_method,
- formula_enable,
- backend,
- f_draw_layout_bbox,
- f_draw_span_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}'")
+ raise ValueError(f"Unsupported backend '{backend}'")
if __name__ == "__main__":
@@ -890,7 +750,6 @@ if __name__ == "__main__":
["ch"],
end_page_id=10,
backend="hybrid-engine",
- # backend = 'pipeline'
)
except Exception as e:
logger.exception(e)
diff --git a/mineru/cli_old/fast_api.py b/mineru/cli_old/fast_api.py
index 5e997cc2..4d49d75c 100644
--- a/mineru/cli_old/fast_api.py
+++ b/mineru/cli_old/fast_api.py
@@ -33,7 +33,6 @@ from base64 import b64encode
from mineru.cli_old.common import (
aio_do_parse,
- do_parse,
image_suffixes,
office_suffixes,
pdf_suffixes,
@@ -859,10 +858,7 @@ async def run_parse_job(
**config,
)
- if request_options.backend == "pipeline":
- await asyncio.to_thread(do_parse, **parse_kwargs)
- else:
- await aio_do_parse(**parse_kwargs)
+ await aio_do_parse(**parse_kwargs)
return response_file_names
diff --git a/mineru/cli_old/gradio_app.py b/mineru/cli_old/gradio_app.py
index 7ece4517..e02ed2af 100644
--- a/mineru/cli_old/gradio_app.py
+++ b/mineru/cli_old/gradio_app.py
@@ -351,15 +351,13 @@ def select_backend_info_key(backend_choice):
backend_choice = normalize_backend(backend_choice)
except ValueError:
pass
- if backend_choice == "pipeline":
- return "backend_info_pipeline"
if backend_choice.startswith("hybrid"):
return "backend_info_hybrid"
return "backend_info_default"
def select_force_ocr_info_key(backend_choice: object) -> str:
- """根据解析后端选择强制 OCR 说明;只有 pipeline 需要提示 OCR 语言要求。"""
+ """根据解析后端选择强制 OCR 说明;当前公开解析后端统一走 Hybrid 文案。"""
if isinstance(backend_choice, str) and backend_choice.startswith("hybrid"):
return "force_ocr_info_hybrid"
return "force_ocr_info"
@@ -874,15 +872,15 @@ def is_effort_option_visible(backend):
def is_ocr_language_option_visible(backend: object) -> bool:
- """判断 OCR 语言选项是否展示;lang 参数只对 pipeline 后端生效。"""
- return backend == "pipeline"
+ """判断 OCR 语言选项是否展示;当前公开 Hybrid 后端不展示独立语言控件。"""
+ return False
def is_force_ocr_option_visible(backend: object) -> bool:
"""判断强制 OCR 开关是否展示;Hybrid 不需要 lang,但仍支持强制 OCR。"""
if not isinstance(backend, str):
return False
- return backend == "pipeline" or backend.startswith("hybrid")
+ return backend.startswith("hybrid")
def should_use_client_side_output_generation(client_side_output_generation):
@@ -1001,7 +999,7 @@ def maybe_generate_local_preview(extract_root, file_name, file_suffix, backend,
backend=backend,
parse_method=parse_method,
parse_dir=parse_dir,
- draw_span=backend.startswith("pipeline"),
+ draw_span=False,
)
result = run_visualization_job(visualization_job)
if result.status != "finished":
@@ -1020,7 +1018,7 @@ async def _run_to_markdown_job(
image_analysis=True,
effort=DEFAULT_HYBRID_EFFORT,
language="ch",
- backend="pipeline",
+ backend=DEFAULT_BACKEND,
url=None,
api_url=None,
client_side_output_generation=False,
@@ -1179,7 +1177,7 @@ async def stream_to_markdown(
image_analysis=True,
effort=DEFAULT_HYBRID_EFFORT,
language="ch",
- backend="pipeline",
+ backend=DEFAULT_BACKEND,
url=None,
api_url=None,
client_side_output_generation=False,
@@ -1591,7 +1589,6 @@ def main(ctx,
"max_pages": "Max convert pages",
"backend": "Backend",
"backend_label_hybrid": "Hybrid (Recommended)",
- "backend_label_pipeline": "Pipeline (Stable multilingual)",
"backend_label_vlm": "VLM (High-precision Chinese/English)",
"backend_label_remote_vlm": "Remote VLM",
"backend_label_remote_hybrid": "Remote Hybrid",
@@ -1606,10 +1603,8 @@ def main(ctx,
"effort": "Hybrid effort",
"effort_info": HYBRID_EFFORT_HELP,
"formula_label_vlm": "Enable display formula recognition",
- "formula_label_pipeline": "Enable formula recognition",
"formula_label_hybrid": "Enable inline formula recognition",
"formula_info_vlm": "If disabled, display formulas will be shown as images.",
- "formula_info_pipeline": "If disabled, display formulas will be shown as images, and inline formulas will not be detected or parsed.",
"formula_info_hybrid": "If disabled, inline formulas will not be detected or parsed.",
"ocr_language": "OCR Language",
"ocr_language_info": "Select the OCR language for image-based PDFs and images.",
@@ -1644,7 +1639,6 @@ def main(ctx,
"office_preview_ignore_once": "Dismiss",
"office_preview_ignore_forever": "Always dismiss",
"backend_info_vlm": "High-precision parsing via VLM, supports Chinese and English documents only.",
- "backend_info_pipeline": "Traditional Multi-model pipeline parsing, supports multiple languages, hallucination-free.",
"backend_info_hybrid": "High-precision hybrid parsing, supports multiple languages.",
"backend_info_default": "Select the backend engine for document parsing.",
},
@@ -1662,7 +1656,6 @@ def main(ctx,
"max_pages": "最大转换页数",
"backend": "解析后端",
"backend_label_hybrid": "Hybrid 推荐",
- "backend_label_pipeline": "Pipeline 稳定多语言",
"backend_label_vlm": "VLM 高精度中英文",
"backend_label_remote_vlm": "Remote VLM",
"backend_label_remote_hybrid": "Remote Hybrid",
@@ -1677,10 +1670,8 @@ def main(ctx,
"effort": "解析强度",
"effort_info": "Low 使用本地 Hybrid 处理;Medium 速度更快;High 精度更高,耗时可能更长。",
"formula_label_vlm": "启用行间公式识别",
- "formula_label_pipeline": "启用公式识别",
"formula_label_hybrid": "启用行内公式识别",
"formula_info_vlm": "禁用后,行间公式将显示为图片。",
- "formula_info_pipeline": "禁用后,行间公式将显示为图片,行内公式将不会被检测或解析。",
"formula_info_hybrid": "禁用后,行内公式将不会被检测或解析。",
"ocr_language": "OCR 语言",
"ocr_language_info": "为扫描版 PDF 和图片选择 OCR 语言。",
@@ -1715,7 +1706,6 @@ def main(ctx,
"office_preview_ignore_once": "忽略",
"office_preview_ignore_forever": "不再提示",
"backend_info_vlm": "多模态大模型高精度解析,仅支持中英文文档。",
- "backend_info_pipeline": "传统多模型管道解析,支持多语言,无幻觉。",
"backend_info_hybrid": "高精度混合解析,支持多语言。",
"backend_info_default": "选择文档解析的后端引擎。",
},
@@ -1727,21 +1717,17 @@ def main(ctx,
backend_choice = normalize_backend(backend_choice)
except ValueError:
pass
- if backend_choice == "pipeline":
- return i18n("formula_label_pipeline")
- elif backend_choice.startswith("hybrid"):
+ if backend_choice.startswith("hybrid"):
return i18n("formula_label_hybrid")
else:
- return i18n("formula_label_pipeline")
+ return i18n("formula_label_hybrid")
def get_formula_info(backend_choice):
try:
backend_choice = normalize_backend(backend_choice)
except ValueError:
pass
- if backend_choice == "pipeline":
- return i18n("formula_info_pipeline")
- elif backend_choice.startswith("hybrid"):
+ if backend_choice.startswith("hybrid"):
return i18n("formula_info_hybrid")
else:
return ""
@@ -1750,7 +1736,7 @@ def main(ctx,
return i18n(select_backend_info_key(backend_choice))
def get_force_ocr_info(backend_choice):
- """根据后端返回强制 OCR 控件说明,避免 Hybrid 显示 pipeline 的语言提示。"""
+ """根据后端返回强制 OCR 控件说明,当前公开解析后端统一使用 Hybrid 文案。"""
return i18n(select_force_ocr_info_key(backend_choice))
# 更新界面函数
@@ -1802,7 +1788,7 @@ def main(ctx,
image_analysis=True,
effort=DEFAULT_HYBRID_EFFORT,
language="ch",
- backend="pipeline",
+ backend=DEFAULT_BACKEND,
url=None,
request: gr.Request = None,
):
diff --git a/mineru/cli_old/output_paths.py b/mineru/cli_old/output_paths.py
index 5047f499..c73308ae 100644
--- a/mineru/cli_old/output_paths.py
+++ b/mineru/cli_old/output_paths.py
@@ -22,8 +22,6 @@ def build_parse_dir(
pass
if is_office:
return output_root / pdf_name / OFFICE_PARSE_DIR_NAME
- if backend.startswith("pipeline"):
- return output_root / pdf_name / parse_method
if backend.startswith("hybrid"):
return output_root / pdf_name / f"hybrid_{parse_method}"
raise ValueError(f"Unknown backend type: {backend}")
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 22738d7f..fdfbe289 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -1712,10 +1712,11 @@ def _iter_block_spans(block: Block) -> Iterator[Span]:
def _span_image_bytes(span: Span) -> tuple[bytes | None, str, str]:
- # TODO: how to get image from office span?
- if not span.image_base64:
+ # 兼容 typed Span 不再携带 image_base64 的场景,后续仍可走 image_path sidecar。
+ image_base64 = getattr(span, "image_base64", None)
+ if not image_base64:
return None, "png", "image/png"
- match = re.match(r"^data:image/(?P<ext>[^;]+);base64,(?P<data>.+)$", span.image_base64, re.DOTALL)
+ match = re.match(r"^data:image/(?P<ext>[^;]+);base64,(?P<data>.+)$", image_base64, re.DOTALL)
if match is None:
return None, "png", "image/png"
ext = match.group("ext").lower()
diff --git a/mineru/kit/commands/parse.py b/mineru/kit/commands/parse.py
index 2dafc28a..be5425b0 100644
--- a/mineru/kit/commands/parse.py
+++ b/mineru/kit/commands/parse.py
@@ -76,6 +76,8 @@ def parse_cmd(
except ValueError as exc:
exit_with_message("invalid_request", str(exc), "backend")
resolved_tier, resolved_backend = effective_local_tier_and_backend(tier, normalized_backend)
+ if resolved_tier == "standard":
+ normalized_effort = "low"
parse_one = partial(
local_parse,
tier=resolved_tier,
diff --git a/mineru/kit/common.py b/mineru/kit/common.py
index a142e233..7307b20f 100644
--- a/mineru/kit/common.py
+++ b/mineru/kit/common.py
@@ -123,7 +123,7 @@ def effective_local_tier_and_backend(tier: Tier | None, backend: str | None) ->
from ..parser.tier import backend_for_tier, resolve_tier_and_backend
if tier is None and backend is None:
- return "standard", "pipeline"
+ return "standard", backend_for_tier("standard")
resolved_tier, resolved_backend = resolve_tier_and_backend(tier=tier, backend=backend)
if tier is None and backend is None:
resolved_backend = backend_for_tier("standard")
diff --git a/mineru/model/table/cls/paddle_table_cls.py b/mineru/model/table/cls/paddle_table_cls.py
index 45489f5e..8e99291f 100644
--- a/mineru/model/table/cls/paddle_table_cls.py
+++ b/mineru/model/table/cls/paddle_table_cls.py
@@ -8,13 +8,14 @@ import onnxruntime
from loguru import logger
from tqdm import tqdm
-from mineru.backend.pipeline.model_list import AtomicModel
from mineru.utils.enum_class import ModelPath
from mineru.utils.models_download_utils import auto_download_and_get_model_root_path
class PaddleTableClsModel:
def __init__(self):
+ from mineru.backend.local_model_runtime import AtomicModel
+
self.sess = onnxruntime.InferenceSession(
os.path.join(auto_download_and_get_model_root_path(ModelPath.paddle_table_cls), ModelPath.paddle_table_cls)
)
diff --git a/mineru/parser/__init__.py b/mineru/parser/__init__.py
index f91afc5a..79fb6932 100644
--- a/mineru/parser/__init__.py
+++ b/mineru/parser/__init__.py
@@ -67,8 +67,10 @@ def _build_parser(
) -> DocumentParser:
path = Path(path)
suffix = _resolve_input_suffix(path)
- _, resolved_backend = resolve_tier_and_backend(tier=tier, backend=backend)
+ resolved_tier, resolved_backend = resolve_tier_and_backend(tier=tier, backend=backend)
resolved_backend, resolved_effort = resolve_backend_and_effort(backend or resolved_backend, effort)
+ if resolved_tier == "standard":
+ resolved_effort = "low"
resolved_ocr_mode = method or ocr_mode
resolved_language = lang or language
resolved_table_enable = (not disable_table) if table_enable is None else table_enable
@@ -88,15 +90,7 @@ def _build_parser(
if suffix not in _PDF_INPUT_SUFFIXES:
raise ValueError(f"Unsupported file type: {suffix or path.suffix or 'unknown'}")
- if resolved_backend == "pipeline":
- return PdfPipelineParser(
- backend=resolved_backend,
- method=resolved_ocr_mode,
- lang=resolved_language,
- formula_enable=resolved_formula_enable,
- table_enable=resolved_table_enable,
- )
- elif resolved_backend.startswith("hybrid-"):
+ if resolved_backend.startswith("hybrid-"):
return PdfHybridParser(
backend=resolved_backend,
method=resolved_ocr_mode,
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index d02d1f86..e7d1ab6b 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -1988,11 +1988,11 @@ def _model_ids_and_tiers_for_server_tier(tier: Tier) -> tuple[list[str], list[di
},
]
- return ["pipeline", "MinerU-HTML"], [
+ return ["Hybrid-Low", "MinerU-HTML"], [
{
"id": "standard",
- "description": "Pipeline-based parsing, balanced speed and quality.",
- "current_model": "pipeline",
+ "description": "Hybrid low parsing with local lightweight models.",
+ "current_model": "hybrid-low",
},
]
@@ -2027,12 +2027,11 @@ def create_app(
upload_dir:
Directory for uploaded files and parse artifacts.
tier:
- Server parsing tier. ``"standard"`` selects the pipeline backend;
- ``"pro"`` selects the Hybrid backend. If ``backend`` is also provided,
+ Server parsing tier. ``"standard"`` selects Hybrid low;
+ ``"pro"`` selects the default Hybrid backend. If ``backend`` is also provided,
both values must be compatible.
backend:
- Advanced server backend mode. ``"pipeline"`` exposes the traditional
- CV+OCR pipeline; ``"hybrid-engine"`` exposes Hybrid parsing.
+ Advanced server backend mode. ``"hybrid-engine"`` exposes local Hybrid parsing.
concurrency:
Maximum concurrent parse jobs (default 1).
url_timeout:
@@ -2045,7 +2044,7 @@ def create_app(
language:
Parser language hint.
ocr_mode:
- PDF OCR/text extraction mode for pipeline and hybrid backends.
+ PDF OCR/text extraction mode for Hybrid backends.
effort:
Hybrid backend effort level. Low uses local Hybrid processing. Medium is
faster. High is more accurate and may take longer.
@@ -2060,6 +2059,8 @@ def create_app(
raw_backend = backend
tier, backend = _resolve_server_tier_and_backend(tier=tier, backend=backend)
backend, effort = resolve_backend_and_effort(raw_backend or backend, effort)
+ if tier == "standard":
+ effort = "low"
dependency_tier = "standard" if backend.startswith("hybrid-") and effort == "low" else tier
_preflight_tier_dependencies(dependency_tier)
_api_key: str | None = api_key or None
@@ -2167,7 +2168,7 @@ def create_app(
help=(
"Advanced parser backend "
f"({', '.join(_API_SERVER_BACKENDS)}). "
- "Defaults from --tier: standard -> pipeline, pro -> hybrid-engine."
+ "Defaults from --tier: standard -> hybrid-engine --effort low, pro -> hybrid-engine."
),
)
@click.option(
@@ -2205,7 +2206,7 @@ def create_app(
"--ocr-mode",
default="auto",
type=click.Choice(_OCR_MODES),
- help="PDF OCR/text extraction mode. Applies to pipeline and hybrid-* backends.",
+ help="PDF OCR/text extraction mode. Applies to hybrid-* backends.",
)
@click.option(
"--effort",
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index a66a2faf..763100a0 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -16,7 +16,7 @@ from ..utils.pdf_document import PDFDocument
_PDF_RETAINED_PAGE_INDICES_KEY = "_pdf_retained_page_indices"
_PDF_BROKEN_PAGE_INDICES_KEY = "_pdf_broken_page_indices"
-_SUPPORTED_MIDDLE_JSON_BACKENDS = {"pipeline", "hybrid", "office"}
+_SUPPORTED_MIDDLE_JSON_BACKENDS = {"hybrid", "office"}
def _parse_optional_int_list(value: Any) -> list[int] | None:
diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.py
index 1c21ffeb..eb5f57a1 100644
--- a/mineru/parser/pdf.py
+++ b/mineru/parser/pdf.py
@@ -10,7 +10,7 @@ from typing import Any
from ..errors import InvalidRequestError
from ..types import PageInfo
-from ..utils.backend_options import resolve_backend_and_effort, validate_effort
+from ..utils.backend_options import CANONICAL_HYBRID_ENGINE, resolve_backend_and_effort, validate_effort
from ..utils.image_payload import ImagePayloadCache
from .base import DocumentParser, ParseResult
@@ -225,105 +225,8 @@ class PdfBaseParser(DocumentParser):
)
-class PdfPipelineParser(PdfBaseParser):
- """PDF / image parser using the pipeline (CV+OCR) backend."""
-
- _parse_method: str = ""
- _backend = "pipeline"
-
- def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:
- self._parse_method = self.method
- return super().parse(path, page_range=page_range)
-
- async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
- self._parse_method = self.method
- return await super().parse_async(path, page_range=page_range)
-
- def parse_batch(self, paths: list[str | Path], *, page_range: str = "") -> list[ParseResult]:
- self._parse_method = self.method
-
- from ..backend.pipeline.pipeline_analyze import doc_analyze_streaming
-
- prepared_inputs: list[_PreparedPdfInput] = []
- pdf_bytes_list: list[bytes] = []
- image_caches: list[ImagePayloadCache] = []
- for p in paths:
- prepared = self._prepare_input(Path(p), page_range)
- prepared_inputs.append(prepared)
- pdf_bytes_list.append(prepared.pdf_bytes)
- image_caches.append(ImagePayloadCache())
-
- results_by_index: dict[int, list[PageInfo]] = {}
-
- def on_doc_ready(doc_index: int, model_list: Any, middle_json: list[PageInfo], _ocr_enable: bool) -> None:
- results_by_index[doc_index] = middle_json
-
- doc_analyze_streaming(
- pdf_bytes_list,
- [self.lang] * len(paths),
- on_doc_ready,
- parse_method=self.method,
- formula_enable=self.formula_enable,
- table_enable=self.table_enable,
- page_index_map_list=[prepared.retained_page_indices for prepared in prepared_inputs],
- image_cache_list=image_caches,
- )
-
- parse_results: list[ParseResult] = []
- for idx in range(len(paths)):
- middle_json = results_by_index[idx]
- prepared = prepared_inputs[idx]
- self._insert_broken_pages(
- middle_json,
- prepared.retained_page_indices,
- prepared.broken_page_indices,
- )
- result = self._build_result(
- middle_json,
- prepared.pdf_bytes,
- prepared.file_name,
- retained_page_indices=prepared.retained_page_indices,
- broken_page_indices=prepared.broken_page_indices,
- image_cache=image_caches[idx],
- )
- parse_results.append(result)
-
- return parse_results
-
- async def parse_batch_async(self, paths: list[str | Path], *, page_range: str = "") -> list[ParseResult]:
- import asyncio
-
- return await asyncio.to_thread(self.parse_batch, paths, page_range=page_range)
-
- def _run_analysis(
- self,
- pdf_bytes: bytes,
- page_index_map: list[int] | None = None,
- image_cache: ImagePayloadCache | None = None,
- ) -> list[PageInfo]:
- from ..backend.pipeline.pipeline_analyze import doc_analyze_streaming
-
- result_holder: dict = {}
-
- def on_doc_ready(_doc_index, model_list, middle_json, _ocr_enable):
- result_holder["middle_json"] = middle_json
-
- doc_analyze_streaming(
- [pdf_bytes],
- [self.lang],
- on_doc_ready,
- parse_method=self.method,
- formula_enable=self.formula_enable,
- table_enable=self.table_enable,
- page_index_map_list=[page_index_map],
- image_cache_list=[image_cache or ImagePayloadCache()],
- )
-
- return result_holder["middle_json"]
-
-
class PdfHybridParser(PdfBaseParser):
- """PDF / image parser using the hybrid (pipeline + VLM) backend."""
+ """PDF / image parser using the Hybrid local/VLM backend."""
_parse_method: str = ""
_backend = "hybrid"
@@ -393,6 +296,16 @@ class PdfHybridParser(PdfBaseParser):
return middle_json
+class PdfPipelineParser(PdfHybridParser):
+ """保留旧 SDK 类名,内部统一委托 Hybrid low 解析。"""
+
+ def __init__(self, **kwargs: Any) -> None:
+ """将旧 PdfPipelineParser 构造参数归一到 Hybrid low,避免继续加载旧 backend。"""
+ kwargs.pop("backend", None)
+ kwargs.pop("effort", None)
+ super().__init__(backend=CANONICAL_HYBRID_ENGINE, effort="low", **kwargs)
+
+
class PdfVlmParser(PdfHybridParser):
"""保留旧 SDK 类名,内部统一委托 Hybrid high 解析。"""
diff --git a/mineru/parser/tier.py b/mineru/parser/tier.py
index cbe71d51..de6560f2 100644
--- a/mineru/parser/tier.py
+++ b/mineru/parser/tier.py
@@ -6,7 +6,13 @@ import sys
from importlib import metadata as importlib_metadata
from ..types import Tier
-from ..utils.backend_options import SUPPORTED_BACKENDS, is_hybrid_backend, normalize_backend
+from ..utils.backend_options import (
+ CANONICAL_HYBRID_ENGINE,
+ LEGACY_PIPELINE_BACKEND_ALIASES,
+ SUPPORTED_BACKENDS,
+ is_hybrid_backend,
+ normalize_backend,
+)
__all__ = [
"PARSER_BACKENDS",
@@ -58,31 +64,33 @@ def backend_for_tier(tier: Tier) -> str:
"""Return the local parser backend used for a parser-layer tier fallback."""
mapping = {
"flash": "flash",
- "standard": "pipeline",
- "pro": "hybrid-engine",
+ "standard": CANONICAL_HYBRID_ENGINE,
+ "pro": CANONICAL_HYBRID_ENGINE,
}
- return mapping.get(tier, "pipeline")
+ return mapping.get(tier, CANONICAL_HYBRID_ENGINE)
def tier_for_backend(backend: str) -> Tier:
+ raw_backend = (backend or "").strip()
+ if raw_backend in LEGACY_PIPELINE_BACKEND_ALIASES:
+ return "standard"
normalized_backend = normalize_backend(backend)
if normalized_backend == "flash":
return "flash"
- if normalized_backend == "pipeline":
- return "standard"
if is_hybrid_backend(normalized_backend):
return "pro"
raise ValueError(f"Unsupported backend '{backend}'. Supported backends: {', '.join(PARSER_BACKENDS)}")
def _backend_supports_tier(backend: str, tier: Tier) -> bool:
+ raw_backend = (backend or "").strip()
normalized_backend = normalize_backend(backend)
if tier == "flash":
return normalized_backend == "flash"
if tier == "standard":
- return normalized_backend == "pipeline"
+ return raw_backend in LEGACY_PIPELINE_BACKEND_ALIASES or normalized_backend == CANONICAL_HYBRID_ENGINE
if tier == "pro":
- return is_hybrid_backend(normalized_backend)
+ return is_hybrid_backend(normalized_backend) and raw_backend not in LEGACY_PIPELINE_BACKEND_ALIASES
return False
@@ -92,10 +100,10 @@ def resolve_tier_and_backend(tier: Tier | None = None, backend: str | None = Non
if backend:
normalized_backend = normalize_backend(backend)
if tier is None:
- return tier_for_backend(normalized_backend), normalized_backend
- if not _backend_supports_tier(normalized_backend, resolved_tier):
+ return tier_for_backend(backend), normalized_backend
+ if not _backend_supports_tier(backend, resolved_tier):
raise ValueError(f"tier '{resolved_tier}' is incompatible with backend '{backend}'")
- return tier_for_backend(normalized_backend), normalized_backend
+ return resolved_tier, normalized_backend
return resolved_tier, backend_for_tier(resolved_tier)
diff --git a/mineru/render/merge_visual.py b/mineru/render/merge_visual.py
index 954eb398..3af064f4 100644
--- a/mineru/render/merge_visual.py
+++ b/mineru/render/merge_visual.py
@@ -44,7 +44,7 @@ def _blocks_in_index_order(blocks: list[Block]) -> list[Block]:
def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> Block:
- # pipeline_magic_model 会把 code_body 的 sub_type/guess_lang 提升到父 code block。
+ # 本地 Hybrid 模型会把 code_body 的 sub_type/guess_lang 提升到父 code block。
# markdown 渲染 code_body 时需要把这两个字段临时透传回来,但不能修改原始输入。
if block.type != BlockType.CODE_BODY:
return block
diff --git a/mineru/render/union_make.py b/mineru/render/union_make.py
index cb64c5b6..2f1e24f8 100644
--- a/mineru/render/union_make.py
+++ b/mineru/render/union_make.py
@@ -8,7 +8,7 @@ from .markdown import blocks_to_markdown
from .office.output import blocks_to_markdown as office_blocks_to_markdown
from .structured_content import block_to_structured_content, merge_adjacent_ref_text_blocks_for_content
-Backend = Literal["pipeline", "hybrid", "office"]
+Backend = Literal["hybrid", "office"]
def _backend_from_pages(pages: list[PageInfo]) -> Backend | None:
diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.js
index e5189374..e9cbd739 100644
--- a/mineru/resources/gradio_app.js
+++ b/mineru/resources/gradio_app.js
@@ -134,8 +134,8 @@
const showClientOptions = backend.endsWith("http-client");
const showImageAnalysis = backend.startsWith("vlm")
|| (backend.startsWith("hybrid") && effort === "high");
- const showOcrLanguage = backend === "pipeline";
- const hideForceOcr = backend !== "pipeline" && !backend.startsWith("hybrid");
+ const showOcrLanguage = false;
+ const hideForceOcr = !backend.startsWith("hybrid");
const hideHybridEffort = !backend.startsWith("hybrid");
document.body.classList.toggle(CLIENT_OPTIONS_VISIBLE_CLASS, showClientOptions);
diff --git a/mineru/types.py b/mineru/types.py
index 2bee5824..9268a4f3 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -560,7 +560,7 @@ class PageInfo(_DocElement):
discarded_blocks: list[Block] = field(default_factory=list)
# Temporary — will be removed once the render layer converges.
- _backend: Literal["pipeline", "hybrid", "office"] | None = None
+ _backend: Literal["hybrid", "office"] | None = None
@dataclass
diff --git a/mineru/utils/backend_options.py b/mineru/utils/backend_options.py
index d8247705..294d75d4 100644
--- a/mineru/utils/backend_options.py
+++ b/mineru/utils/backend_options.py
@@ -10,7 +10,6 @@ DEFAULT_EFFORT: Final = DEFAULT_HYBRID_EFFORT
HYBRID_EFFORT_HELP: Final = "Low uses local Hybrid processing. Medium is faster. High is more accurate and may take longer."
LOCAL_BACKEND_CHOICES: Final[tuple[str, ...]] = (
- "pipeline",
CANONICAL_HYBRID_ENGINE,
)
HTTP_CLIENT_BACKEND_CHOICES: Final[tuple[str, ...]] = (
@@ -23,10 +22,12 @@ HYBRID_EFFORT_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(HYBRID_E
BACKEND_ALIASES: Final[dict[str, str]] = {
"hybrid-auto-engine": CANONICAL_HYBRID_ENGINE,
+ "pipeline": CANONICAL_HYBRID_ENGINE,
"vlm-engine": CANONICAL_HYBRID_ENGINE,
"vlm-auto-engine": CANONICAL_HYBRID_ENGINE,
"vlm-http-client": "hybrid-http-client",
}
+LEGACY_PIPELINE_BACKEND_ALIASES: Final[frozenset[str]] = frozenset({"pipeline"})
LEGACY_VLM_BACKEND_ALIASES: Final[frozenset[str]] = frozenset(
{
"vlm-engine",
@@ -69,11 +70,13 @@ def validate_effort(effort: str | None) -> str:
def resolve_backend_and_effort(backend: str | None, effort: str | None = None) -> tuple[str, str]:
- """同时解析 backend 与 effort,旧 VLM backend 统一转为 Hybrid high。"""
+ """同时解析 backend 与 effort,旧 pipeline/VLM backend 分别统一转为 Hybrid low/high。"""
raw_backend = (backend or "").strip()
resolved_backend = normalize_backend(raw_backend)
resolved_effort = validate_effort(effort)
- if raw_backend in LEGACY_VLM_BACKEND_ALIASES:
+ if raw_backend in LEGACY_PIPELINE_BACKEND_ALIASES:
+ resolved_effort = "low"
+ elif raw_backend in LEGACY_VLM_BACKEND_ALIASES:
resolved_effort = "high"
return resolved_backend, resolved_effort
diff --git a/mineru/utils/ocr_language.py b/mineru/utils/ocr_language.py
index 5fcb5e7b..adcadc25 100644
--- a/mineru/utils/ocr_language.py
+++ b/mineru/utils/ocr_language.py
@@ -107,7 +107,7 @@ def format_public_ocr_lang_description() -> str:
for lang in PUBLIC_OCR_LANGUAGES
]
return (
- "(Adapted for pipeline backend only) Input the languages in the pdf "
+ "(Adapted for local Hybrid OCR) Input the languages in the pdf "
"to improve OCR accuracy. Options:\n"
+ "\n".join(option_lines)
)
diff --git a/mineru/utils/title_level_postprocess.py b/mineru/utils/title_level_postprocess.py
index f1816370..8a8ab108 100644
--- a/mineru/utils/title_level_postprocess.py
+++ b/mineru/utils/title_level_postprocess.py
@@ -40,11 +40,9 @@ def apply_title_leveling_to_pdf_info(pdf_info: list[PageInfo]) -> None:
def finalize_client_side_pages(pages: list[PageInfo], backend: str, effort: str = DEFAULT_HYBRID_EFFORT) -> None:
"""按调用方传入的后端类型,对 pages 原地执行客户端可完成的 finalize。"""
- if backend == "pipeline":
- from mineru.backend.pipeline.model_output_to_middle_json import finalize_middle_json_from_preproc
-
- finalize_middle_json_from_preproc(pages)
- elif backend == "hybrid":
+ if backend == "hybrid":
from mineru.backend.hybrid.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}'")
diff --git a/tests/unittest/test_backend_block_object_regressions.py b/tests/unittest/test_backend_block_object_regressions.py
index 382205fa..57644504 100644
--- a/tests/unittest/test_backend_block_object_regressions.py
+++ b/tests/unittest/test_backend_block_object_regressions.py
@@ -5,10 +5,6 @@ from types import SimpleNamespace
from PIL import Image
from mineru.backend.hybrid.model_output_to_middle_json import blocks_to_page_info as hybrid_blocks_to_page_info
-from mineru.backend.pipeline.model_output_to_middle_json import (
- blocks_to_page_info as pipeline_blocks_to_page_info,
- finalize_middle_json_from_preproc as finalize_pipeline_middle_json_from_preproc,
-)
from mineru.types import BlockType
@@ -20,40 +16,6 @@ def _image_dict(width: int = 200, height: int = 200) -> dict[str, object]:
return {"scale": 1.0, "img_pil": Image.new("RGB", (width, height), "white")}
-def test_pipeline_block_objects_survive_visual_grouping_and_finalize() -> None:
- page_info = pipeline_blocks_to_page_info(
- {
- "layout_dets": [
- {
- "label": "figure_title",
- "bbox": [10, 10, 120, 25],
- "index": 1,
- "score": 0.99,
- "text": "Figure 1",
- },
- {
- "label": "image",
- "bbox": [10, 30, 120, 90],
- "index": 2,
- "score": 0.99,
- },
- ]
- },
- _image_dict(),
- _fake_pdf_page(),
- 0,
- ocr_enable=True,
- )
-
- finalize_pipeline_middle_json_from_preproc([page_info])
-
- assert len(page_info.preproc_blocks) == 1
- visual_block = page_info.preproc_blocks[0]
- assert visual_block.type == BlockType.IMAGE
- assert {block.type for block in visual_block.blocks} == {BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION}
- assert page_info.para_blocks[0].type == BlockType.IMAGE
-
-
def test_hybrid_block_objects_sort_and_group_without_dict_access() -> None:
page_info = hybrid_blocks_to_page_info(
[
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index b5c52fd6..e09b75c0 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -279,10 +279,10 @@ def test_load_pages_from_done_batches_keeps_newest_page_idx(tmp_path: Path) -> N
def test_parser_tier_backend_mapping_is_parser_layer_only() -> None:
assert backend_for_tier("flash") == "flash"
- assert backend_for_tier("standard") == "pipeline"
+ assert backend_for_tier("standard") == "hybrid-engine"
assert backend_for_tier("pro") == "hybrid-engine"
assert resolve_tier_and_backend(tier=None) == ("pro", "hybrid-engine")
- assert resolve_tier_and_backend(tier="pro", backend="vlm-auto-engine") == ("pro", "vlm-engine")
+ assert resolve_tier_and_backend(tier="pro", backend="vlm-auto-engine") == ("pro", "hybrid-engine")
def test_managed_api_server_args_use_tier_and_selected_port_for_process_start() -> None:
diff --git a/tests/unittest/test_doclib_progressive_reading.py b/tests/unittest/test_doclib_progressive_reading.py
index 6456473f..8169f6f0 100644
--- a/tests/unittest/test_doclib_progressive_reading.py
+++ b/tests/unittest/test_doclib_progressive_reading.py
@@ -16,7 +16,7 @@ def _page(page_idx: int, *texts: str) -> PageInfo:
)
for index, text in enumerate(texts)
]
- return PageInfo(page_idx=page_idx, page_size=(100, 100), para_blocks=blocks, _backend="pipeline")
+ return PageInfo(page_idx=page_idx, page_size=(100, 100), para_blocks=blocks, _backend="hybrid")
def test_paginated_default_content_pages_are_first_ten() -> None:
@@ -221,7 +221,7 @@ def test_page_markdown_blocks_prefers_markdown_table_in_doclib() -> None:
],
)
],
- _backend="pipeline",
+ _backend="hybrid",
)
assert _page_markdown_blocks(page) == [
diff --git a/tests/unittest/test_e2e.py b/tests/unittest/test_e2e.py
index b109236f..63d26abf 100644
--- a/tests/unittest/test_e2e.py
+++ b/tests/unittest/test_e2e.py
@@ -1,97 +1,16 @@
# Copyright (c) Opendatalab. All rights reserved.
import json
import os
-from pathlib import Path
from bs4 import BeautifulSoup
from fuzzywuzzy import fuzz
from loguru import logger
-from mineru.backend.pipeline.pipeline_analyze import doc_analyze_streaming as pipeline_doc_analyze_streaming
-from mineru.cli_old.common import convert_pdf_bytes_to_bytes, prepare_env, read_fn
from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.parser.base import ParseResult
from mineru.render import render_content_list, render_markdown
-def test_pipeline_with_two_config():
- __dir__ = os.path.dirname(os.path.abspath(__file__))
- pdf_files_dir = os.path.join(__dir__, "pdfs")
- output_dir = os.path.join(__dir__, "output")
- pdf_suffixes = [".pdf"]
- image_suffixes = [".png", ".jpeg", ".jpg"]
-
- doc_path_list = []
- for doc_path in Path(pdf_files_dir).glob("*"):
- if doc_path.suffix in pdf_suffixes + image_suffixes:
- doc_path_list.append(doc_path)
-
- # os.environ["MINERU_MODEL_SOURCE"] = "modelscope"
-
- pdf_file_names = []
- pdf_bytes_list = []
- p_lang_list = []
- for path in doc_path_list:
- file_name = str(Path(path).stem)
- pdf_bytes = read_fn(path)
- pdf_file_names.append(file_name)
- pdf_bytes_list.append(pdf_bytes)
- p_lang_list.append("en")
- for idx, pdf_bytes in enumerate(pdf_bytes_list):
- new_pdf_bytes = convert_pdf_bytes_to_bytes(pdf_bytes)
- pdf_bytes_list[idx] = new_pdf_bytes
-
- run_pipeline_parse(
- pdf_file_names,
- pdf_bytes_list,
- p_lang_list,
- output_dir,
- parse_method="txt",
- )
- res_json_path = (Path(__file__).parent / "output" / "test" / "txt" / "test_content_list.json").as_posix()
- assert_content(res_json_path, parse_method="txt")
- run_pipeline_parse(
- pdf_file_names,
- pdf_bytes_list,
- p_lang_list,
- output_dir,
- parse_method="ocr",
- )
- res_json_path = (Path(__file__).parent / "output" / "test" / "ocr" / "test_content_list.json").as_posix()
- assert_content(res_json_path, parse_method="ocr")
-
-
-def run_pipeline_parse(
- pdf_file_names,
- pdf_bytes_list,
- p_lang_list,
- output_dir,
- parse_method,
-):
- output_info = []
- for pdf_file_name in pdf_file_names:
- local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
- output_info.append((pdf_file_name, local_image_dir, local_md_dir))
-
- def on_doc_ready(doc_index, model_list, middle_json, ocr_enable):
- del ocr_enable
- pdf_file_name, local_image_dir, local_md_dir = output_info[doc_index]
- write_infer_result(
- pdf_file_name,
- local_image_dir,
- local_md_dir,
- middle_json,
- model_list,
- )
-
- pipeline_doc_analyze_streaming(
- pdf_bytes_list,
- p_lang_list,
- on_doc_ready,
- parse_method=parse_method,
- )
-
-
def write_infer_result(
pdf_file_name,
local_image_dir,
diff --git a/tests/unittest/test_middle_json_validator.py b/tests/unittest/test_middle_json_validator.py
index b7884011..3590ecc9 100644
--- a/tests/unittest/test_middle_json_validator.py
+++ b/tests/unittest/test_middle_json_validator.py
@@ -159,7 +159,7 @@ def test_validate_pages_reports_span_content_contracts() -> None:
def test_validate_pages_warns_legacy_page_backend() -> None:
page = _valid_page()
- page._backend = "pipeline"
+ page._backend = "hybrid"
issues = validate_pages([page])
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index cab5511e..d7229dee 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -37,7 +37,7 @@ def _table_page_with_cached_inline_image(img_bytes: bytes) -> tuple[PageInfo, Im
],
)
],
- _backend="pipeline",
+ _backend="hybrid",
)
return page, image_cache, inline_image
@@ -103,7 +103,7 @@ def test_parse_result_from_dict_accepts_pages_and_preserves_page_backend() -> No
{
"page_idx": 0,
"page_size": [100, 200],
- "_backend": "pipeline",
+ "_backend": "hybrid",
"preproc_blocks": [
{
"index": 0,
@@ -130,7 +130,7 @@ def test_parse_result_from_dict_accepts_pages_and_preserves_page_backend() -> No
)
assert len(restored.pages) == 1
- assert restored.pages[0]._backend == "pipeline"
+ assert restored.pages[0]._backend == "hybrid"
assert restored.pages[0].page_size == (100, 200)
assert restored.pages[0].preproc_blocks[0].level == 1
@@ -157,13 +157,13 @@ def test_parse_result_from_dict_keeps_page_backend_over_root_backend() -> None:
"pages": [
{
"page_idx": 0,
- "_backend": "pipeline",
+ "_backend": "hybrid",
}
],
}
)
- assert restored.pages[0]._backend == "pipeline"
+ assert restored.pages[0]._backend == "hybrid"
def test_parse_result_from_dict_rejects_legacy_vlm_backend() -> None:
@@ -171,6 +171,12 @@ def test_parse_result_from_dict_rejects_legacy_vlm_backend() -> None:
ParseResult.from_dict({"_backend": "vlm", "pages": [{"page_idx": 0}]})
+def test_parse_result_from_dict_rejects_legacy_pipeline_backend() -> None:
+ legacy_backend = "pipeline"
+ with pytest.raises(ValueError, match="Unsupported middle json backend 'pipeline'"):
+ ParseResult.from_dict({"_backend": legacy_backend, "pages": [{"page_idx": 0}]})
+
+
def test_parse_result_preserves_true_merge_prev_in_staged_middle_json() -> None:
block = Block(index=0, type="text", bbox=(0.0, 0.0, 10.0, 10.0), merge_prev=True)
result = ParseResult(pages=[PageInfo(page_idx=0, preproc_blocks=[block])])
@@ -257,7 +263,7 @@ def test_parse_result_structured_content_method_and_save_name() -> None:
],
)
],
- _backend="pipeline",
+ _backend="hybrid",
)
result = ParseResult(pages=[page])
writes: dict[str, str] = {}
@@ -302,7 +308,7 @@ def test_parse_result_render_methods_use_export_pages_without_mutating_source(
],
)
],
- _backend="pipeline",
+ _backend="hybrid",
)
result = ParseResult(pages=[page], _image_cache=image_cache)
captured: list[list[PageInfo]] = []
@@ -367,7 +373,7 @@ def test_parse_result_save_writes_cached_images_and_exports_clean_middle_json()
],
)
],
- _backend="pipeline",
+ _backend="hybrid",
)
result = ParseResult(pages=[page], _image_cache=image_cache)
writes: dict[str, bytes | str] = {}
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 2c83ed7b..81432a05 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -79,13 +79,14 @@ print("ok")
assert result.stdout.strip() == "ok"
-def test_validate_effort_accepts_low_and_keeps_legacy_vlm_high() -> None:
- """校验 low 成为公开 Hybrid effort,旧 VLM backend 仍强制 high。"""
+def test_validate_effort_accepts_low_and_maps_legacy_backends() -> None:
+ """校验 legacy backend 输入统一映射到当前 Hybrid effort 合约。"""
from mineru.utils.backend_options import HYBRID_EFFORT_CHOICES, resolve_backend_and_effort, validate_effort
assert validate_effort("low") == "low"
assert "low" in HYBRID_EFFORT_CHOICES
assert resolve_backend_and_effort("vlm-engine", "low") == ("hybrid-engine", "high")
+ assert resolve_backend_and_effort("pipeline", "high") == ("hybrid-engine", "low")
def test_api_client_builds_file_page_range_without_options(tmp_path: Path) -> None:
@@ -148,7 +149,7 @@ def test_api_client_downloads_image_sidecars_and_preserves_pdf_mapping(monkeypat
def test_api_client_accepts_remote_pdf_info_json(monkeypatch: pytest.MonkeyPatch) -> None:
parser = MinerUApiParser(api_url="https://staging.mineru.org.cn/api", tier="standard")
middle_json = {
- "_backend": "pipeline",
+ "_backend": "hybrid",
"_version_name": "remote",
"pdf_info": [{"page_idx": 0, "page_size": [100, 200]}],
}
@@ -169,13 +170,13 @@ def test_api_client_accepts_remote_pdf_info_json(monkeypatch: pytest.MonkeyPatch
assert len(result.pages) == 1
assert result.pages[0].page_idx == 0
assert result.pages[0].page_size == (100, 200)
- assert result.pages[0]._backend == "pipeline"
+ assert result.pages[0]._backend == "hybrid"
def test_async_api_client_accepts_remote_pdf_info_json(monkeypatch: pytest.MonkeyPatch) -> None:
parser = MinerUApiParser(api_url="https://staging.mineru.org.cn/api", tier="standard")
middle_json = {
- "_backend": "pipeline",
+ "_backend": "hybrid",
"pdf_info": [{"page_idx": 0, "page_size": [100, 200]}],
}
@@ -203,7 +204,7 @@ def test_async_api_client_accepts_remote_pdf_info_json(monkeypatch: pytest.Monke
assert len(result.pages) == 1
assert result.pages[0].page_idx == 0
assert result.pages[0].page_size == (100, 200)
- assert result.pages[0]._backend == "pipeline"
+ assert result.pages[0]._backend == "hybrid"
@pytest.mark.parametrize("image_path", ["../escape.png", "/tmp/escape.png", "\\escape.png", "C:\\escape.png"])
@@ -491,13 +492,13 @@ def test_create_app_does_not_read_runtime_settings_from_env(tmp_path: Path, monk
app = create_app(upload_dir=str(tmp_path))
assert app.state.tier == "standard"
- assert app.state.backend == "pipeline"
+ assert app.state.backend == "hybrid-engine"
assert app.state.concurrency == 1
assert app.state.url_timeout == 60
assert app.state.max_wait == 600
assert app.state.language == "ch"
assert app.state.ocr_mode == "auto"
- assert app.state.effort == "medium"
+ assert app.state.effort == "low"
assert app.state.table_enable is True
assert app.state.formula_enable is True
assert app.state.image_analysis is True
@@ -582,7 +583,7 @@ def test_api_server_rendered_outputs_store_image_sidecars(
page_idx=0,
page_size=(100, 100),
para_blocks=[block],
- _backend="pipeline",
+ _backend="hybrid",
)
],
_image_cache=image_cache,
@@ -610,12 +611,13 @@ def test_api_server_rendered_outputs_store_image_sidecars(
rec,
request,
file_store,
- server_backend="pipeline",
+ server_backend="hybrid-engine",
language="ch",
ocr_mode="auto",
table_enable=True,
formula_enable=True,
image_analysis=True,
+ effort="low",
)
)
@@ -647,7 +649,7 @@ def test_api_server_middle_json_preserves_backend_for_client_rendering(
page_idx=0,
page_size=(100, 100),
para_blocks=[block],
- _backend="pipeline",
+ _backend="hybrid",
)
]
)
@@ -674,12 +676,13 @@ def test_api_server_middle_json_preserves_backend_for_client_rendering(
rec,
request,
file_store,
- server_backend="pipeline",
+ server_backend="hybrid-engine",
language="ch",
ocr_mode="auto",
table_enable=True,
formula_enable=True,
image_analysis=True,
+ effort="low",
)
)
@@ -687,7 +690,7 @@ def test_api_server_middle_json_preserves_backend_for_client_rendering(
payload = json.loads(file_store.read_file_data(output_ref.file_id).decode("utf-8"))
roundtrip = ParseResult.from_dict(payload)
- assert payload["_backend"] == "pipeline"
+ assert payload["_backend"] == "hybrid"
assert roundtrip.content_list()
assert roundtrip.structured_content()
@@ -713,7 +716,7 @@ def test_api_server_sanitizes_surrogates_in_text_outputs(
page_idx=0,
page_size=(100, 100),
para_blocks=[block],
- _backend="pipeline",
+ _backend="hybrid",
)
]
)
@@ -740,12 +743,13 @@ def test_api_server_sanitizes_surrogates_in_text_outputs(
rec,
request,
file_store,
- server_backend="pipeline",
+ server_backend="hybrid-engine",
language="ch",
ocr_mode="auto",
table_enable=True,
formula_enable=True,
image_analysis=True,
+ effort="low",
)
)
@@ -794,12 +798,13 @@ def test_api_server_logs_traceback_when_job_file_fails(
rec,
request,
file_store,
- server_backend="pipeline",
+ server_backend="hybrid-engine",
language="ch",
ocr_mode="auto",
table_enable=True,
formula_enable=True,
image_analysis=True,
+ effort="low",
)
)
@@ -854,7 +859,8 @@ def test_api_server_tier_selects_compatible_backend(tmp_path: Path, monkeypatch:
assert pro_app.state.backend == "hybrid-engine"
assert [tier["id"] for tier in pro_app.state.tiers] == ["pro"]
assert standard_app.state.tier == "standard"
- assert standard_app.state.backend == "pipeline"
+ assert standard_app.state.backend == "hybrid-engine"
+ assert standard_app.state.effort == "low"
assert [tier["id"] for tier in standard_app.state.tiers] == ["standard"]
@@ -863,7 +869,8 @@ def test_api_server_defaults_to_standard_tier(tmp_path: Path, monkeypatch: pytes
app = create_app(upload_dir=str(tmp_path))
assert app.state.tier == "standard"
- assert app.state.backend == "pipeline"
+ assert app.state.backend == "hybrid-engine"
+ assert app.state.effort == "low"
assert [tier["id"] for tier in app.state.tiers] == ["standard"]
@@ -947,9 +954,15 @@ def test_api_server_cli_reports_dependency_preflight_without_traceback(monkeypat
assert "Traceback" not in result.output
-def test_api_server_rejects_incompatible_tier_and_backend(tmp_path: Path) -> None:
- with pytest.raises(ValueError, match="incompatible"):
- create_app(upload_dir=str(tmp_path), tier="pro", backend="pipeline")
+def test_api_server_maps_legacy_pipeline_backend_to_standard_hybrid_low(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _stub_api_server_dependency_preflight(monkeypatch)
+ app = create_app(upload_dir=str(tmp_path), backend="pipeline")
+
+ assert app.state.tier == "standard"
+ assert app.state.backend == "hybrid-engine"
+ assert app.state.effort == "low"
def test_api_server_allows_compatible_tier_and_explicit_backend(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -997,6 +1010,27 @@ def test_build_parser_maps_legacy_vlm_backend_to_hybrid_high(tmp_path: Path) ->
assert parser.effort == "high"
+def test_build_parser_maps_legacy_pipeline_backend_to_hybrid_low(tmp_path: Path) -> None:
+ pdf = tmp_path / "demo.pdf"
+ pdf.write_bytes(b"%PDF-1.7\n")
+
+ parser = _build_parser(pdf, backend="pipeline", effort="high")
+
+ assert parser.__class__.__name__ == "PdfHybridParser"
+ assert parser.backend == "hybrid-engine"
+ assert parser.effort == "low"
+
+
+def test_pdf_pipeline_parser_compat_delegates_to_hybrid_low() -> None:
+ parser = parser_pdf.PdfPipelineParser(method="ocr", lang="en", effort="high")
+
+ assert isinstance(parser, parser_pdf.PdfHybridParser)
+ assert parser.backend == "hybrid-engine"
+ assert parser.method == "ocr"
+ assert parser.lang == "en"
+ assert parser.effort == "low"
+
+
def test_pdf_hybrid_low_parser_skips_vlm_backend_resolution(monkeypatch: pytest.MonkeyPatch) -> None:
"""校验 Hybrid low 直接进入本地分支,不解析 VLM engine。"""
seen: dict[str, object] = {}
@@ -1124,12 +1158,13 @@ def test_pdf_hybrid_parser_passes_call_mode_to_backend_resolver(monkeypatch: pyt
assert backends == ["sync-backend", "async-backend"]
-def test_api_server_accepts_parser_backend_values(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_api_server_accepts_public_parser_backend_values(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from mineru.utils.backend_options import HTTP_CLIENT_BACKEND_CHOICES, LOCAL_BACKEND_CHOICES, normalize_backend
assert _API_SERVER_BACKENDS == LOCAL_BACKEND_CHOICES + HTTP_CLIENT_BACKEND_CHOICES
_stub_api_server_dependency_preflight(monkeypatch)
+ assert "pipeline" not in _API_SERVER_BACKENDS
assert "vlm" not in _API_SERVER_BACKENDS
assert "vlm-engine" not in _API_SERVER_BACKENDS
assert "vlm-http-client" not in _API_SERVER_BACKENDS
@@ -1138,10 +1173,9 @@ def test_api_server_accepts_parser_backend_values(tmp_path: Path, monkeypatch: p
for backend in _API_SERVER_BACKENDS:
app = create_app(upload_dir=str(tmp_path / backend), backend=backend)
expected_backend = normalize_backend(backend)
- expected_tier = "standard" if expected_backend == "pipeline" else "pro"
assert app.state.backend == expected_backend
- assert app.state.tier == expected_tier
+ assert app.state.tier == "pro"
def test_api_server_stores_parser_runtime_options(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -1158,7 +1192,7 @@ def test_api_server_stores_parser_runtime_options(tmp_path: Path, monkeypatch: p
assert app.state.language == "ch"
assert app.state.ocr_mode == "ocr"
- assert app.state.effort == "high"
+ assert app.state.effort == "low"
assert app.state.table_enable is False
assert app.state.formula_enable is False
assert app.state.image_analysis is False
@@ -1262,6 +1296,7 @@ def test_api_server_cli_help_hides_backend_aliases() -> None:
assert result.exit_code == 0
assert "hybrid-engine" in normalized_output
+ assert "pipeline" not in normalized_output
assert "vlm-engine" not in normalized_output
assert "vlm-http-client" not in normalized_output
assert "hybrid-auto-engine" not in normalized_output
diff --git a/tests/unittest/test_render_html_table.py b/tests/unittest/test_render_html_table.py
index 26d36e62..9b385276 100644
--- a/tests/unittest/test_render_html_table.py
+++ b/tests/unittest/test_render_html_table.py
@@ -197,7 +197,7 @@ def test_render_markdown_prefers_markdown_table_when_enabled() -> None:
)
],
)
- page = PageInfo(page_idx=0, para_blocks=[table_block], _backend="pipeline")
+ page = PageInfo(page_idx=0, para_blocks=[table_block], _backend="hybrid")
assert render_markdown([page], prefer_markdown_table=False) == html
assert render_markdown([page], prefer_markdown_table=True) == "\n".join(
diff --git a/tests/unittest/test_title_level_postprocess.py b/tests/unittest/test_title_level_postprocess.py
index e262473a..a85d58b3 100644
--- a/tests/unittest/test_title_level_postprocess.py
+++ b/tests/unittest/test_title_level_postprocess.py
@@ -1,5 +1,7 @@
import json
+import pytest
+
from mineru.parser.base import ParseResult
from mineru.types import Block, ContentType, Line, PageInfo, Span
from mineru.utils import title_level_postprocess
@@ -55,16 +57,11 @@ def test_regenerate_client_side_outputs_forwards_hybrid_effort(monkeypatch, tmp_
def test_finalize_client_side_pages_uses_explicit_backend(monkeypatch) -> None:
- calls: list[list[PageInfo]] = []
- pages = [PageInfo(page_idx=0, _backend="pipeline")]
- monkeypatch.setattr(
- "mineru.backend.pipeline.model_output_to_middle_json.finalize_middle_json_from_preproc",
- lambda parsed_pages: calls.append(parsed_pages),
- )
-
- title_level_postprocess.finalize_client_side_pages(pages, "pipeline")
+ legacy_backend = "pipeline"
+ pages = [PageInfo(page_idx=0, _backend=legacy_backend)]
- assert calls == [pages]
+ with pytest.raises(ValueError, match="Unsupported client-side finalize backend 'pipeline'"):
+ title_level_postprocess.finalize_client_side_pages(pages, legacy_backend)
def test_finalize_client_side_hybrid_pages_uses_round_tripped_merge_prev_then_cleans_it() -> None: