Skip to content

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

feat: update Middle JSON schema to 3.0 and enhance document parsing support

myhloli24d16acd7739
diff --git a/CLAUDE.md b/CLAUDE.md
index 56051c54..4dbf1d73 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -150,15 +150,15 @@ class MinerUParser(DocumentParser):
self._analyze_fn = doc_analyze
```
-## Middle JSON Schema 2.0 架构
+## Middle JSON Schema 3.0 架构
-pr-5415 重构后,Middle JSON 已收敛为 schema 2.0 的统一结构,不再有 pipeline/vlm/office 三套独立实现。
+Middle JSON 已收敛为 schema 3.0 的统一结构,并使用结构化 InlineSpan 表达自然语言行内语义,不再有 pipeline/vlm/office 三套独立实现。
### 1. 统一分析入口
-`backend/analyze.py:doc_analyze()` 是 PDF、EPUB、HTML、CSV 与 Office 文档的唯一公共入口,通过 `file_suffix` 路由到 `backend/analysis/pdf/pipeline.py:analyze_pdf`、`backend/analysis/epub.py:analyze_epub`、`backend/analysis/html.py:analyze_html`、`backend/analysis/csv.py:analyze_csv` 或 `backend/analysis/office.py:analyze_office`,最终经 `backend/postprocess/pages.py:model_list_to_pages()` 产出统一 `pages`。`MinerUParser` 是 `DocumentParser` 的唯一实现,替代旧的 `PdfHybridParser`/`PdfFlashParser`/`DocxParser` 等。
+`backend/analyze.py:doc_analyze()` 是 PDF、OFD、EPUB、HTML、CSV 与 Office 文档的唯一公共入口,通过 `file_suffix` 路由到 `backend/analysis/pdf/pipeline.py:analyze_pdf`、`backend/analysis/ofd.py:analyze_ofd`、`backend/analysis/epub.py:analyze_epub`、`backend/analysis/html.py:analyze_html`、`backend/analysis/csv.py:analyze_csv` 或 `backend/analysis/office.py:analyze_office`,生成严格 `ModelJson` 后统一交给 `backend/postprocess/document.py:model_json_to_middle_json()` 构造 `MiddleJson`。`MinerUParser` 是 `DocumentParser` 的唯一实现,替代旧的 `PdfHybridParser`/`PdfFlashParser`/`DocxParser` 等。
-### 2. MiddleJson 顶层字段(schema 2.0)
+### 2. MiddleJson 顶层字段(schema 3.0)
`mineru/types.py:MiddleJson` 严格定义:
@@ -166,12 +166,12 @@ pr-5415 重构后,Middle JSON 已收敛为 schema 2.0 的统一结构,不再
|------|------|------|
| `pages` | `list[PageInfo]` | 严格按 `page_idx` 升序的页面数组 |
| `is_full_document` | `bool` | 是否整本文档解析(空 `page_index_map` 时为 `True`) |
-| `file_suffix` | `Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "rtf", "csv", "epub", "html", "odt", "ods", "odp"]` | 输入文件类型 |
+| `file_suffix` | `Literal["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "rtf", "csv", "epub", "html", "ofd", "odt", "ods", "odp"]` | 输入文件类型 |
| `effort` | `Literal["flash", "medium", "high", "xhigh"]` | 分析强度 |
| `parse_mode` | `Literal["txt", "ocr"]` | 解析模式 |
| `mineru_version` | `str` | MinerU 版本号 |
-不再有 `_backend`/`_version_name`/`pdf_info`/`_ocr_enable`/`_vlm_ocr_enable` 等旧字段。
+schema 3.0 输出不再有 `_backend`/`_version_name`/`pdf_info`/`_ocr_enable`/`_vlm_ocr_enable` 等旧字段;这些字段只能作为受支持旧 payload 的迁移输入出现。
### 2.1 ModelJson 严格容器
@@ -183,12 +183,14 @@ pr-5415 重构后,Middle JSON 已收敛为 schema 2.0 的统一结构,不再
### 4. Block 类型体系
-`mineru/types.py` 使用 Pydantic 模型替代旧 `Block`/`Line`/`Span` dataclass:
+`mineru/types.py` 使用严格 Pydantic 模型替代旧 `Block`/`Line`/几何 `Span` dataclass:
-- 叶子块(`TextBlock`/`EquationBlock`/`ImageBodyBlock` 等)直接持有 `content: str`
+- 自然语言块(正文、标题、页眉页脚、脚注、视觉注释与算法正文)持有 `content: list[InlineSpan]`
+- `InlineSpan` 是 `TextSpan`/`EquationInlineSpan`/`CodeInlineSpan`/`HyperlinkSpan` 的严格联合,只表达行内语义,不携带 bbox、score、字体或图片字段
+- `EquationBlock`、图片/表格/图表 body 与普通 `CodeBodyBlock` 等专用叶子继续使用各自的字符串或图片载荷字段
- 视觉父块(`ImageBlock`/`TableBlock`/`ChartBlock`/`CodeBlock`)持有 `content: list[child blocks]`,子块包含唯一 body + 可选 caption/footnote
- `BlockType.INTERLINE_EQUATION` 已重命名为 `BlockType.EQUATION`
-- 不再有 `Line`/`Span` 独立类型,行级和 span 级 bbox 不再生成
+- 不再生成旧版独立 `Line`/几何 `Span` 类型及行级、span 级 bbox
### 5. 统一 render 入口
@@ -199,15 +201,15 @@ pr-5415 重构后,Middle JSON 已收敛为 schema 2.0 的统一结构,不再
- `RenderFormat.DOCX` → `render_docx`
- `RenderFormat.STRUCTURED_CONTENT` → `render_structured_content`
-`render/_internal/` 下按目标格式分目录组织共享逻辑(`common/`/`markdown/`/`html/`/`docx/`/`structured_content/`),顶层同名模块只是惰性公共门面。行内语义解析归 `backend/postprocess/inline.py`,renderer 只能单向依赖该模块和 `backend/postprocess/table_merge`。不再有 `pipeline_union_make`/`vlm_union_make`/`office_union_make` 三套逻辑,`content_list` 格式和 `render_content_list` 函数已删除。
+`render/_internal/` 下按目标格式分目录组织共享逻辑(`common/`/`markdown/`/`html/`/`docx/`/`structured_content/`),顶层同名模块只是惰性公共门面。InlineSpan 的规范化、连接、裁剪和可见文本操作归 `backend/postprocess/inline.py`,renderer 按 Span discriminator 分派,并只能单向依赖该模块和 `backend/postprocess/table_merge`。不再有 `pipeline_union_make`/`vlm_union_make`/`office_union_make` 三套逻辑,`content_list` 格式和 `render_content_list` 函数已删除。
### 5.1 目录职责
- `model/runtime/` 负责设备、显存、ONNX 与 Hybrid 本地模型生命周期;模型仓库和下载分别位于 `model/registry.py`、`model/download.py`。
-- `model/flash/pdf/` 负责 PDFDocument、PDFium、原生文本、样式和表格恢复;`model/flash/epub/` 负责 OCF、OPF、spine 与 XHTML/SVG;`model/flash/csv.py` 负责分隔符文本解析;`model/flash/office/` 负责十类 Office/RTF/ODF 格式。
-- `utils/` 只保留 geometry、image、image payload、language/text、platform 和 stdio 等叶子能力;活动代码不得把业务实现重新放入 utils。
-- 稳定依赖方向为 `utils/types → model → backend → render → parser/kit/doclib`,禁止反向引用。
+- `model/flash/pdf/` 负责 PDFDocument、PDFium、原生文本、样式和表格恢复;`model/flash/ofd/` 负责 OFD 包、资源、固定版式场景与阅读顺序;`model/flash/epub/` 负责 OCF、OPF、spine 与 XHTML/SVG;`model/flash/csv.py` 负责分隔符文本解析;`model/flash/office/` 负责十类 Office/RTF/ODF 格式。
+- `utils/` 只保留 geometry、image、image payload、language/text、URL/超链接目标校验与共享安全 scheme 集合、platform 和 stdio 等无业务依赖的叶子能力;是否允许相对链接、fragment 等格式策略由调用方显式选择,活动代码不得把格式解析或其它业务实现放入 utils。
+- `utils/types` 共同组成基础能力层,`types.py` 可以复用不依赖上层模块的 leaf utility;稳定依赖方向为 `utils/types → model → backend → render → parser/kit/doclib`,禁止上层模块被基础层反向引用。
### 6. ParseResult 与 MiddleJson 的关系
-`ParseResult` 持有 `MiddleJson` 实例,`pages` 改为 property 委托给 `middle_json.pages`。`to_dict()`/`from_dict()` 处理 schema 2.0 与旧 1.0 payload 的双向兼容(1.0 经 `backend/postprocess/legacy_schema_adapter.py:legacy_page_to_model_list` 回推为 model_list 重走后处理)。
+`ParseResult` 持有 `MiddleJson` 实例,`pages` property 委托给 `middle_json.pages`。`to_dict()` 只输出 schema 3.0;`from_dict()` 直接读取 3.0,并将 MinerU 3.4.5 `pdf_info` 与对应 schema 1.0 `pages` 包装经 `backend/postprocess/legacy_schema_adapter.py:legacy_page_to_model_list` 单向回推为 raw model-list 后重走统一后处理。schema 2.0 与其它未知旧 payload 不自动迁移,必须从源文件重新解析。
diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.md
index a6d73ee3..4f4d4485 100644
--- a/docs/next/middle-json/current-medium.md
+++ b/docs/next/middle-json/current-medium.md
@@ -19,8 +19,9 @@
`tuple[MiddleJson, ModelJson]`,`ParseResult.to_dict()` 输出
`schema_version="3.0"`。
-Schema 3.0 是严格切换:缺失版本或版本为 1.0/2.0 的 API 结果、缓存和本地
-payload 不自动迁移,调用方必须从源文件重新解析。
+Schema 3.0 是严格的运行时与公开输出契约。`ParseResult.from_dict()` 直接读取 3.0,
+并仅将可识别的 MinerU 3.4.5 `pdf_info` 或对应 schema 1.0 `pages` 包装单向迁移为 3.0;
+其它缺失版本的 envelope、schema 2.0 与未知旧 payload 必须从源文件重新解析。
## ModelJson
diff --git a/mineru/model/flash/ofd/images.py b/mineru/model/flash/ofd/images.py
index 7ba6857a..1a0a6dcf 100644
--- a/mineru/model/flash/ofd/images.py
+++ b/mineru/model/flash/ofd/images.py
@@ -97,7 +97,7 @@ def build_image_item(
ctm = parse_affine(image_object.get("CTM"))
raw_angle = transform_angle(parent_transform.compose(ctm))
angle = canonical_angle(raw_angle)
- if angle not in {0, 90, 180, 270} or not math.isclose(raw_angle % 90.0, 0.0, abs_tol=5.0):
+ if angle not in {0, 90, 180, 270} or not math.isclose(math.remainder(raw_angle, 90.0), 0.0, abs_tol=5.0):
diagnostic = "unsupported_image_affine"
payload = None
else:
diff --git a/mineru/model/flash/ofd/text.py b/mineru/model/flash/ofd/text.py
index 9e80023f..bb6dac1b 100644
--- a/mineru/model/flash/ofd/text.py
+++ b/mineru/model/flash/ofd/text.py
@@ -317,7 +317,7 @@ def build_text_lines(
lines: list[TextLine] = []
object_id = parse_int(text_object.get("ID"))
for code_index, text_code in enumerate(element for element in text_object if local_name(element.tag) == "TextCode"):
- text = decode_text_code(element_text(text_code))
+ text = decode_text_code("".join(text_code.itertext()))
if not text:
continue
budget.charge(text)
diff --git a/mineru/model/flash/office/docx/docx_converter.py b/mineru/model/flash/office/docx/docx_converter.py
index f6067116..8e70fa36 100644
--- a/mineru/model/flash/office/docx/docx_converter.py
+++ b/mineru/model/flash/office/docx/docx_converter.py
@@ -43,6 +43,7 @@ from ..._shared.spans import (
inline_span_plain_text,
slice_span_dicts,
strip_span_dicts,
+ text_spans,
)
from ..rich_text import (
append_rich_text_element,
@@ -839,10 +840,11 @@ class DocxConverter:
shape_text_elements = shape_text_xpath(element)
if shape_text_elements:
# 从形状文本创建自定义文本元素
- text_content = " ".join([t.text for t in shape_text_elements if t.text])
- text_content = self._normalize_text_block_content(text_content)
- if text_content.strip():
- logger.debug(f"Found shape text: {text_content[:50]}...")
+ raw_text = " ".join([t.text for t in shape_text_elements if t.text])
+ text_content = self._normalize_text_block_content(text_spans(raw_text))
+ visible_text = inline_span_plain_text(text_content)
+ if visible_text:
+ logger.debug(f"Found shape text: {visible_text[:50]}...")
self.cur_page.append(
{
"type": BlockType.TEXT,
diff --git a/tests/unittest/test_flash_docx_equationxml.py b/tests/unittest/test_flash_docx_equationxml.py
index 8816794e..359e6b6b 100644
--- a/tests/unittest/test_flash_docx_equationxml.py
+++ b/tests/unittest/test_flash_docx_equationxml.py
@@ -3,7 +3,9 @@ from __future__ import annotations
import asyncio
from io import BytesIO
from pathlib import Path
+from zipfile import ZIP_DEFLATED, ZipFile
+from docx import Document
from lxml import etree # type: ignore[reportAttributeAccessIssue]
import pytest
@@ -69,6 +71,39 @@ def _equationxml_with_forbidden_pict() -> str:
return etree.tostring(root, encoding="unicode")
+def _fallback_shape_text_docx(text: str) -> bytes:
+ """构造只可由 shape-text fallback 读取文字的 DOCX。"""
+ document = Document()
+ document.add_paragraph("before")
+ source_buffer = BytesIO()
+ document.save(source_buffer)
+ with ZipFile(BytesIO(source_buffer.getvalue())) as source:
+ members = {name: source.read(name) for name in source.namelist()}
+
+ word_namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+ drawing_namespace = "http://schemas.openxmlformats.org/drawingml/2006/main"
+ root = etree.fromstring(members["word/document.xml"])
+ body = root.find(f"{{{word_namespace}}}body")
+ assert body is not None
+ drawing = etree.Element(f"{{{word_namespace}}}drawing")
+ text_body = etree.SubElement(drawing, f"{{{drawing_namespace}}}txBody")
+ etree.SubElement(text_body, f"{{{drawing_namespace}}}bodyPr")
+ etree.SubElement(text_body, f"{{{drawing_namespace}}}t").text = text
+ body.insert(max(0, len(body) - 1), drawing)
+ members["word/document.xml"] = etree.tostring(
+ root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+
+ output = BytesIO()
+ with ZipFile(output, "w", ZIP_DEFLATED) as target:
+ for name, payload in members.items():
+ target.writestr(name, payload)
+ return output.getvalue()
+
+
def test_equationxml_decoder_converts_spec_document_and_fraction() -> None:
"""验证规范 Word 2003 XML 包装可复用现有 OMML 转换器。"""
@@ -78,6 +113,16 @@ def test_equationxml_decoder_converts_spec_document_and_fraction() -> None:
assert decoder.decode(build_word_2003_fraction_equation_xml()) == r"\frac{a}{b}"
+def test_docx_fallback_shape_text_uses_inline_spans() -> None:
+ """验证非标准 shape 文字 fallback 输出 Span 而不会中断整份解析。"""
+ pages = DocxModel().predict(BytesIO(_fallback_shape_text_docx(" shape text ")))
+
+ assert pages[0][-1] == {
+ "type": BlockType.TEXT,
+ "content": text_spans("shape text"),
+ }
+
+
@pytest.mark.parametrize(
("source_latex", "expected_latex"),
[
diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.py
index 32bb78d1..6bb9f5c0 100644
--- a/tests/unittest/test_flash_ofd.py
+++ b/tests/unittest/test_flash_ofd.py
@@ -7,6 +7,8 @@ from io import BytesIO
from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile
+from lxml import etree
+from PIL import Image
import pytest
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
@@ -17,7 +19,12 @@ from mineru.doclib.services.parse_svc import ParseService
from mineru.errors import InvalidRequestError
from mineru.model.flash import OfdModel
from mineru.model.flash.ofd import OfdParseError, detect_ofd
+from mineru.model.flash.ofd.geometry import Affine, canonical_angle
+from mineru.model.flash.ofd.images import build_image_item
+from mineru.model.flash.ofd.models import MediaResource, OfdPageScene, ResourceRegistry
from mineru.model.flash.ofd.package import OfdPackage
+from mineru.model.flash.ofd.reading_order import OfdReadingOrderProjector
+from mineru.model.flash.ofd.text import FontMetricResolver, OfdTextBudget, build_text_lines
from mineru.parser import MinerUParser
from mineru.parser import api_server
from mineru.parser.api_server import CreateJobRequest, FileStore
@@ -141,6 +148,99 @@ def test_ofd_cardinal_text_directions_keep_geometry_and_angle() -> None:
assert model.pages[0][0]["bbox"][3] > model.pages[0][0]["bbox"][1]
+def test_ofd_textcode_preserves_boundary_whitespace_and_glyph_positions() -> None:
+ """验证 TextCode 首尾空格参与 Delta 展开和 CGTransform 全局位置映射。"""
+ text_element = etree.fromstring(
+ b'<TextObject ID="9" Boundary="10 10 50 10" Font="1" Size="5">'
+ b'<TextCode X="1" Y="5" DeltaX="5 7"> A </TextCode>'
+ b'<CGTransform CodePosition="1" CodeCount="1"><Glyphs>42</Glyphs></CGTransform>'
+ b"</TextObject>"
+ )
+ package_buffer = BytesIO()
+ with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:
+ archive.writestr("OFD.xml", "<OFD/>")
+ package = OfdPackage(package_buffer.getvalue())
+
+ lines = build_text_lines(
+ text_element,
+ parent_transform=Affine(),
+ parent_clip=(0.0, 0.0, 100.0, 100.0),
+ resources=ResourceRegistry(),
+ package=package,
+ font_metrics=FontMetricResolver(package),
+ budget=OfdTextBudget(),
+ paint_order=0,
+ layer_type="body",
+ template_id=None,
+ )
+
+ assert len(lines) == 1
+ assert lines[0].text == " A "
+ assert [glyph.glyph_id for glyph in lines[0].glyphs] == [None, 42, None]
+ assert [glyph.origin[0] for glyph in lines[0].glyphs] == pytest.approx([11.0, 16.0, 23.0])
+
+
+ ("raw_angle", "expected_angle"),
+ [
+ (89.9, 90),
+ (90.1, 90),
+ (179.9, 180),
+ (180.1, 180),
+ (359.9, 0),
+ (0.1, 0),
+ ],
+)
+def test_ofd_image_near_cardinal_rotation_accepts_both_directions(raw_angle: float, expected_angle: int) -> None:
+ """验证图片旋转从直角两侧逼近时都保留载荷和阅读顺序 block。"""
+ image_buffer = BytesIO()
+ Image.new("RGB", (2, 2), "white").save(image_buffer, format="PNG")
+ package_buffer = BytesIO()
+ with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:
+ archive.writestr("OFD.xml", "<OFD/>")
+ archive.writestr("Res/image.png", image_buffer.getvalue())
+ package = OfdPackage(package_buffer.getvalue())
+ transform = Affine.rotation(raw_angle)
+ ctm = " ".join(str(value) for value in (transform.a, transform.b, transform.c, transform.d, transform.e, transform.f))
+ image_element = etree.fromstring(f'<ImageObject ID="1" Boundary="0 0 10 10" ResourceID="1" CTM="{ctm}"/>'.encode())
+ resources = ResourceRegistry(
+ media={
+ 1: MediaResource(
+ resource_id=1,
+ media_type="Image",
+ media_format="PNG",
+ media_part="Res/image.png",
+ )
+ }
+ )
+
+ item = build_image_item(
+ image_element,
+ parent_transform=Affine(),
+ parent_clip=(0.0, 0.0, 100.0, 100.0),
+ resources=resources,
+ package=package,
+ paint_order=0,
+ layer_type="body",
+ template_id=None,
+ )
+
+ assert item is not None
+ assert item.diagnostic is None
+ assert item.image_base64
+ scene = OfdPageScene(
+ page_idx=0,
+ physical_box=(0.0, 0.0, 100.0, 100.0),
+ content_box=None,
+ images=[item],
+ )
+ blocks = OfdReadingOrderProjector([scene]).project_page(scene)
+ assert len(blocks) == 1
+ assert blocks[0]["type"] == BlockType.IMAGE
+ assert blocks[0]["image_base64"] == item.image_base64
+ assert canonical_angle(raw_angle) == expected_angle
+
+
def test_ofd_template_grid_recovers_table() -> None:
"""验证模板路径和页面文字共同恢复高置信全线表。"""
paths = "".join(