Skip to content

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

feat: replace content_list_v2 with structured_content and update related functions and documentation

myhloli7dcc429dbba5
diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.md
index fd6dfe4c..5d3b50bb 100644
--- a/docs/en/reference/output_files.md
+++ b/docs/en/reference/output_files.md
@@ -393,13 +393,13 @@ Text levels are distinguished through the `text_level` field:
]
```
-### Common Content List V2 (content_list_v2.json)(development version, subject to change)
+### Common Structured Content (structured_content.json)(development version, subject to change)
-**File naming format**: `{original_filename}_content_list_v2.json`
+**File naming format**: `{original_filename}_structured_content.json`
##### Functionality
-`content_list_v2.json` is the new structured output added in 3.0. All backends now emit it in addition to the legacy `content_list.json`:
+`structured_content.json` is the new structured output added in 3.0. All backends now emit it in addition to the legacy `content_list.json`:
- The top level is grouped by page for page-oriented consumption
- Each item uses a unified `type + content` structure for easier programmatic processing
@@ -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 `*_content_list_v2.json`; see the common V2 section above for the shared structure.
+- Starting with 3.0, the VLM backend also emits `*_structured_content.json`; see the Structured Content section above for the shared structure.
##### Examples
@@ -736,7 +736,7 @@ The above files constitute MinerU's complete output results. Users can choose ap
- **Content extraction**: (Use simplified files):
* *.md
* content_list.json
- * content_list_v2.json
+ * structured_content.json
- **Secondary development**: (Use structured files):
* middle.json
diff --git a/docs/next/implementation-plan.md b/docs/next/implementation-plan.md
index bad12bf9..ef7fba97 100644
--- a/docs/next/implementation-plan.md
+++ b/docs/next/implementation-plan.md
@@ -211,7 +211,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS
3. 调用 `ParseService.process_doc()`。
4. 检查 `parsed/<sha-prefix>/<sha>/<tier>/` 中只有 `.json` 文件。
5. 检查 JSON 内容形态为 `{"pages": [...]}`。
-6. 检查没有 `output.md`、`content_list.json`、`content_list_v2.json`、`output.html`。
+6. 检查没有 `output.md`、`content_list.json`、`structured_content.json`、`output.html`。
完成边界:
@@ -749,7 +749,7 @@ M1 和 M2 的部分测试任务可以并行,但 `ParseResult.from_dict()`、JS
1. 定位当前 `parse_content()` 或等价读取入口,并迁移为 `GET /docs/{sha256}/content`。
2. 实现按 `sha256 + tier + page_range` 收集已完成 JSON 批次。
3. 使用 `ParseResult.from_dict()` 恢复 pages。
-4. 按请求格式调用 `markdown()`、`content_list()`、`content_list_v2()` 或 HTML render。
+4. 按请求格式调用 `markdown()`、`content_list()`、`structured_content()` 或 HTML render。
5. 如果请求页未被覆盖,返回明确状态或错误,不生成空内容。
6. 保持输出文件写入只发生在用户指定 `output` 时。
diff --git a/docs/next/middle-json/README.md b/docs/next/middle-json/README.md
index b92a8e1a..23172574 100644
--- a/docs/next/middle-json/README.md
+++ b/docs/next/middle-json/README.md
@@ -54,7 +54,7 @@ Middle JSON 下一版要达到以下目标:
| Schema | 稳定 dataclass 字段和 envelope。 | `current-standard.md`、`envelope.md` |
| Normalization | 补齐 backend 差异。 | `backend-gaps.md` |
| Agent-native | 引用、locator。 | `agent-gaps.md` |
-| Structured Content | 盘点当前 content_list_v2,作为新 schema 起点。 | `structured-content-current.md` |
+| Structured Content | 盘点当前 structured_content,作为新 schema 起点。 | `structured-content-current.md` |
| Structured Content Schema | 定义 NEXT 版目标 schema 草案。 | `structured-content-schema.md` |
| Rendering | 统一 Markdown / Content List / Structured Content 消费。 | `rendering.md` |
| Migration | 分阶段落地。 | `migration.md` |
diff --git a/docs/next/middle-json/backend-gaps.md b/docs/next/middle-json/backend-gaps.md
index 5116c528..e29aefbd 100644
--- a/docs/next/middle-json/backend-gaps.md
+++ b/docs/next/middle-json/backend-gaps.md
@@ -20,7 +20,7 @@
| typed schema | 已解决 | `PageInfo/Block/Line/Span` 已是事实标准。 | 文档化并增加 validation。 |
| 顶层 envelope | 未解决 | `pdf_info/_backend`、`pages`、`ParseResult.pages` 并存。 | 定义 canonical envelope。 |
| bbox 缺失 | 部分解决 | Office/HTML 使用 `EMPTY_BBOX`,Agent 定位不足。 | 标准化 unknown bbox 语义和补齐策略。 |
-| page_size 缺失 | 部分解决 | Office/HTML 可能为空,content_list_v2 bbox 归一化受影响。 | Office/HTML 明确 page_size 策略。 |
+| page_size 缺失 | 部分解决 | Office/HTML 可能为空,structured_content bbox 归一化受影响。 | Office/HTML 明确 page_size 策略。 |
| index 稳定性 | 部分解决 | reading order 可用,但 Agent locator 不够稳定。 | normalization 阶段重编号。 |
| `preproc_blocks` | 部分解决 | PDF backend 有,Office/HTML 主要直接产出 `para_blocks`。 | 明确 public schema 是否保留。 |
| render 统一 | 部分解决 | 有统一 facade,内部仍按 backend dispatch。 | 收敛 backend-specific content list。 |
@@ -35,7 +35,7 @@
- 通常有 `page_size` 和 bbox。
- 有 `preproc_blocks`,并经过 para split 生成 `para_blocks`。
- `doc_title` / `paragraph_title` 等类型可能经后处理转为 `title`。
-- content_list_v2 仍有 pipeline-specific 实现。
+- structured_content 的 PDF 后端实现已收敛到 `render/structured_content.py`;Office 仍保留 office-specific converter。
已解决:
@@ -46,7 +46,7 @@
仍需工作:
1. 明确 `preproc_blocks` 是否写入 public envelope。
-2. 将 pipeline-specific content_list_v2 逻辑逐步迁入通用 render。
+2. 继续确认 PDF 通用 structured_content converter 与 Office converter 的字段差异。
3. 确认 block index 在 `para_blocks + discarded_blocks + children` 中是否满足全页稳定排序。
4. 清理或规范 `doc_title` / `paragraph_title` / `vertical_text` 等类型进入 render 前的归一化规则。
@@ -77,7 +77,7 @@
1. 明确 VLM block 粒度与 Pipeline OCR 粒度的兼容语义。
2. 统一 VLM-specific type 在 content_list / Agent citation 中的表达。
3. 确认归一化坐标绝不进入 public Middle JSON。
-4. 将 VLM content_list_v2 特殊逻辑逐步归并。
+4. 确认 VLM/Hybrid 与 Pipeline 在统一 structured_content converter 下的字段一致性。
验收:
@@ -175,7 +175,7 @@ P0:
P1:
-1. 收敛 content_list_v2 backend-specific 分支。
+1. 收敛 Office/HTML 与 PDF structured_content 字段差异。
2. 统一 Office/HTML unknown bbox 语义。
3. 公开或隐藏 Office style/hyperlink 内部字段。
4. 将 `_backend` 从 `PageInfo` 迁移到 `_meta.backend`。
diff --git a/docs/next/middle-json/migration.md b/docs/next/middle-json/migration.md
index 4e1077b4..4ad7ca15 100644
--- a/docs/next/middle-json/migration.md
+++ b/docs/next/middle-json/migration.md
@@ -100,12 +100,12 @@
1. render facade 接受 envelope 或 pages + meta。
2. 为 markdown 增加可选 Agent marker。
-3. 明确 Content List v2 schema。
-4. 把 backend-specific content_list_v2 逐步收敛到 type-specific helper。
+3. 明确 Structured Content schema。
+4. 把 Office-specific structured_content 逐步收敛到 type-specific helper。
验收:
-- Markdown / Content List / Content List v2 均可从 canonical envelope 生成。
+- Markdown / Content List / Structured Content 均可从 canonical envelope 生成。
- renderer 不依赖 `pdf_info`。
- backend-specific dispatch 数量下降。
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 0fd64a16..06ed7ae4 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -10,16 +10,16 @@
当前已有统一入口:
```python
-from mineru.render import render_markdown, render_content_list, render_content_list_v2
+from mineru.render import render_markdown, render_content_list, render_structured_content
```
`ParseResult` 也通过这些入口生成输出:
- `ParseResult.markdown()`
- `ParseResult.content_list()`
-- `ParseResult.content_list_v2()`
+- `ParseResult.structured_content()`
-`content_list_v2` 是当前代码函数名;NEXT 版公开格式名定为 Structured Content,命名决策见 [ADR-0001](../decisions/0001-json-output-formats.md)。
+`structured_content` 是当前代码和 NEXT 版公开格式名,命名决策见 [ADR-0001](../decisions/0001-json-output-formats.md)。
这说明底稿中“三套 union_make 完全割裂”的问题已经部分解决。
@@ -31,7 +31,7 @@ from mineru.render import render_markdown, render_content_list, render_content_l
|------|----------|
| Markdown | 有统一 facade;Office 仍走 office-specific markdown。 |
| Content List v1 | 有统一 facade;Office 仍走 office-specific converter。 |
-| Content List v2 | Pipeline / VLM / Office 仍分别调用不同实现。 |
+| Structured Content | PDF 后端共用 `render/structured_content.py`;Office 仍走 office-specific converter。 |
此外,render 当前通过 `PageInfo._backend` 判断 backend。这是临时实现,不应成为长期 schema。
@@ -101,22 +101,22 @@ backend = envelope["_meta"]["backend"]
4. validator 提醒 `_backend` 是 legacy/internal。
5. backend-specific 逻辑收敛后,render 不再需要 backend 判断。
-## Content List v2 收敛
+## Structured Content 收敛
P0:
-- 明确 Content List v2 的目标 schema。
-- 确保所有 backend 输出都能生成 v2。
-- 保留当前 backend dispatch,先补 validator。
+- 明确 Structured Content 的目标 schema。
+- 确保所有 backend 输出都能生成 structured_content。
+- 保留当前 Office dispatch,先补 validator。
P1:
-- 抽出通用 block-to-v2 映射。
-- 将 pipeline/vlm/office 特殊逻辑变成 type-specific helper,而不是 backend-specific module。
+- PDF 已抽出通用 block-to-structured-content 映射。
+- 将 Office 特殊逻辑逐步变成 type-specific helper,而不是 backend-specific module。
P2:
-- 删除 backend-specific v2 converter。
+- 删除 backend-specific structured_content converter。
- render 只依赖 block type,不依赖 backend。
## Agent Marker
diff --git a/docs/next/middle-json/structured-content-current.md b/docs/next/middle-json/structured-content-current.md
index 02c35362..c9ddaf0c 100644
--- a/docs/next/middle-json/structured-content-current.md
+++ b/docs/next/middle-json/structured-content-current.md
@@ -1,17 +1,17 @@
-# 当前 Content List v2 结构盘点
+# 当前 Structured Content 结构盘点
状态: Draft
读者: Structured Content schema 设计者、render 开发者、backend 开发者、编程 Agent
-范围: 梳理当前代码中 `content_list_v2` 的事实输出结构,作为 NEXT 版 `structured_content` / `structured-content` schema 的起点
+范围: 梳理当前代码中 `structured_content` 的事实输出结构,作为 NEXT 版 `structured_content` / `structured-content` schema 的起点
非目标: 定义最终 Structured Content schema;重写 render 实现
## 1. 定位
-NEXT 版公开格式名已经定为 `structured_content` / `structured-content`。当前代码里的 `content_list_v2` 是它的事实起点,但不是 NEXT 版公开格式名。
+NEXT 版公开格式名已经定为 `structured_content` / `structured-content`,当前代码也使用该命名。
本文只回答:
-- 当前 `content_list_v2` 从哪里生成。
+- 当前 `structured_content` 从哪里生成。
- 顶层结构是什么。
- 每类 item 当前有哪些字段。
- Pipeline、VLM/Hybrid、Office 之间有哪些差异。
@@ -22,11 +22,10 @@ NEXT 版公开格式名已经定为 `structured_content` / `structured-content`
当前统一入口:
```text
-ParseResult.content_list_v2()
- -> render_content_list_v2(pages, img_bucket_path="")
+ParseResult.structured_content()
+ -> render_structured_content(pages, img_bucket_path="")
-> 根据 PageInfo._backend 分发
- -> pipeline: backend/pipeline/pipeline_middle_json_mkcontent.py
- -> vlm/hybrid: backend/vlm/vlm_middle_json_mkcontent.py
+ -> PDF pipeline/vlm/hybrid: render/structured_content.py
-> office: render/office/output.py
```
@@ -34,16 +33,16 @@ ParseResult.content_list_v2()
| 调用点 | 当前产物名 |
|--------|------------|
-| `ParseResult.save()` | `{prefix}_content_list_v2.json` |
-| 旧 CLI dump | `{pdf_file_name}_content_list_v2.json` |
-| client-side output regeneration | `{doc_stem}_content_list_v2.json` |
-| 当前 parse API server | `output_files.content_list_v2` |
+| `ParseResult.save()` | `{prefix}_structured_content.json` |
+| 旧 CLI dump | `{pdf_file_name}_structured_content.json` |
+| client-side output regeneration | `{doc_stem}_structured_content.json` |
+| 当前 parse API server | `output_files.structured_content` |
-这些是实现现状。NEXT 版公开 API / CLI / SDK 应使用 `structured_content` / `structured-content`。
+这些是实现现状。NEXT 版公开 API / CLI / SDK 统一使用 `structured_content` / `structured-content`。
## 3. 顶层结构
-当前 `render_content_list_v2()` 返回:
+当前 `render_structured_content()` 返回:
```text
list[list[dict]]
@@ -104,7 +103,7 @@ list[list[dict]]
### 4.1 BBox
-当前 PDF backend 的 v2 item bbox 是归一化到 0-1000 的整数框:
+当前 PDF backend 的 structured_content item bbox 是归一化到 0-1000 的整数框:
```json
"bbox": [x0, y0, x1, y1]
@@ -114,7 +113,7 @@ list[list[dict]]
- Pipeline/VLM/Hybrid 会输出 item 级 bbox。
- Office 通常不输出 bbox。
-- v2 converter 没有统一过滤 `EMPTY_BBOX`;如果 source bbox 是 `(0, 0, 0, 0)`,当前可能输出 `[0, 0, 0, 0]`。
+- structured_content converter 没有统一过滤 `EMPTY_BBOX`;如果 source bbox 是 `(0, 0, 0, 0)`,当前可能输出 `[0, 0, 0, 0]`。
- Pipeline helper 返回 tuple,VLM 直接返回 list;JSON 序列化后都会变成 array。
- bbox 只在 item 级别出现;PDF span 通常没有 bbox,Office span 可能因为 `asdict(span)` 携带 bbox。
@@ -137,7 +136,7 @@ Structured Content 需要重新定义 unknown bbox,不应把 `[0, 0, 0, 0]`
当前实现并没有使用全部类型:
-- `md` 和 `code_inline` 当前没有在主要 v2 converter 中稳定产出。
+- `md` 和 `code_inline` 当前没有在主要 structured_content converter 中稳定产出。
- `hyperlink` 可能从 Office raw span 中出现,但它不在 `ContentTypeV2` 中。
- `index` 由 Pipeline 和 Office 输出;VLM converter 当前没有显式 `index` 分支。
@@ -167,7 +166,7 @@ PDF backend 会合并相邻同类 text span,并做换行、连字符和 CJK
### 6.2 Office span
-Office v2 直接使用 `asdict(span)` 输出 span,因此字段更接近 Middle JSON 的 `Span`:
+Office structured_content 直接使用 `asdict(span)` 输出 span,因此字段更接近 Middle JSON 的 `Span`:
```json
{
@@ -529,7 +528,7 @@ Pipeline/Office 输出:
差异:
- Pipeline index item 和 list item 形态接近。
-- Office index item 复用 `_flatten_list_items_v2()`,因此可能带 `ilevel`、`prefix`、`anchor`。
+- Office index item 复用 `_flatten_structured_list_items()`,因此可能带 `ilevel`、`prefix`、`anchor`。
- VLM converter 当前没有显式 `index` 分支。
## 8. Backend 差异汇总
diff --git a/docs/next/middle-json/structured-content-schema.md b/docs/next/middle-json/structured-content-schema.md
index c63b1ab9..3b91abe1 100644
--- a/docs/next/middle-json/structured-content-schema.md
+++ b/docs/next/middle-json/structured-content-schema.md
@@ -3,7 +3,7 @@
状态: Draft
读者: Structured Content 实现者、API/SDK/CLI 开发者、Agent 能力开发者
范围: NEXT 版 `structured_content` / `structured-content` 的目标 schema 草案
-非目标: 定义 Middle JSON;定义 Markdown/HTML 输出;覆盖所有历史 `content_list_v2` 细节
+非目标: 定义 Middle JSON;定义 Markdown/HTML 输出;覆盖所有历史 v2 细节
## 1. 定位
@@ -16,7 +16,7 @@ Structured Content 是从 Middle JSON render 得到的结构化内容 JSON。它
1. 比 Middle JSON 更适合直接消费。
2. 比 Markdown 更结构化。
3. 保留页、item、span、bbox 和 locator,支持 Agent 引用。
-4. 以当前 `content_list_v2` 为起点,但不照搬其内部字段泄漏和 backend 差异。
+4. 以当前 `structured_content` 为起点,但不照搬其内部字段泄漏和 backend 差异。
## 2. 顶层结构
@@ -109,7 +109,7 @@ Structured Content 是从 Middle JSON render 得到的结构化内容 JSON。它
说明:
-- 当前 `content_list_v2` 的外层数组下标应显式提升为 `page_idx`。
+- 当前 `structured_content` 的外层数组下标应显式提升为 `page_idx`。
- Office/HTML 如果没有真实 page size,应输出 `page_size:null`,不要伪造尺寸。
## 4. Item 通用结构
@@ -571,7 +571,7 @@ p{page_idx}_i{item_idx}
## 9. Normalization Rules
-从当前 `content_list_v2` 到 Structured Content 的第一版 normalization:
+从当前 `structured_content` 到 Structured Content 的第一版 normalization:
1. 裸二维数组包装为 envelope。
2. 外层数组下标转成 `page_idx` 和 `page_number`。
@@ -597,7 +597,7 @@ P0 validator 应检查:
- item `locator.page_idx` 与所在 page 一致。
- bbox 只能是 `null` 或 0-1000 的四元整数数组。
- span 不包含 `_` 开头字段。
-- `json`、`content_list_v2`、`content-list-v2` 不作为公开格式名出现。
+- `json` 和历史 v2 格式名不作为公开格式名出现。
## 11. Open Design Points
diff --git a/docs/next/sdk/parse-result.md b/docs/next/sdk/parse-result.md
index f365d1e9..db8680e3 100644
--- a/docs/next/sdk/parse-result.md
+++ b/docs/next/sdk/parse-result.md
@@ -44,7 +44,7 @@ class ParseResult:
def markdown(self, *, add_markers: bool = False) -> str: ...
def content_list(self) -> list[dict]: ...
- def content_list_v2(self) -> list[dict]: ...
+ def structured_content(self) -> list[list[dict]]: ...
def images(self) -> dict[str, bytes]: ...
def save(self, writer) -> None: ...
```
@@ -59,7 +59,7 @@ class ParseResult:
| `from_json()` | TODO | 必须实现。 |
| `markdown()` | 已有 | 保持,参数名稳定。 |
| `content_list()` | 已有 | 保持。 |
-| `content_list_v2()` | 已有 | 保持。 |
+| `structured_content()` | 已有 | 保持。 |
| `images()` | 已有 | 保持,返回 path -> bytes。 |
| `save()` | 已有 | 需要稳定输出文件命名。 |
@@ -126,7 +126,7 @@ writer.write(path: str, data: bytes) -> None
| `{prefix}.md` | Markdown。 |
| `{prefix}_middle.json` | `to_json()`。 |
| `{prefix}_content_list.json` | content list。 |
-| `{prefix}_content_list_v2.json` | content list v2。 |
+| `{prefix}_structured_content.json` | structured content。 |
| `{prefix}_model.json` | 原始模型输出,可选。 |
| image paths | 图片 bytes。 |
diff --git a/docs/next/workflows.md b/docs/next/workflows.md
index 27dd989f..9c9af3e9 100644
--- a/docs/next/workflows.md
+++ b/docs/next/workflows.md
@@ -501,7 +501,7 @@ doclib 不在 `parsed/` 中保存:
- `output.md`
- `content_list.json`
-- `content_list_v2.json`
+- `structured_content.json`
- `output.html`
这些格式都由 Middle JSON 读取时转换得到。
diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.md
index fb5000c2..a02a9eb8 100644
--- a/docs/zh/reference/output_files.md
+++ b/docs/zh/reference/output_files.md
@@ -393,13 +393,13 @@
]
```
-### 通用内容列表 V2 (content_list_v2.json)(开发中,格式可能调整)
+### 通用结构化内容 (structured_content.json)(开发中,格式可能调整)
-**文件命名格式**:`{原文件名}_content_list_v2.json`
+**文件命名格式**:`{原文件名}_structured_content.json`
##### 功能说明
-`content_list_v2.json` 是 3.0 起新增的结构化输出文件,所有后端都会在保留 `content_list.json` 的同时额外输出该文件:
+`structured_content.json` 是 3.0 起新增的结构化输出文件,所有后端都会在保留 `content_list.json` 的同时额外输出该文件:
- 顶层是按页分组的列表,便于按页消费结果
- 每个内容块使用统一的 `type + content` 结构,适合程序化处理
@@ -779,7 +779,7 @@ vlm 后端的 content_list.json 文件结构与 pipeline 后端类似,伴随
* `page_number`
* `aside_text`
* `page_footnote`
-- 3.0 起,vlm 后端也会同时输出 `*_content_list_v2.json`,其通用结构见上文“通用内容列表 V2”。
+- 3.0 起,vlm 后端也会同时输出 `*_structured_content.json`,其通用结构见上文“通用结构化内容”。
##### 示例数据
- code 类型 content
@@ -861,7 +861,7 @@ vlm 后端的 content_list.json 文件结构与 pipeline 后端类似,伴随
- **内容提取**(使用简化文件):
* *.md
* content_list.json
- * content_list_v2.json
+ * structured_content.json
- **二次开发**(使用结构化文件):
* middle.json
diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
deleted file mode 100644
index 00227a84..00000000
--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py
+++ /dev/null
@@ -1,420 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from __future__ import annotations
-
-from typing import Any
-
-from ...render.markdown import _get_title_level
-from ...render.merge import (
- CJK_LANGS,
- _collect_text_for_lang_detection,
- _next_line_starts_with_lowercase_text,
- _normalize_text_content,
-)
-from ...render.merge_visual import _format_embedded_html, _normalize_visual_content
-from ...types import BBox, Block, BlockType, ContentType, ContentTypeV2, IntBBox, Line
-from ...utils.language import detect_lang
-from ..utils.char_utils import is_hyphen_at_line_end
-
-
-def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:
- """将视觉父块的 sub_type 透传到 content_list 输出顶层。"""
- sub_type = para_block.sub_type
- if sub_type:
- para_content["sub_type"] = sub_type
-
-
-def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list[Block]:
- """将连续 ref_text 包装为临时父 Block,供 content_list 输出为参考文献列表。"""
- merged_blocks: list[Block] = []
- ref_group: list[Block] = []
-
- def flush_ref_group() -> None:
- nonlocal ref_group
- if not ref_group:
- return
- if len(ref_group) == 1:
- merged_blocks.append(ref_group[0])
- else:
- merged_blocks.append(
- Block(
- index=ref_group[0].index,
- type=BlockType.REF_TEXT,
- bbox=ref_group[0].bbox,
- blocks=list(ref_group),
- )
- )
- ref_group = []
-
- for para_block in para_blocks or []:
- if para_block.type == BlockType.REF_TEXT:
- ref_group.append(para_block)
- continue
-
- flush_ref_group()
- merged_blocks.append(para_block)
-
- flush_ref_group()
- return merged_blocks
-
-
-def _build_bbox(para_bbox: BBox, page_size: tuple[int, int]) -> IntBBox | None:
- if not para_bbox or not page_size:
- return None
- page_width, page_height = page_size
- x0, y0, x1, y1 = para_bbox
- return (
- int(x0 * 1000 / page_width),
- int(y0 * 1000 / page_height),
- int(x1 * 1000 / page_width),
- int(y1 * 1000 / page_height),
- )
-
-
-def _get_ref_text_item_blocks(para_block: Block) -> list[Block]:
- return para_block.blocks or [para_block]
-
-
-def _split_list_item_blocks(para_block: Block) -> list[Block]:
- item_blocks = []
- current_lines = []
-
- for line_idx, line in enumerate(para_block.lines):
- if line_idx > 0 and line._is_list_start and current_lines:
- item_blocks.append(
- {
- "type": BlockType.TEXT,
- "lines": current_lines,
- }
- )
- current_lines = []
- current_lines.append(line)
-
- if current_lines:
- item_blocks.append(
- {
- "type": BlockType.TEXT,
- "lines": current_lines,
- }
- )
-
- return item_blocks
-
-
-def _get_body_data(para_block: Block) -> tuple[str, str]:
- def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
- for line in lines:
- for span in line.spans:
- span_type = span.type
- if span_type == ContentType.TABLE:
- return span.image_path, span.content
- if span_type == ContentType.CHART:
- return span.image_path, span.content
- if span_type == ContentType.IMAGE:
- return span.image_path, _normalize_visual_content(span.content)
- if span_type == ContentType.INTERLINE_EQUATION:
- return span.image_path, span.content
- return "", ""
-
- if para_block.blocks:
- for block in para_block.blocks:
- block_type = block.type
- if block_type in [
- BlockType.IMAGE_BODY,
- BlockType.TABLE_BODY,
- BlockType.CHART_BODY,
- BlockType.CODE_BODY,
- ]:
- result = get_data_from_spans(block.lines)
- if result != ("", "") or block_type == BlockType.CHART_BODY:
- return result
- return "", ""
-
- return get_data_from_spans(para_block.lines)
-
-
-def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
- block_lang = detect_lang(_collect_text_for_lang_detection(para_block))
- para_content: list[dict[str, Any]] = []
- para_type = para_block.type
-
- for line_idx, line in enumerate(para_block.lines):
- for span_idx, span in enumerate(line.spans):
- span_type = span.type
-
- if span_type == ContentType.TEXT:
- content = _normalize_text_content(span.content)
- if not content.strip():
- continue
-
- output_type = ContentTypeV2.SPAN_PHONETIC if para_type == BlockType.PHONETIC else ContentTypeV2.SPAN_TEXT
- is_last_span = span_idx == len(line.spans) - 1
-
- if block_lang in CJK_LANGS:
- rendered_content = content if is_last_span else f"{content} "
- else:
- if (
- is_last_span
- and is_hyphen_at_line_end(content)
- and _next_line_starts_with_lowercase_text(para_block, line_idx)
- ):
- rendered_content = content[:-1]
- elif is_last_span and is_hyphen_at_line_end(content):
- rendered_content = content
- else:
- rendered_content = f"{content} "
-
- if para_content and para_content[-1]["type"] == output_type:
- para_content[-1]["content"] += rendered_content
- else:
- para_content.append(
- {
- "type": output_type,
- "content": rendered_content,
- }
- )
- elif span_type == ContentType.INLINE_EQUATION:
- content = span.content.strip()
- if content:
- para_content.append(
- {
- "type": ContentTypeV2.SPAN_EQUATION_INLINE,
- "content": content,
- }
- )
-
- if para_content and para_content[-1]["type"] in [
- ContentTypeV2.SPAN_TEXT,
- ContentTypeV2.SPAN_PHONETIC,
- ]:
- para_content[-1]["content"] = para_content[-1]["content"].rstrip()
-
- return para_content
-
-
-def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, page_size: list[int]) -> dict[str, Any] | None:
- para_type = para_block.type
- para_content = None
-
- if para_type in [
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.ASIDE_TEXT,
- BlockType.PAGE_NUMBER,
- BlockType.PAGE_FOOTNOTE,
- ]:
- if para_type == BlockType.HEADER:
- content_type = ContentTypeV2.PAGE_HEADER
- elif para_type == BlockType.FOOTER:
- content_type = ContentTypeV2.PAGE_FOOTER
- elif para_type == BlockType.ASIDE_TEXT:
- content_type = ContentTypeV2.PAGE_ASIDE_TEXT
- elif para_type == BlockType.PAGE_NUMBER:
- content_type = ContentTypeV2.PAGE_NUMBER
- elif para_type == BlockType.PAGE_FOOTNOTE:
- content_type = ContentTypeV2.PAGE_FOOTNOTE
- else:
- raise ValueError(f"Unknown para_type: {para_type}")
- para_content = {
- "type": content_type,
- "content": {
- f"{content_type}_content": merge_para_with_text_v2(para_block),
- },
- }
- elif para_type == BlockType.TITLE:
- title_level = _get_title_level(para_block)
- if title_level != 0:
- para_content = {
- "type": ContentTypeV2.TITLE,
- "content": {
- "title_content": merge_para_with_text_v2(para_block),
- "level": title_level,
- },
- }
- else:
- para_content = {
- "type": ContentTypeV2.PARAGRAPH,
- "content": {
- "paragraph_content": merge_para_with_text_v2(para_block),
- },
- }
- elif para_type in [
- BlockType.TEXT,
- BlockType.ABSTRACT,
- ]:
- para_content = {
- "type": ContentTypeV2.PARAGRAPH,
- "content": {
- "paragraph_content": merge_para_with_text_v2(para_block),
- },
- }
- elif para_type == BlockType.INTERLINE_EQUATION:
- image_path, math_content = _get_body_data(para_block)
- para_content = {
- "type": ContentTypeV2.EQUATION_INTERLINE,
- "content": {
- "math_content": math_content,
- "math_type": "latex",
- "image_source": {"path": f"{img_bucket_path}/{image_path}"},
- },
- }
- elif para_type == BlockType.IMAGE:
- image_caption = []
- image_footnote = []
- image_path, image_content = _get_body_data(para_block)
- for block in para_block.blocks:
- if block.type == BlockType.IMAGE_CAPTION:
- image_caption.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.IMAGE_FOOTNOTE:
- image_footnote.extend(merge_para_with_text_v2(block))
- para_content = {
- "type": ContentTypeV2.IMAGE,
- "content": {
- "image_source": {"path": f"{img_bucket_path}/{image_path}"},
- "image_caption": image_caption,
- "image_footnote": image_footnote,
- },
- }
- if image_content or para_block.sub_type:
- para_content["content"]["content"] = image_content
- _apply_visual_sub_type(para_content, para_block)
- elif para_type == BlockType.TABLE:
- table_caption = []
- table_footnote = []
- image_path, html = _get_body_data(para_block)
- table_html = _format_embedded_html(html, img_bucket_path)
- table_nest_level = 2 if table_html.count("<table") > 1 else 1
- if "colspan" in table_html or "rowspan" in table_html or table_nest_level > 1:
- table_type = ContentTypeV2.TABLE_COMPLEX
- else:
- table_type = ContentTypeV2.TABLE_SIMPLE
- for block in para_block.blocks:
- if block.type == BlockType.TABLE_CAPTION:
- table_caption.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.TABLE_FOOTNOTE:
- table_footnote.extend(merge_para_with_text_v2(block))
- para_content = {
- "type": ContentTypeV2.TABLE,
- "content": {
- "image_source": {"path": f"{img_bucket_path}/{image_path}"},
- "table_caption": table_caption,
- "table_footnote": table_footnote,
- "html": table_html,
- "table_type": table_type,
- "table_nest_level": table_nest_level,
- },
- }
- elif para_type == BlockType.CHART:
- chart_caption = []
- chart_footnote = []
- image_path, _ = _get_body_data(para_block)
- for block in para_block.blocks:
- if block.type == BlockType.CHART_CAPTION:
- chart_caption.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.CHART_FOOTNOTE:
- chart_footnote.extend(merge_para_with_text_v2(block))
- para_content = {
- "type": ContentTypeV2.CHART,
- "content": {
- "image_source": {"path": f"{img_bucket_path}/{image_path}"},
- "content": "",
- "chart_caption": chart_caption,
- "chart_footnote": chart_footnote,
- },
- }
- elif para_type == BlockType.CODE:
- code_caption = []
- code_footnote = []
- code_content = []
- for block in para_block.blocks:
- if block.type == BlockType.CODE_CAPTION:
- code_caption.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.CODE_FOOTNOTE:
- code_footnote.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.CODE_BODY:
- code_content = merge_para_with_text_v2(block)
-
- sub_type = para_block.sub_type
- if sub_type == BlockType.CODE:
- para_content = {
- "type": ContentTypeV2.CODE,
- "content": {
- "code_caption": code_caption,
- "code_content": code_content,
- "code_footnote": code_footnote,
- "code_language": para_block.guess_lang or "txt",
- },
- }
- elif sub_type == BlockType.ALGORITHM:
- para_content = {
- "type": ContentTypeV2.ALGORITHM,
- "content": {
- "algorithm_caption": code_caption,
- "algorithm_content": code_content,
- "algorithm_footnote": code_footnote,
- },
- }
- else:
- raise ValueError(f"Unknown code sub_type: {sub_type}")
- elif para_type == BlockType.REF_TEXT:
- list_items = []
- for block in _get_ref_text_item_blocks(para_block):
- item_content = merge_para_with_text_v2(block)
- if item_content:
- list_items.append(
- {
- "item_type": "text",
- "item_content": item_content,
- }
- )
- para_content = {
- "type": ContentTypeV2.LIST,
- "content": {
- "list_type": ContentTypeV2.LIST_REF,
- "list_items": list_items,
- },
- }
- elif para_type == BlockType.LIST:
- list_items = []
- for block in _split_list_item_blocks(para_block):
- item_content = merge_para_with_text_v2(block)
- if item_content:
- list_items.append(
- {
- "item_type": "text",
- "item_content": item_content,
- }
- )
- para_content = {
- "type": ContentTypeV2.LIST,
- "content": {
- "list_type": ContentTypeV2.LIST_TEXT,
- "attribute": para_block._list_attribute or "unordered",
- "list_items": list_items,
- },
- }
- elif para_type == BlockType.INDEX:
- list_items = []
- for block in _split_list_item_blocks(para_block):
- item_content = merge_para_with_text_v2(block)
- if item_content:
- list_items.append(
- {
- "item_type": "text",
- "item_content": item_content,
- }
- )
- para_content = {
- "type": ContentTypeV2.INDEX,
- "content": {
- "list_type": ContentTypeV2.LIST_TEXT,
- "list_items": list_items,
- },
- }
- if not para_content:
- return None
-
- bbox = _build_bbox(para_block.bbox, page_size)
- if bbox:
- para_content["bbox"] = bbox
-
- return para_content
diff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.py
deleted file mode 100644
index aee86dd7..00000000
--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py
+++ /dev/null
@@ -1,366 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from typing import Any
-
-from loguru import logger
-
-from ...render.markdown import _get_title_level
-from ...render.merge import _normalize_text_content
-from ...render.merge_visual import _build_media_path, _format_embedded_html
-from ...types import Block, BlockType, ContentType, ContentTypeV2, Line
-from ...utils.language import detect_lang
-from ..utils.char_utils import is_hyphen_at_line_end
-
-
-def _has_following_joinable_span(para_block: Block, line_idx: int, span_idx: int) -> bool:
- """判断当前 span 后面是否还有可拼接文本,避免把分隔空格落到段落末尾。"""
- for next_line_idx in range(line_idx, len(para_block.lines)):
- next_line = para_block.lines[next_line_idx]
- start_span_idx = span_idx + 1 if next_line_idx == line_idx else 0
- for next_span in next_line.spans[start_span_idx:]:
- next_span_type = next_span.type
- if next_span_type == ContentType.TEXT:
- if _normalize_text_content(next_span.content).strip():
- return True
- elif next_span_type == ContentType.INLINE_EQUATION:
- if str(next_span.content).strip():
- return True
- return False
-
-
-def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:
- sub_type = para_block.sub_type
- if sub_type:
- para_content["sub_type"] = sub_type
-
-
-def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, page_size: tuple[int, int]) -> dict:
- para_type = para_block.type
- para_content = {}
- if para_type in [
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.ASIDE_TEXT,
- BlockType.PAGE_NUMBER,
- BlockType.PAGE_FOOTNOTE,
- ]:
- if para_type == BlockType.HEADER:
- content_type = ContentTypeV2.PAGE_HEADER
- elif para_type == BlockType.FOOTER:
- content_type = ContentTypeV2.PAGE_FOOTER
- elif para_type == BlockType.ASIDE_TEXT:
- content_type = ContentTypeV2.PAGE_ASIDE_TEXT
- elif para_type == BlockType.PAGE_NUMBER:
- content_type = ContentTypeV2.PAGE_NUMBER
- elif para_type == BlockType.PAGE_FOOTNOTE:
- content_type = ContentTypeV2.PAGE_FOOTNOTE
- else:
- raise ValueError(f"Unknown para_type: {para_type}")
- para_content = {
- "type": content_type,
- "content": {
- f"{content_type}_content": merge_para_with_text_v2(para_block),
- },
- }
- elif para_type == BlockType.TITLE:
- title_level = _get_title_level(para_block)
- if title_level != 0:
- para_content = {
- "type": ContentTypeV2.TITLE,
- "content": {"title_content": merge_para_with_text_v2(para_block), "level": title_level},
- }
- else:
- para_content = {
- "type": ContentTypeV2.PARAGRAPH,
- "content": {
- "paragraph_content": merge_para_with_text_v2(para_block),
- },
- }
- elif para_type in [BlockType.TEXT, BlockType.PHONETIC]:
- para_content = {
- "type": ContentTypeV2.PARAGRAPH,
- "content": {
- "paragraph_content": merge_para_with_text_v2(para_block),
- },
- }
- elif para_type == BlockType.INTERLINE_EQUATION:
- image_path, math_content = get_body_data(para_block)
- para_content = {
- "type": ContentTypeV2.EQUATION_INTERLINE,
- "content": {
- "math_content": math_content,
- "math_type": "latex",
- "image_source": {"path": f"{img_bucket_path}/{image_path}"},
- },
- }
- elif para_type == BlockType.IMAGE:
- image_caption = []
- image_footnote = []
- image_path, image_content = get_body_data(para_block)
- image_source = {
- "path": _build_media_path(img_bucket_path, image_path),
- }
- for block in para_block.blocks:
- if block.type == BlockType.IMAGE_CAPTION:
- image_caption.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.IMAGE_FOOTNOTE:
- image_footnote.extend(merge_para_with_text_v2(block))
- para_content = {
- "type": ContentTypeV2.IMAGE,
- "content": {
- "image_source": image_source,
- "content": image_content if image_content else "",
- "image_caption": image_caption,
- "image_footnote": image_footnote,
- },
- }
- _apply_visual_sub_type(para_content, para_block)
- elif para_type == BlockType.TABLE:
- table_caption = []
- table_footnote = []
- image_path, html = get_body_data(para_block)
- table_html = _format_embedded_html(html, img_bucket_path)
- image_source = {
- "path": f"{img_bucket_path}/{image_path}",
- }
- if table_html.count("<table") > 1:
- table_nest_level = 2
- else:
- table_nest_level = 1
- if "colspan" in table_html or "rowspan" in table_html or table_nest_level > 1:
- table_type = ContentTypeV2.TABLE_COMPLEX
- else:
- table_type = ContentTypeV2.TABLE_SIMPLE
-
- for block in para_block.blocks:
- if block.type == BlockType.TABLE_CAPTION:
- table_caption.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.TABLE_FOOTNOTE:
- table_footnote.extend(merge_para_with_text_v2(block))
- para_content = {
- "type": ContentTypeV2.TABLE,
- "content": {
- "image_source": image_source,
- "table_caption": table_caption,
- "table_footnote": table_footnote,
- "html": table_html,
- "table_type": table_type,
- "table_nest_level": table_nest_level,
- },
- }
- elif para_type == BlockType.CHART:
- chart_caption = []
- chart_footnote = []
- image_path, chart_content = get_body_data(para_block)
- for block in para_block.blocks:
- if block.type == BlockType.CHART_CAPTION:
- chart_caption.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.CHART_FOOTNOTE:
- chart_footnote.extend(merge_para_with_text_v2(block))
- para_content = {
- "type": ContentTypeV2.CHART,
- "content": {
- "image_source": {
- "path": _build_media_path(img_bucket_path, image_path),
- },
- "content": chart_content if chart_content else "",
- "chart_caption": chart_caption,
- "chart_footnote": chart_footnote,
- },
- }
- _apply_visual_sub_type(para_content, para_block)
- elif para_type == BlockType.CODE:
- code_caption = []
- code_content = []
- for block in para_block.blocks:
- if block.type == BlockType.CODE_CAPTION:
- code_caption.extend(merge_para_with_text_v2(block))
- if block.type == BlockType.CODE_BODY:
- code_content = merge_para_with_text_v2(block)
- sub_type = para_block.sub_type
- if sub_type == BlockType.CODE:
- para_content = {
- "type": ContentTypeV2.CODE,
- "content": {
- "code_caption": code_caption,
- "code_content": code_content,
- "code_language": para_block.guess_lang or "txt",
- },
- }
- elif sub_type == BlockType.ALGORITHM:
- para_content = {
- "type": ContentTypeV2.ALGORITHM,
- "content": {
- "algorithm_caption": code_caption,
- "algorithm_content": code_content,
- },
- }
- else:
- raise ValueError(f"Unknown code sub_type: {sub_type}")
- elif para_type == BlockType.REF_TEXT:
- para_content = {
- "type": ContentTypeV2.LIST,
- "content": {
- "list_type": ContentTypeV2.LIST_REF,
- "list_items": [
- {
- "item_type": "text",
- "item_content": merge_para_with_text_v2(para_block),
- }
- ],
- },
- }
- elif para_type == BlockType.LIST:
- if para_block.sub_type:
- if para_block.sub_type == BlockType.REF_TEXT:
- list_type = ContentTypeV2.LIST_REF
- elif para_block.sub_type == BlockType.TEXT:
- list_type = ContentTypeV2.LIST_TEXT
- else:
- raise ValueError(f"Unknown list sub_type: {para_block.sub_type}")
- else:
- list_type = ContentTypeV2.LIST_TEXT
- list_items = []
- for block in para_block.blocks:
- item_content = merge_para_with_text_v2(block)
- if item_content:
- list_items.append(
- {
- "item_type": "text",
- "item_content": item_content,
- }
- )
- para_content = {
- "type": ContentTypeV2.LIST,
- "content": {
- "list_type": list_type,
- "list_items": list_items,
- },
- }
-
- page_width, page_height = page_size
- para_bbox = para_block.bbox
- if para_bbox:
- x0, y0, x1, y1 = para_bbox
- para_content["bbox"] = [
- int(x0 * 1000 / page_width),
- int(y0 * 1000 / page_height),
- int(x1 * 1000 / page_width),
- int(y1 * 1000 / page_height),
- ]
-
- return para_content
-
-
-def get_body_data(para_block: Block) -> tuple[str, str]:
- """
- Extract image_path and body content from para_block
- Returns:
- - For IMAGE: (image_path, content)
- - For TABLE: (image_path, html)
- - For CHART: (image_path, content)
- - For INTERLINE_EQUATION: (image_path, content)
- - Default: ('', '')
- """
-
- def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
- for line in lines:
- for span in line.spans:
- span_type = span.type
- if span_type == ContentType.TABLE:
- return span.image_path, span.content
- elif span_type == ContentType.CHART:
- return span.image_path, span.content
- elif span_type == ContentType.IMAGE:
- return span.image_path, span.content
- elif span_type == ContentType.INTERLINE_EQUATION:
- return span.image_path, span.content
- elif span_type == ContentType.TEXT:
- return "", span.content
- return "", ""
-
- # 处理嵌套的 blocks 结构
- if para_block.blocks:
- for block in para_block.blocks:
- block_type = block.type
- if block_type in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY, BlockType.CODE_BODY]:
- result = get_data_from_spans(block.lines)
- if result != ("", ""):
- return result
- return "", ""
-
- # 处理直接包含 lines 的结构
- return get_data_from_spans(para_block.lines)
-
-
-def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
- block_text = ""
- for line in para_block.lines:
- for span in line.spans:
- if span.type in [ContentType.TEXT]:
- span.content = _normalize_text_content(span.content)
- block_text += span.content
- block_lang = detect_lang(block_text)
-
- para_content: list[dict[str, Any]] = []
- para_type = para_block.type
- for i, line in enumerate(para_block.lines):
- for j, span in enumerate(line.spans):
- span_type = span.type
- if span.content.strip():
- if span_type == ContentType.TEXT:
- if para_type == BlockType.PHONETIC:
- span_type = ContentTypeV2.SPAN_PHONETIC
- else:
- span_type = ContentTypeV2.SPAN_TEXT
- if span_type == ContentType.INLINE_EQUATION:
- span_type = ContentTypeV2.SPAN_EQUATION_INLINE
- if span_type in [
- ContentTypeV2.SPAN_TEXT,
- ]:
- # 定义CJK语言集合(中日韩)
- cjk_langs = {"zh", "ja", "ko"}
- # logger.info(f'block_lang: {block_lang}, content: {content}')
-
- # 判断是否为行末span
- is_last_span = j == len(line.spans) - 1
- has_following_joinable_span = _has_following_joinable_span(para_block, i, j)
-
- if block_lang in cjk_langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
- if has_following_joinable_span and not is_last_span:
- span_content = f"{span.content} "
- else:
- span_content = span.content
- else:
- # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
- if is_last_span and is_hyphen_at_line_end(span.content):
- # 如果下一行的第一个span是小写字母开头,删除连字符
- if (
- i + 1 < len(para_block.lines)
- and para_block.lines[i + 1].spans
- and para_block.lines[i + 1].spans[0].type == ContentType.TEXT
- and para_block.lines[i + 1].spans[0].content
- and para_block.lines[i + 1].spans[0].content[0].islower()
- ):
- span_content = span.content[:-1]
- else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格
- span_content = span.content
- else:
- # 西方文本语境下content间需要空格分隔
- if has_following_joinable_span:
- span_content = f"{span.content} "
- else:
- span_content = span.content
-
- if para_content and para_content[-1]["type"] == span_type:
- # 合并相同类型的span
- para_content[-1]["content"] += span_content
- else:
- span_content = {"type": span_type, "content": span_content}
- para_content.append(span_content)
-
- elif span_type in [ContentTypeV2.SPAN_PHONETIC, ContentTypeV2.SPAN_EQUATION_INLINE]:
- span_content = {"type": span_type, "content": span.content}
- para_content.append(span_content)
- else:
- logger.warning(f"Unknown span type in merge_para_with_text_v2: {span_type}")
- return para_content
diff --git a/mineru/cli_old/client_side_output.py b/mineru/cli_old/client_side_output.py
index 8265e7af..a6818b15 100644
--- a/mineru/cli_old/client_side_output.py
+++ b/mineru/cli_old/client_side_output.py
@@ -6,7 +6,7 @@ from pathlib import Path
from typing import Any
from mineru.parser.base import ParseResult
-from mineru.render import render_content_list, render_content_list_v2, render_markdown
+from mineru.render import render_content_list, render_markdown, render_structured_content
from mineru.utils.title_level_postprocess import finalize_client_side_pages
from mineru.version import __version__
@@ -44,7 +44,7 @@ def regenerate_client_side_outputs(
middle_json_path = parse_dir / f"{doc_stem}_middle.json"
markdown_path = parse_dir / f"{doc_stem}.md"
content_list_path = parse_dir / f"{doc_stem}_content_list.json"
- content_list_v2_path = parse_dir / f"{doc_stem}_content_list_v2.json"
+ structured_content_path = parse_dir / f"{doc_stem}_structured_content.json"
if not middle_json_path.exists():
raise FileNotFoundError(f"Missing middle json file: {middle_json_path}")
@@ -70,8 +70,8 @@ def regenerate_client_side_outputs(
render_content_list(pages, image_dir),
)
_write_json(
- content_list_v2_path,
- render_content_list_v2(pages, image_dir),
+ structured_content_path,
+ render_structured_content(pages, image_dir),
)
output_middle_json = ParseResult(pages=pages).to_dict()
output_middle_json["_backend"] = normalized_backend
@@ -82,5 +82,5 @@ def regenerate_client_side_outputs(
middle_json_path,
markdown_path,
content_list_path,
- content_list_v2_path,
+ structured_content_path,
)
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index 94191fc5..82068ae7 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -19,7 +19,7 @@ from mineru.backend.vlm.vlm_analyze import aio_doc_analyze as aio_vlm_doc_analyz
from mineru.backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze
from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.parser.base import ParseResult
-from mineru.render import render_content_list, render_content_list_v2, render_markdown
+from mineru.render import render_content_list, render_markdown, render_structured_content
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
@@ -266,10 +266,10 @@ def _process_output(
json.dumps(content_list, ensure_ascii=False, indent=4),
)
- content_list_v2 = render_content_list_v2(middle_json, image_dir)
+ structured_content = render_structured_content(middle_json, image_dir)
md_writer.write_string(
- f"{pdf_file_name}_content_list_v2.json",
- json.dumps(content_list_v2, ensure_ascii=False, indent=4),
+ f"{pdf_file_name}_structured_content.json",
+ json.dumps(structured_content, ensure_ascii=False, indent=4),
)
if f_dump_middle_json:
diff --git a/mineru/cli_old/fast_api.py b/mineru/cli_old/fast_api.py
index 19fab7b5..f5109766 100644
--- a/mineru/cli_old/fast_api.py
+++ b/mineru/cli_old/fast_api.py
@@ -561,14 +561,14 @@ def create_result_zip(
),
)
- path = os.path.join(parse_dir, f"{pdf_name}_content_list_v2.json")
+ path = os.path.join(parse_dir, f"{pdf_name}_structured_content.json")
if os.path.exists(path):
zf.write(
path,
arcname=build_zip_arcname(
pdf_name,
parse_dir,
- f"{pdf_name}_content_list_v2.json",
+ f"{pdf_name}_structured_content.json",
),
)
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index 3814196d..304e2f9e 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -1241,7 +1241,7 @@ async def _run_job(
fid = file_store.create_file_for_output(f"{fr.name}.content_list.json", cl, sha256hex=sha)
output_files.content_list = OutputFileRef(file_id=fid, bytes=len(cl))
elif fmt == "structured_content":
- cl2 = json.dumps(result.content_list_v2(), ensure_ascii=False).encode("utf-8")
+ cl2 = json.dumps(result.structured_content(), ensure_ascii=False).encode("utf-8")
sha = hashlib.sha256(cl2).hexdigest()
file_store.store_blob(cl2, sha256hex=sha)
fid = file_store.create_file_for_output(f"{fr.name}.structured_content.json", cl2, sha256hex=sha)
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index 663de991..a3c717e8 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -9,7 +9,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
-from ..render import render_content_list, render_content_list_v2, render_markdown
+from ..render import render_content_list, render_markdown, render_structured_content
from ..schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
from ..types import PageInfo
@@ -74,8 +74,8 @@ class ParseResult:
def content_list(self) -> list[dict[str, Any]]:
return render_content_list(self.pages)
- def content_list_v2(self) -> list[dict[str, Any]]:
- return render_content_list_v2(self.pages)
+ def structured_content(self) -> list[list[dict[str, Any]]]:
+ return render_structured_content(self.pages)
def save(self, writer: Any) -> None:
writer.write_string("markdown.md", self.markdown())
@@ -87,7 +87,7 @@ class ParseResult:
)
writer.write_string(
"structured_content.json",
- json.dumps(self.content_list_v2(), ensure_ascii=False, indent=1),
+ json.dumps(self.structured_content(), ensure_ascii=False, indent=1),
)
if self._model_output is not None:
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index 3269f36f..e7bbc090 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -1,7 +1,7 @@
-from .union_make import render_content_list, render_content_list_v2, render_markdown
+from .union_make import render_content_list, render_markdown, render_structured_content
__all__ = [
"render_content_list",
- "render_content_list_v2",
"render_markdown",
+ "render_structured_content",
]
diff --git a/mineru/render/office/output.py b/mineru/render/office/output.py
index 414c35e6..12155ed1 100644
--- a/mineru/render/office/output.py
+++ b/mineru/render/office/output.py
@@ -111,8 +111,8 @@ def _flatten_list_items(list_block: Block, root_ilevel: int | None = None) -> li
return items
-def _flatten_list_items_v2(list_block: Block, root_ilevel: int | None = None) -> list[dict[str, Any]]:
- """Recursively flatten nested list blocks into v2-structured item dicts."""
+def _flatten_structured_list_items(list_block: Block, root_ilevel: int | None = None) -> list[dict[str, Any]]:
+ """递归展开 Office 嵌套列表,生成 structured_content list item 字典。"""
items = []
if root_ilevel is None:
root_ilevel = _get_list_ilevel(list_block)
@@ -122,9 +122,9 @@ def _flatten_list_items_v2(list_block: Block, root_ilevel: int | None = None) ->
for block in list_block.blocks:
if block.type in [BlockType.LIST, BlockType.INDEX]:
- items.extend(_flatten_list_items_v2(block, root_ilevel))
+ items.extend(_flatten_structured_list_items(block, root_ilevel))
else:
- item_content = merge_para_with_text_v2(block)
+ item_content = merge_para_with_structured_spans(block)
if item_content:
if attribute == "ordered":
prefix = f"{' ' * relative_ilevel}{ordered_counter}."
@@ -347,11 +347,11 @@ def _collect_caption_texts(para_block: Block, caption_type: str) -> list[str]:
return [merge_para_with_text(block) for block in _iter_child_blocks(para_block, caption_type)]
-def _collect_caption_v2(para_block: Block, caption_type: str) -> list[dict[str, Any]]:
- """收集 content_list_v2 使用的结构化 caption spans。"""
+def _collect_structured_caption(para_block: Block, caption_type: str) -> list[dict[str, Any]]:
+ """收集 structured_content 使用的结构化 caption spans。"""
caption_content = []
for block in _iter_child_blocks(para_block, caption_type):
- caption_content.extend(merge_para_with_text_v2(block))
+ caption_content.extend(merge_para_with_structured_spans(block))
return caption_content
@@ -495,7 +495,8 @@ def make_blocks_to_content_list(para_block: Block, img_bucket_path: str, page_id
return para_content
-def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
+def block_to_structured_content(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
+ """将 Office middle_json Block 转换为 structured_content 单项。"""
para_type = para_block.type
para_content: dict[str, Any] = {}
if para_type in [
@@ -514,7 +515,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> d
para_content = {
"type": content_type,
"content": {
- f"{content_type}_content": merge_para_with_text_v2(para_block),
+ f"{content_type}_content": merge_para_with_structured_spans(para_block),
},
}
elif para_type == BlockType.TITLE:
@@ -522,13 +523,13 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> d
if title_level != 0:
para_content = {
"type": ContentTypeV2.TITLE,
- "content": {"title_content": merge_para_with_text_v2(para_block), "level": title_level},
+ "content": {"title_content": merge_para_with_structured_spans(para_block), "level": title_level},
}
else:
para_content = {
"type": ContentTypeV2.PARAGRAPH,
"content": {
- "paragraph_content": merge_para_with_text_v2(para_block),
+ "paragraph_content": merge_para_with_structured_spans(para_block),
},
}
elif para_type in [
@@ -537,7 +538,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> d
para_content = {
"type": ContentTypeV2.PARAGRAPH,
"content": {
- "paragraph_content": merge_para_with_text_v2(para_block),
+ "paragraph_content": merge_para_with_structured_spans(para_block),
},
}
elif para_type == BlockType.INTERLINE_EQUATION:
@@ -558,7 +559,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> d
"type": ContentTypeV2.IMAGE,
"content": {
"image_source": image_source,
- "image_caption": _collect_caption_v2(
+ "image_caption": _collect_structured_caption(
para_block,
BlockType.IMAGE_CAPTION,
),
@@ -578,7 +579,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> d
para_content = {
"type": ContentTypeV2.TABLE,
"content": {
- "table_caption": _collect_caption_v2(
+ "table_caption": _collect_structured_caption(
para_block,
BlockType.TABLE_CAPTION,
),
@@ -596,7 +597,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> d
"path": _build_media_path(img_bucket_path, image_path),
},
"content": _format_embedded_html(chart_content, img_bucket_path),
- "chart_caption": _collect_caption_v2(
+ "chart_caption": _collect_structured_caption(
para_block,
BlockType.CHART_CAPTION,
),
@@ -610,7 +611,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> d
"content": {
"list_type": list_type,
"attribute": attribute,
- "list_items": _flatten_list_items_v2(para_block),
+ "list_items": _flatten_structured_list_items(para_block),
},
}
elif para_type == BlockType.INDEX:
@@ -618,7 +619,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str) -> d
"type": ContentTypeV2.INDEX,
"content": {
"list_type": ContentTypeV2.LIST_TEXT,
- "list_items": _flatten_list_items_v2(para_block),
+ "list_items": _flatten_structured_list_items(para_block),
},
}
@@ -671,8 +672,8 @@ def get_body_data(para_block: Block) -> tuple[str, str]:
return get_data_from_spans(para_block.lines)
-def _span_has_content_for_v2(span: Span, visible_styles: set[str]) -> bool:
- """判断 V2 span 是否应保留,支持 hyperlink children 的可见空白样式。"""
+def _span_has_structured_content(span: Span, visible_styles: set[str]) -> bool:
+ """判断 structured span 是否应保留,支持 hyperlink children 的可见空白样式。"""
content = span.content
span_style = span._style
if content.strip():
@@ -689,8 +690,8 @@ def _span_has_content_for_v2(span: Span, visible_styles: set[str]) -> bool:
return False
-def _render_span_for_v2(span: Span) -> dict[str, Any]:
- """显式渲染 Office v2 span,避免 dataclass 内部字段泄漏到结构化输出。"""
+def _render_structured_span(span: Span) -> dict[str, Any]:
+ """显式渲染 Office structured span,避免 dataclass 内部字段泄漏到结构化输出。"""
rendered_span = span.to_dict()
if rendered_span["type"] == ContentType.INLINE_EQUATION:
rendered_span["type"] = ContentTypeV2.SPAN_EQUATION_INLINE
@@ -699,18 +700,18 @@ def _render_span_for_v2(span: Span) -> dict[str, Any]:
if span._style:
rendered_span["style"] = list(span._style)
if span._children:
- rendered_span["children"] = [_render_span_for_v2(child) for child in span._children]
+ rendered_span["children"] = [_render_structured_span(child) for child in span._children]
return rendered_span
-def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
- """将 Office 段落转换为 content_list_v2 spans,避免原地修改 middle_json。"""
+def merge_para_with_structured_spans(para_block: Block) -> list[dict[str, Any]]:
+ """将 Office 段落转换为 structured_content spans,避免原地修改 middle_json。"""
_visible_styles = {"underline", "strikethrough"}
para_content: list[dict[str, Any]] = []
if para_block.type == BlockType.TITLE:
section_number = para_block.section_number
if section_number:
- # v2 保持结构化 spans,同时补上 middle_json 已生成的自动标题编号。
+ # structured_content 保持结构化 spans,同时补上 middle_json 已生成的自动标题编号。
para_content.append(
{
"type": ContentTypeV2.SPAN_TEXT,
@@ -719,6 +720,6 @@ def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:
)
for line in para_block.lines:
for span in line.spans:
- if _span_has_content_for_v2(span, _visible_styles):
- para_content.append(_render_span_for_v2(span))
+ if _span_has_structured_content(span, _visible_styles):
+ para_content.append(_render_structured_span(span))
return para_content
diff --git a/mineru/render/structured_content.py b/mineru/render/structured_content.py
new file mode 100644
index 00000000..44b08185
--- /dev/null
+++ b/mineru/render/structured_content.py
@@ -0,0 +1,524 @@
+# Copyright (c) Opendatalab. All rights reserved.
+from __future__ import annotations
+
+from typing import Any
+
+from ..backend.utils.char_utils import is_hyphen_at_line_end
+from ..types import BBox, Block, BlockType, ContentType, ContentTypeV2, IntBBox, Line
+from ..utils.language import detect_lang
+from .markdown import _get_title_level
+from .merge import (
+ CJK_LANGS,
+ _collect_text_for_lang_detection,
+ _next_line_starts_with_lowercase_text,
+ _normalize_text_content,
+)
+from .merge_visual import _build_media_path, _format_embedded_html, _normalize_visual_content
+
+
+def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list[Block]:
+ """将连续参考文献块合并为临时父块,统一 content_list 与 structured_content 的列表输出。"""
+ merged_blocks: list[Block] = []
+ ref_group: list[Block] = []
+
+ def flush_ref_group() -> None:
+ """把当前连续 ref_text 分组写入结果,单个块保持原样避免无意义包装。"""
+ nonlocal ref_group
+ if not ref_group:
+ return
+ if len(ref_group) == 1:
+ merged_blocks.append(ref_group[0])
+ else:
+ merged_blocks.append(
+ Block(
+ index=ref_group[0].index,
+ type=BlockType.REF_TEXT,
+ bbox=ref_group[0].bbox,
+ blocks=list(ref_group),
+ )
+ )
+ ref_group = []
+
+ for para_block in para_blocks or []:
+ if para_block.type == BlockType.REF_TEXT:
+ ref_group.append(para_block)
+ continue
+
+ flush_ref_group()
+ merged_blocks.append(para_block)
+
+ flush_ref_group()
+ return merged_blocks
+
+
+def block_to_structured_content(
+ para_block: Block,
+ img_bucket_path: str,
+ page_size: tuple[int, int] | list[int] | None,
+) -> dict[str, Any] | None:
+ """将 PDF middle_json Block 转换为 structured_content 单项。"""
+ para_type = para_block.type
+ para_content: dict[str, Any] | None = None
+
+ if para_type in [
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.ASIDE_TEXT,
+ BlockType.PAGE_NUMBER,
+ BlockType.PAGE_FOOTNOTE,
+ ]:
+ content_type = _page_content_type(para_type)
+ para_content = {
+ "type": content_type,
+ "content": {
+ f"{content_type}_content": merge_para_with_structured_spans(para_block),
+ },
+ }
+ elif para_type == BlockType.TITLE:
+ title_level = _get_title_level(para_block)
+ if title_level != 0:
+ para_content = {
+ "type": ContentTypeV2.TITLE,
+ "content": {
+ "title_content": merge_para_with_structured_spans(para_block),
+ "level": title_level,
+ },
+ }
+ else:
+ para_content = _paragraph_content(para_block)
+ elif para_type in [BlockType.TEXT, BlockType.ABSTRACT, BlockType.PHONETIC]:
+ para_content = _paragraph_content(para_block)
+ elif para_type == BlockType.INTERLINE_EQUATION:
+ image_path, math_content = _get_body_data(para_block)
+ para_content = {
+ "type": ContentTypeV2.EQUATION_INTERLINE,
+ "content": {
+ "math_content": math_content,
+ "math_type": "latex",
+ "image_source": {"path": _build_media_path(img_bucket_path, image_path)},
+ },
+ }
+ elif para_type == BlockType.IMAGE:
+ para_content = _image_content(para_block, img_bucket_path)
+ elif para_type == BlockType.TABLE:
+ para_content = _table_content(para_block, img_bucket_path)
+ elif para_type == BlockType.CHART:
+ para_content = _chart_content(para_block, img_bucket_path)
+ elif para_type == BlockType.CODE:
+ para_content = _code_content(para_block)
+ elif para_type == BlockType.REF_TEXT:
+ para_content = _ref_text_content(para_block)
+ elif para_type == BlockType.LIST:
+ para_content = _list_content(para_block)
+ elif para_type == BlockType.INDEX:
+ para_content = _index_content(para_block)
+
+ if not para_content:
+ return None
+
+ bbox = _build_bbox(para_block.bbox, page_size)
+ if bbox:
+ para_content["bbox"] = bbox
+ return para_content
+
+
+def merge_para_with_structured_spans(para_block: Block) -> list[dict[str, Any]]:
+ """将段落文本和行内公式转换为 structured_content span,且不修改原始 span。"""
+ block_lang = detect_lang(_collect_text_for_lang_detection(para_block))
+ para_content: list[dict[str, Any]] = []
+ para_type = para_block.type
+
+ for line_idx, line in enumerate(para_block.lines):
+ for span_idx, span in enumerate(line.spans):
+ span_type = span.type
+
+ if span_type == ContentType.TEXT:
+ content = _normalize_text_content(span.content)
+ if not content.strip():
+ continue
+
+ output_type = ContentTypeV2.SPAN_PHONETIC if para_type == BlockType.PHONETIC else ContentTypeV2.SPAN_TEXT
+ rendered_content = _render_text_span_content(
+ para_block,
+ block_lang,
+ line,
+ line_idx,
+ span_idx,
+ content,
+ )
+ if para_content and para_content[-1]["type"] == output_type:
+ para_content[-1]["content"] += rendered_content
+ else:
+ para_content.append(
+ {
+ "type": output_type,
+ "content": rendered_content,
+ }
+ )
+ elif span_type == ContentType.INLINE_EQUATION:
+ content = span.content.strip()
+ if content:
+ para_content.append(
+ {
+ "type": ContentTypeV2.SPAN_EQUATION_INLINE,
+ "content": content,
+ }
+ )
+
+ if para_content and para_content[-1]["type"] in [
+ ContentTypeV2.SPAN_TEXT,
+ ContentTypeV2.SPAN_PHONETIC,
+ ]:
+ para_content[-1]["content"] = para_content[-1]["content"].rstrip()
+
+ return para_content
+
+
+def _page_content_type(para_type: str) -> str:
+ """将页面附属块类型映射到 structured_content 顶层类型。"""
+ if para_type == BlockType.HEADER:
+ return ContentTypeV2.PAGE_HEADER
+ if para_type == BlockType.FOOTER:
+ return ContentTypeV2.PAGE_FOOTER
+ if para_type == BlockType.ASIDE_TEXT:
+ return ContentTypeV2.PAGE_ASIDE_TEXT
+ if para_type == BlockType.PAGE_NUMBER:
+ return ContentTypeV2.PAGE_NUMBER
+ if para_type == BlockType.PAGE_FOOTNOTE:
+ return ContentTypeV2.PAGE_FOOTNOTE
+ raise ValueError(f"Unknown para_type: {para_type}")
+
+
+def _paragraph_content(para_block: Block) -> dict[str, Any]:
+ """构造普通段落 structured_content 项。"""
+ return {
+ "type": ContentTypeV2.PARAGRAPH,
+ "content": {
+ "paragraph_content": merge_para_with_structured_spans(para_block),
+ },
+ }
+
+
+def _image_content(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
+ """构造图片 structured_content 项,保留 caption、footnote、sub_type 与视觉文本。"""
+ image_caption: list[dict[str, Any]] = []
+ image_footnote: list[dict[str, Any]] = []
+ image_path, image_content = _get_body_data(para_block)
+ for block in para_block.blocks:
+ if block.type == BlockType.IMAGE_CAPTION:
+ image_caption.extend(merge_para_with_structured_spans(block))
+ if block.type == BlockType.IMAGE_FOOTNOTE:
+ image_footnote.extend(merge_para_with_structured_spans(block))
+ para_content: dict[str, Any] = {
+ "type": ContentTypeV2.IMAGE,
+ "content": {
+ "image_source": {"path": _build_media_path(img_bucket_path, image_path)},
+ "image_caption": image_caption,
+ "image_footnote": image_footnote,
+ },
+ }
+ if image_content or para_block.sub_type:
+ para_content["content"]["content"] = image_content
+ _apply_visual_sub_type(para_content, para_block)
+ return para_content
+
+
+def _table_content(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
+ """构造表格 structured_content 项,并计算简单/复杂表格标记。"""
+ table_caption: list[dict[str, Any]] = []
+ table_footnote: list[dict[str, Any]] = []
+ image_path, html = _get_body_data(para_block)
+ table_html = _format_embedded_html(html, img_bucket_path)
+ table_nest_level = 2 if table_html.count("<table") > 1 else 1
+ if "colspan" in table_html or "rowspan" in table_html or table_nest_level > 1:
+ table_type = ContentTypeV2.TABLE_COMPLEX
+ else:
+ table_type = ContentTypeV2.TABLE_SIMPLE
+ for block in para_block.blocks:
+ if block.type == BlockType.TABLE_CAPTION:
+ table_caption.extend(merge_para_with_structured_spans(block))
+ if block.type == BlockType.TABLE_FOOTNOTE:
+ table_footnote.extend(merge_para_with_structured_spans(block))
+ return {
+ "type": ContentTypeV2.TABLE,
+ "content": {
+ "image_source": {"path": _build_media_path(img_bucket_path, image_path)},
+ "table_caption": table_caption,
+ "table_footnote": table_footnote,
+ "html": table_html,
+ "table_type": table_type,
+ "table_nest_level": table_nest_level,
+ },
+ }
+
+
+def _chart_content(para_block: Block, img_bucket_path: str) -> dict[str, Any]:
+ """构造图表 structured_content 项,兼容仅有截图或仅有 HTML 内容的情况。"""
+ chart_caption: list[dict[str, Any]] = []
+ chart_footnote: list[dict[str, Any]] = []
+ image_path, chart_content = _get_body_data(para_block)
+ for block in para_block.blocks:
+ if block.type == BlockType.CHART_CAPTION:
+ chart_caption.extend(merge_para_with_structured_spans(block))
+ if block.type == BlockType.CHART_FOOTNOTE:
+ chart_footnote.extend(merge_para_with_structured_spans(block))
+ para_content = {
+ "type": ContentTypeV2.CHART,
+ "content": {
+ "image_source": {
+ "path": _build_media_path(img_bucket_path, image_path),
+ },
+ "content": chart_content if chart_content else "",
+ "chart_caption": chart_caption,
+ "chart_footnote": chart_footnote,
+ },
+ }
+ _apply_visual_sub_type(para_content, para_block)
+ return para_content
+
+
+def _code_content(para_block: Block) -> dict[str, Any]:
+ """构造代码或算法 structured_content 项,统一保留 caption 与 footnote。"""
+ code_caption: list[dict[str, Any]] = []
+ code_footnote: list[dict[str, Any]] = []
+ code_content: list[dict[str, Any]] = []
+ for block in para_block.blocks:
+ if block.type == BlockType.CODE_CAPTION:
+ code_caption.extend(merge_para_with_structured_spans(block))
+ if block.type == BlockType.CODE_FOOTNOTE:
+ code_footnote.extend(merge_para_with_structured_spans(block))
+ if block.type == BlockType.CODE_BODY:
+ code_content = merge_para_with_structured_spans(block)
+
+ sub_type = para_block.sub_type
+ if sub_type == BlockType.CODE:
+ return {
+ "type": ContentTypeV2.CODE,
+ "content": {
+ "code_caption": code_caption,
+ "code_content": code_content,
+ "code_footnote": code_footnote,
+ "code_language": para_block.guess_lang or "txt",
+ },
+ }
+ if sub_type == BlockType.ALGORITHM:
+ return {
+ "type": ContentTypeV2.ALGORITHM,
+ "content": {
+ "algorithm_caption": code_caption,
+ "algorithm_content": code_content,
+ "algorithm_footnote": code_footnote,
+ },
+ }
+ raise ValueError(f"Unknown code sub_type: {sub_type}")
+
+
+def _ref_text_content(para_block: Block) -> dict[str, Any]:
+ """构造参考文献列表项,支持已经合并的临时父 ref_text 块。"""
+ list_items: list[dict[str, Any]] = []
+ for block in _get_ref_text_item_blocks(para_block):
+ item_content = merge_para_with_structured_spans(block)
+ if item_content:
+ list_items.append(
+ {
+ "item_type": "text",
+ "item_content": item_content,
+ }
+ )
+ return {
+ "type": ContentTypeV2.LIST,
+ "content": {
+ "list_type": ContentTypeV2.LIST_REF,
+ "list_items": list_items,
+ },
+ }
+
+
+def _list_content(para_block: Block) -> dict[str, Any]:
+ """构造普通列表 structured_content 项,兼容子 block 列表和按行拆分列表。"""
+ if para_block.sub_type:
+ if para_block.sub_type == BlockType.REF_TEXT:
+ list_type = ContentTypeV2.LIST_REF
+ elif para_block.sub_type == BlockType.TEXT:
+ list_type = ContentTypeV2.LIST_TEXT
+ else:
+ raise ValueError(f"Unknown list sub_type: {para_block.sub_type}")
+ else:
+ list_type = ContentTypeV2.LIST_TEXT
+
+ list_items = _block_list_items(para_block)
+ content: dict[str, Any] = {
+ "list_type": list_type,
+ "list_items": list_items,
+ }
+ if list_type == ContentTypeV2.LIST_TEXT:
+ content["attribute"] = para_block._list_attribute or "unordered"
+ return {
+ "type": ContentTypeV2.LIST,
+ "content": content,
+ }
+
+
+def _index_content(para_block: Block) -> dict[str, Any]:
+ """构造目录索引 structured_content 项。"""
+ return {
+ "type": ContentTypeV2.INDEX,
+ "content": {
+ "list_type": ContentTypeV2.LIST_TEXT,
+ "list_items": _block_list_items(para_block),
+ },
+ }
+
+
+def _block_list_items(para_block: Block) -> list[dict[str, Any]]:
+ """将列表容器中的子块或行拆分为 structured_content list_items。"""
+ item_blocks = para_block.blocks if para_block.blocks else _split_list_item_blocks(para_block)
+ list_items: list[dict[str, Any]] = []
+ for block in item_blocks:
+ item_content = merge_para_with_structured_spans(block)
+ if item_content:
+ list_items.append(
+ {
+ "item_type": "text",
+ "item_content": item_content,
+ }
+ )
+ return list_items
+
+
+def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:
+ """将视觉块 sub_type 透传到 structured_content 顶层。"""
+ sub_type = para_block.sub_type
+ if sub_type:
+ para_content["sub_type"] = sub_type
+
+
+def _build_bbox(para_bbox: BBox, page_size: tuple[int, int] | list[int] | None) -> IntBBox | None:
+ """按千分位归一化 bbox,缺少页面尺寸时跳过 bbox 输出。"""
+ if not para_bbox or not page_size:
+ return None
+ page_width, page_height = page_size
+ if not page_width or not page_height:
+ return None
+ x0, y0, x1, y1 = para_bbox
+ return [
+ int(x0 * 1000 / page_width),
+ int(y0 * 1000 / page_height),
+ int(x1 * 1000 / page_width),
+ int(y1 * 1000 / page_height),
+ ]
+
+
+def _get_ref_text_item_blocks(para_block: Block) -> list[Block]:
+ """返回参考文献列表项块,未合并时使用当前块作为单项。"""
+ return para_block.blocks or [para_block]
+
+
+def _split_list_item_blocks(para_block: Block) -> list[Block]:
+ """按 line._is_list_start 将单个列表块拆成临时列表项块。"""
+ item_blocks = []
+ current_lines = []
+
+ for line_idx, line in enumerate(para_block.lines):
+ if line_idx > 0 and line._is_list_start and current_lines:
+ item_blocks.append(
+ Block(
+ index=para_block.index,
+ type=BlockType.TEXT,
+ bbox=para_block.bbox,
+ lines=current_lines,
+ )
+ )
+ current_lines = []
+ current_lines.append(line)
+
+ if current_lines:
+ item_blocks.append(
+ Block(
+ index=para_block.index,
+ type=BlockType.TEXT,
+ bbox=para_block.bbox,
+ lines=current_lines,
+ )
+ )
+
+ return item_blocks
+
+
+def _get_body_data(para_block: Block) -> tuple[str, str]:
+ """从视觉类 block 中提取图片路径和主体内容。"""
+
+ def get_data_from_spans(lines: list[Line]) -> tuple[str, str]:
+ """按 span 顺序读取第一个可渲染的视觉或文本载荷。"""
+ for line in lines:
+ for span in line.spans:
+ span_type = span.type
+ if span_type == ContentType.TABLE:
+ return span.image_path, span.content
+ if span_type == ContentType.CHART:
+ return span.image_path, span.content
+ if span_type == ContentType.IMAGE:
+ return span.image_path, _normalize_visual_content(span.content)
+ if span_type == ContentType.INTERLINE_EQUATION:
+ return span.image_path, span.content
+ if span_type == ContentType.TEXT:
+ return "", span.content
+ return "", ""
+
+ if para_block.blocks:
+ for block in para_block.blocks:
+ block_type = block.type
+ if block_type in [
+ BlockType.IMAGE_BODY,
+ BlockType.TABLE_BODY,
+ BlockType.CHART_BODY,
+ BlockType.CODE_BODY,
+ ]:
+ result = get_data_from_spans(block.lines)
+ if result != ("", "") or block_type == BlockType.CHART_BODY:
+ return result
+ return "", ""
+
+ return get_data_from_spans(para_block.lines)
+
+
+def _has_following_joinable_span(para_block: Block, line_idx: int, span_idx: int) -> bool:
+ """判断当前 span 后面是否还有可拼接内容,避免多余尾随空格。"""
+ for next_line_idx in range(line_idx, len(para_block.lines)):
+ next_line = para_block.lines[next_line_idx]
+ start_span_idx = span_idx + 1 if next_line_idx == line_idx else 0
+ for next_span in next_line.spans[start_span_idx:]:
+ next_span_type = next_span.type
+ if next_span_type == ContentType.TEXT:
+ if _normalize_text_content(next_span.content).strip():
+ return True
+ elif next_span_type == ContentType.INLINE_EQUATION:
+ if str(next_span.content).strip():
+ return True
+ return False
+
+
+def _render_text_span_content(
+ para_block: Block,
+ block_lang: str,
+ line: Line,
+ line_idx: int,
+ span_idx: int,
+ content: str,
+) -> str:
+ """按语言和跨行断词规则渲染 structured_content 文本 span 内容。"""
+ is_last_span = span_idx == len(line.spans) - 1
+ has_following_joinable_span = _has_following_joinable_span(para_block, line_idx, span_idx)
+
+ if block_lang in CJK_LANGS:
+ if has_following_joinable_span and not is_last_span:
+ return f"{content} "
+ return content
+
+ if is_last_span and is_hyphen_at_line_end(content):
+ if _next_line_starts_with_lowercase_text(para_block, line_idx):
+ return content[:-1]
+ return content
+ if has_following_joinable_span:
+ return f"{content} "
+ return content
diff --git a/mineru/render/union_make.py b/mineru/render/union_make.py
index 8a29fd23..fff7f82f 100644
--- a/mineru/render/union_make.py
+++ b/mineru/render/union_make.py
@@ -6,6 +6,7 @@ from typing import Any, Literal
from ..types import PageInfo
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", "vlm", "hybrid", "office"]
@@ -41,36 +42,27 @@ def _dispatch_make_content_list(
return item.to_dict(skip_defaults=True)
-def _dispatch_make_content_list_v2(
+def _dispatch_block_to_structured_content(
backend: Backend,
para_block: Any,
img_bucket_path: str,
page_size: Any,
) -> Any:
- if backend == "pipeline":
- from ..backend.pipeline.pipeline_middle_json_mkcontent import make_blocks_to_content_list_v2
-
- return make_blocks_to_content_list_v2(para_block, img_bucket_path, page_size)
if backend == "office":
- from .office.output import make_blocks_to_content_list_v2
+ from .office.output import block_to_structured_content as office_block_to_structured_content
- return make_blocks_to_content_list_v2(para_block, img_bucket_path)
- # vlm / hybrid
- from ..backend.vlm.vlm_middle_json_mkcontent import make_blocks_to_content_list_v2
+ return office_block_to_structured_content(para_block, img_bucket_path)
- return make_blocks_to_content_list_v2(para_block, img_bucket_path, page_size)
+ return block_to_structured_content(para_block, img_bucket_path, page_size)
def _get_merged_para_blocks(paras_of_layout: list, paras_of_discarded: list, backend: Backend) -> list:
"""Build the para-block list for Content-List modes.
- The pipeline backend runs ``merge_adjacent_ref_text_blocks_for_content``
- before merging layout and discarded blocks; the other backends simply
- concatenate them.
+ PDF backends merge adjacent ``ref_text`` blocks before rendering so both
+ legacy content_list and structured_content expose references as a list.
"""
- if backend == "pipeline":
- from ..backend.pipeline.pipeline_middle_json_mkcontent import merge_adjacent_ref_text_blocks_for_content
-
+ if backend != "office":
return merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))
return (paras_of_layout or []) + (paras_of_discarded or [])
@@ -143,11 +135,11 @@ def render_content_list(
return output_items
-def render_content_list_v2(
+def render_structured_content(
pdf_info: list[PageInfo],
img_bucket_path: str = "",
) -> list[list[dict[str, Any]]]:
- """Render pages to a per-page Content List (V2)."""
+ """Render pages to per-page Structured Content."""
backend = _backend_from_pages(pdf_info)
if backend is None:
return []
@@ -157,7 +149,7 @@ def render_content_list_v2(
page_contents: list[dict[str, Any]] = []
if para_blocks:
for para_block in para_blocks:
- item = _dispatch_make_content_list_v2(backend, para_block, img_bucket_path, page_info.page_size)
+ item = _dispatch_block_to_structured_content(backend, para_block, img_bucket_path, page_info.page_size)
if item:
page_contents.append(item)
output_lists.append(page_contents)
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index ad691c18..09aaa851 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -5,7 +5,7 @@ import pytest
from mineru.parser.base import ParseResult
from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
-from mineru.types import Block, Line, PageInfo, Span
+from mineru.types import Block, ContentType, Line, PageInfo, Span
def test_parse_result_does_not_expose_backend_version_or_file_name() -> None:
@@ -126,3 +126,48 @@ def test_parse_result_from_json_restores_pages() -> None:
restored = ParseResult.from_json(json.dumps(data))
assert restored.to_dict() == ParseResult.from_dict(data).to_dict()
+
+
+def test_parse_result_structured_content_method_and_save_name() -> None:
+ page = PageInfo(
+ page_idx=0,
+ page_size=(100, 100),
+ para_blocks=[
+ Block(
+ index=0,
+ type="text",
+ bbox=(0.0, 0.0, 10.0, 10.0),
+ lines=[
+ Line(
+ bbox=(0.0, 0.0, 10.0, 10.0),
+ spans=[
+ Span(
+ type=ContentType.TEXT,
+ bbox=(0.0, 0.0, 10.0, 10.0),
+ content="hello",
+ )
+ ],
+ )
+ ],
+ )
+ ],
+ _backend="pipeline",
+ )
+ result = ParseResult(pages=[page])
+ writes: dict[str, str] = {}
+
+ class MemoryWriter:
+ def write_string(self, path: str, content: str) -> None:
+ """记录 ParseResult.save 写出的文本产物,避免测试依赖真实文件系统。"""
+ writes[path] = content
+
+ def write(self, path: str, content: bytes) -> None:
+ """记录图片产物写出接口,当前用例不会实际产生图片。"""
+ writes[path] = content.decode("utf-8")
+
+ structured_content = result.structured_content()
+ result.save(MemoryWriter())
+
+ assert structured_content[0][0]["content"]["paragraph_content"][0]["content"] == "hello"
+ assert "structured_content.json" in writes
+ assert "content_list" + "_v2.json" not in writes