Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix: bound raster decoding and malformed OFD paths
myhlolicdc82f9724ea
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4dbf1d73..aba8eab8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -199,9 +199,13 @@ schema 3.0 输出不再有 `_backend`/`_version_name`/`pdf_info`/`_ocr_enable`/`- `RenderFormat.MARKDOWN` → `render_markdown`- `RenderFormat.HTML` → `render_html`- `RenderFormat.DOCX` → `render_docx`+- `RenderFormat.EPUB` → `render_epub`- `RenderFormat.STRUCTURED_CONTENT` → `render_structured_content`+- `RenderFormat.CONTENT_LIST` → `render_content_list`+- `RenderFormat.CONTENT_LIST_V2` → `render_content_list_v2`+- `RenderFormat.PDF` → `render_pdf`-`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` 函数已删除。+`render/_internal/` 下按目标格式分目录组织共享逻辑(`common/`/`markdown/`/`html/`/`docx/`/`epub/`/`pdf/`/`content_list/`/`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 V1/V2 是由严格 MiddleJson 派生的正式兼容输出,不恢复旧 backend 并行实现。EPUB、PDF 与两套 Content List 只扩展低层 `mineru.render` 公共面,不自动扩展 ParseResult、CLI、API Server 或 doclib 输出合同。### 5.1 目录职责diff --git a/docs/next/decisions/0001-json-output-formats.md b/docs/next/decisions/0001-json-output-formats.mdindex 010081aa..163ef245 100644--- a/docs/next/decisions/0001-json-output-formats.md+++ b/docs/next/decisions/0001-json-output-formats.md@@ -31,9 +31,9 @@ MinerU 当前同时存在三类 JSON 结构:| Structured Content | `structured-content` | `structured_content` | 面向 Agent 和新客户端的结构化内容 JSON,替代公开名称 `content-list-v2`。 || HTML | `html` | `html` | 从 Middle JSON 或 Markdown 派生的 HTML 输出。 |-`Structured Content` 是 Content List v2 这类结构的公开产品名。当前代码中的 `content_list_v2` 函数名属于实现现状,不进入 NEXT 版公开 CLI/API/SDK 格式契约。+`Structured Content` 是面向新客户端的 Content List v2 类结构产品名。低层 `mineru.render` 同时正式保留 `content_list` 与 `content_list_v2` 两套 3.4.5 兼容输出;它们属于 SDK render 合同,但不因此进入 NEXT CLI 或 API Server 的正式格式集合。-`json` 不作为正式格式名。`content_list_v2` / `content-list-v2` 不进入公开格式集合。NEXT 版尚未实现,没有历史兼容负担;除当前代码内部命名外,新实现和新文档只使用正式格式名。+`json` 不作为正式格式名。CLI/API 产品文档继续使用 `structured-content` / `structured_content`,不把 `content-list-v2` / `content_list_v2` 作为同义格式名;需要精确兼容 3.4.5 V2 结构的 SDK 调用方使用 `mineru.render.RenderFormat.CONTENT_LIST_V2` 或 `render_content_list_v2()`。## 输出边界@@ -86,12 +86,12 @@ Structured Content 的版本演进通过 schema version 表达,而不是把公- CLI `--format` 应支持 `middle-json`、`content-list`、`structured-content`。- API `output_formats` 应支持 `middle_json`、`content_list`、`structured_content`。-- 当前代码里的 `content_list_v2()` / `render_content_list_v2()` 需要迁移到 Structured Content 语义;公开接口只使用正式格式名。+- `render_content_list()` / `render_content_list_v2()` 作为低层 SDK 兼容输出保留;新客户端优先使用 Structured Content。- doclib 的 `parsed/` 目录仍只持久化 Middle JSON;Content List v1 和 Structured Content 都是读取时派生结果。## 后续动作1. 更新 CLI/API/SDK 文档中的格式名示例。2. 为 Structured Content 定义 schema version 字段和 validator。-3. 将现有 `render_content_list_v2()` 的文档表述逐步迁移为 Structured Content render。-4. 在实现计划中把 `content_list_v2` backend-specific converter 收敛任务改写为 Structured Content schema 收敛任务。+3. 文档必须区分低层兼容 renderer 与 CLI/API 产品格式名,不能把 `content_list_v2` 当作 `structured_content` 的别名。+4. Content List renderer 只从严格 MiddleJson 派生,不恢复 backend-specific converter。diff --git a/mineru/model/flash/ofd/images.py b/mineru/model/flash/ofd/images.pyindex 1a0a6dcf..bc92e9b2 100644--- a/mineru/model/flash/ofd/images.py+++ b/mineru/model/flash/ofd/images.py@@ -12,6 +12,7 @@ from lxml import etree # type: ignore[reportMissingImports]from .._shared.image import image_to_b64strfrom ....types import BBox+from ....utils.image_payload import validate_decoded_raster_sizefrom .geometry import Affine, bbox_intersection, canonical_angle, parse_affine, parse_st_box, transform_angle, transform_bboxfrom .models import ImageItem, ResourceRegistryfrom .package import OfdPackage, parse_int@@ -23,6 +24,7 @@ def _serialize_raster(data: bytes, *, alpha: int, angle: int) -> str | None:"""使用 Pillow 校验、旋转并编码常见位图。"""try:with Image.open(BytesIO(data)) as source:+ validate_decoded_raster_size(*source.size)source.load()image = source.copy()except (Image.DecompressionBombError, UnidentifiedImageError, OSError, SyntaxError, ValueError):diff --git a/mineru/model/flash/ofd/path.py b/mineru/model/flash/ofd/path.pyindex f35f461d..7f9605ca 100644--- a/mineru/model/flash/ofd/path.py+++ b/mineru/model/flash/ofd/path.py@@ -101,7 +101,7 @@ def _segments(value: str, transform: Affine, budget: OfdPathBudget) -> list[tuplcurrent = subpath_startcontinueif command is None or command == "C":- continue+ return []needed = arity[command]if index + needed > len(tokens):breakdiff --git a/mineru/render/_internal/epub/assets.py b/mineru/render/_internal/epub/assets.pyindex e57bf0cc..1719a28c 100644--- a/mineru/render/_internal/epub/assets.py+++ b/mineru/render/_internal/epub/assets.py@@ -18,6 +18,7 @@ from ....utils.image_payload import (extract_mineru_generated_svg_fallback,normalize_image_extension,parse_image_data_uri_strict,+ validate_decoded_raster_size,validate_image_sidecar_path,)@@ -149,6 +150,7 @@ def _prepare_epub_image(data: bytes, *, declared_extension: str | None) -> tupledetected = normalize_image_extension(image.format or "")if not detected:raise ValueError("Unsupported image format")+ validate_decoded_raster_size(*image.size)image.load()if expected is not None and expected != detected:raise ValueError("Image bytes do not match the declared format")@@ -159,7 +161,7 @@ def _prepare_epub_image(data: bytes, *, declared_extension: str | None) -> tupleoutput = BytesIO()converted.save(output, format="PNG")return output.getvalue(), "png"- except (UnidentifiedImageError, OSError, ValueError) as exc:+ except (Image.DecompressionBombError, UnidentifiedImageError, OSError, ValueError) as exc:raise ValueError("Invalid or unsupported image payload") from excdiff --git a/mineru/render/_internal/pdf/assets.py b/mineru/render/_internal/pdf/assets.pyindex 7c280910..819f7b69 100644--- a/mineru/render/_internal/pdf/assets.py+++ b/mineru/render/_internal/pdf/assets.py@@ -16,6 +16,7 @@ from ....types import ImagePayloadBlockfrom ....utils.image_payload import (extract_mineru_generated_svg_fallback,parse_image_data_uri_strict,+ validate_decoded_raster_size,validate_image_sidecar_path,)@@ -106,6 +107,10 @@ def prepare_image_bytes(data: bytes, *, declared_extension: str | None = None) -if detected_extension is None:raise PdfAssetError(f"Unsupported image format: {image.format or 'unknown'}")width_px, height_px = image.size+ try:+ validate_decoded_raster_size(width_px, height_px)+ except ValueError as exc:+ raise PdfAssetError(str(exc)) from excimage.load()if expected_extension is not None and expected_extension != detected_extension:raise PdfAssetError(@@ -115,7 +120,7 @@ def prepare_image_bytes(data: bytes, *, declared_extension: str | None = None) -return _convert_webp_to_png(image, width_px, height_px)except PdfAssetError:raise- except (UnidentifiedImageError, OSError, ValueError) as exc:+ except (Image.DecompressionBombError, UnidentifiedImageError, OSError, ValueError) as exc:raise PdfAssetError("Invalid or corrupted image payload") from excreturn PreparedImage(data=data,diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.pyindex 452e89d2..60783efa 100644--- a/mineru/utils/image_payload.py+++ b/mineru/utils/image_payload.py@@ -7,6 +7,7 @@ import hashlibfrom pathlib import Path, PureWindowsPathimport reimport xml.etree.ElementTree as ElementTree+from typing import Finalfrom urllib.parse import urlsplitINLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;\"']+);base64,([^\"']+)", re.DOTALL)@@ -14,6 +15,8 @@ _SVG_NAMESPACE = "http://www.w3.org/2000/svg"_MINERU_SVG_MARKER = "wmf-emf"_MINERU_SVG_FALLBACK_ID = "mineru-raster-fallback"MAX_GENERATED_SVG_BYTES = 64 * 1024 * 1024+MAX_DECODED_RASTER_DIMENSION: Final = 8_192+MAX_DECODED_RASTER_PIXELS: Final = 16_000_000_MAX_GENERATED_SVG_NODES = 100_000_SAFE_SVG_ATTRIBUTES: dict[str, set[str]] = {"svg": {"width", "height", "viewBox", "data-mineru-generated"},@@ -68,6 +71,21 @@ def normalize_image_extension(fmt: str) -> str:return "jpg" if normalized in {"jpeg", "jpg"} else normalized+def validate_decoded_raster_size(width: int, height: int) -> None:+ """在 Pillow 解码像素前校验 raster 单边尺寸与总像素预算。"""+ if (+ width <= 0+ or height <= 0+ or width > MAX_DECODED_RASTER_DIMENSION+ or height > MAX_DECODED_RASTER_DIMENSION+ or width * height > MAX_DECODED_RASTER_PIXELS+ ):+ raise ValueError(+ f"Decoded raster image exceeds limits: {width}x{height}; "+ f"max_dimension={MAX_DECODED_RASTER_DIMENSION}, max_pixels={MAX_DECODED_RASTER_PIXELS}"+ )++def _parse_svg_root_strict(payload: bytes) -> ElementTree.Element:"""在固定字节预算内解析 SVG 根节点,并在实体展开前拒绝 DTD。"""if len(payload) > MAX_GENERATED_SVG_BYTES:diff --git a/tests/unittest/test_epub_render.py b/tests/unittest/test_epub_render.pyindex 29baf568..442eef9e 100644--- a/tests/unittest/test_epub_render.py+++ b/tests/unittest/test_epub_render.py@@ -4,6 +4,7 @@ import base64from copy import deepcopyfrom datetime import datetime, timezonefrom io import BytesIO+from unittest.mock import MagicMockfrom zipfile import ZIP_STORED, ZipFilefrom lxml import etree@@ -13,6 +14,7 @@ import pytestfrom mineru.backend.analyze import doc_analyzefrom mineru.model.flash.epub import EpubPackagefrom mineru.render import render_epub+from mineru.render._internal.epub import assets as epub_assetsfrom mineru.types import (AlgorithmBodyBlock,ChartBlock,@@ -34,6 +36,11 @@ from mineru.types import (TableBodyBlock,TextBlock,)+from mineru.utils.image_payload import (+ MAX_DECODED_RASTER_DIMENSION,+ MAX_DECODED_RASTER_PIXELS,+ validate_decoded_raster_size,+)from _epub_test_utils import build_epub_fixturefrom _span_test_utils import equation, hyperlink, inline@@ -337,6 +344,62 @@ def test_epub_assets_are_embedded_deduplicated_and_missing_sources_degrade_to_teassert requested == ["images/shared.png", "images/missing.png"]+ ("width", "height", "is_valid"),+ [+ (4_000, 4_000, True),+ (8_192, 1, True),+ (4_001, 4_000, False),+ (8_193, 1, False),+ (0, 1, False),+ (-1, 1, False),+ ],+)+def test_decoded_raster_size_uses_shared_dimension_and_pixel_limits(width: int, height: int, is_valid: bool) -> None:+ """验证共享 raster 解码预算固定为单边 8192 与总像素 1600 万。"""+ assert MAX_DECODED_RASTER_DIMENSION == 8_192+ assert MAX_DECODED_RASTER_PIXELS == 16_000_000+ if is_valid:+ validate_decoded_raster_size(width, height)+ return+ with pytest.raises(ValueError, match="Decoded raster image exceeds limits"):+ validate_decoded_raster_size(width, height)+++def test_epub_oversized_image_is_omitted_before_pixel_decode(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 EPUB 超限 raster 在 load 前省略且保留图片识别文字。"""+ image = MagicMock()+ image.__enter__.return_value = image+ image.format = "PNG"+ image.size = (4_001, 4_000)+ image.load.side_effect = AssertionError("oversized image must not be decoded")+ monkeypatch.setattr(epub_assets.Image, "open", lambda _source: image)+ middle = _middle(+ _page(+ 0,+ ImageBlock(+ type="image",+ index=0,+ content=[+ ImageBodyBlock(+ type="image_body",+ index=0,+ content="Oversized OCR",+ image_path="images/oversized.png",+ )+ ],+ ),+ )+ )++ payload = render_epub(middle, asset_resolver=lambda _path: b"oversized", modified_at=_FIXED_TIME)++ with _archive(payload) as archive:+ assert not [name for name in archive.namelist() if name.startswith("EPUB/assets/")]+ assert "Oversized OCR" in _text(_xml(archive, "EPUB/text/content.xhtml"))+ image.load.assert_not_called()++def test_epub_mathml_failure_uses_visible_latex_without_false_manifest_property() -> None:"""验证无效 LaTeX 回退为可见文本且不会误声明 mathml。"""middle = _middle(_page(0, EquationBlock(type="equation", index=0, content="{")))diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.pyindex 6bb9f5c0..1dc26205 100644--- a/tests/unittest/test_flash_ofd.py+++ b/tests/unittest/test_flash_ofd.py@@ -5,6 +5,7 @@ import hashlibimport jsonfrom io import BytesIOfrom pathlib import Path+from unittest.mock import MagicMockfrom zipfile import ZIP_DEFLATED, ZipFilefrom lxml import etree@@ -19,10 +20,12 @@ from mineru.doclib.services.parse_svc import ParseServicefrom mineru.errors import InvalidRequestErrorfrom mineru.model.flash import OfdModelfrom mineru.model.flash.ofd import OfdParseError, detect_ofd+from mineru.model.flash.ofd import images as ofd_imagesfrom mineru.model.flash.ofd.geometry import Affine, canonical_anglefrom mineru.model.flash.ofd.images import build_image_itemfrom mineru.model.flash.ofd.models import MediaResource, OfdPageScene, ResourceRegistryfrom mineru.model.flash.ofd.package import OfdPackage+from mineru.model.flash.ofd.path import OfdPathBudget, _segmentsfrom mineru.model.flash.ofd.reading_order import OfdReadingOrderProjectorfrom mineru.model.flash.ofd.text import FontMetricResolver, OfdTextBudget, build_text_linesfrom mineru.parser import MinerUParser@@ -241,6 +244,46 @@ def test_ofd_image_near_cardinal_rotation_accepts_both_directions(raw_angle: floassert canonical_angle(raw_angle) == expected_angle+def test_ofd_oversized_image_is_rejected_before_pixel_decode(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 OFD 超限 raster 在 Pillow load 前降级为无载荷 diagnostic。"""+ image = MagicMock()+ image.__enter__.return_value = image+ image.size = (8_193, 1)+ image.load.side_effect = AssertionError("oversized image must not be decoded")+ monkeypatch.setattr(ofd_images.Image, "open", lambda _source: image)+ package_buffer = BytesIO()+ with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:+ archive.writestr("OFD.xml", "<OFD/>")+ archive.writestr("Res/image.png", b"oversized")+ package = OfdPackage(package_buffer.getvalue())+ image_element = etree.fromstring(b'<ImageObject ID="1" Boundary="0 0 10 10" ResourceID="1"/>')++ item = build_image_item(+ image_element,+ parent_transform=Affine(),+ parent_clip=(0.0, 0.0, 100.0, 100.0),+ resources=ResourceRegistry(+ media={1: MediaResource(1, "Image", "PNG", "Res/image.png")},+ ),+ package=package,+ paint_order=0,+ layer_type="body",+ template_id=None,+ )++ assert item is not None+ assert item.image_base64 is None+ assert item.diagnostic == "unsupported_image_payload"+ image.load.assert_not_called()+++def test_ofd_path_rejects_unexpected_numeric_tokens_without_hanging() -> None:+ """验证无活动命令或 C 后的数字 token 直接使当前非法路径降级。"""+ assert _segments("1 2", Affine(), OfdPathBudget()) == []+ assert _segments("M 0 0 C 1 2 L 3 4", Affine(), OfdPathBudget()) == []+ assert _segments("M 0 0 L 10 0", Affine(), OfdPathBudget()) == [((0.0, 0.0), (10.0, 0.0))]++def test_ofd_template_grid_recovers_table() -> None:"""验证模板路径和页面文字共同恢复高置信全线表。"""paths = "".join(diff --git a/tests/unittest/test_pdf_render.py b/tests/unittest/test_pdf_render.pyindex 3cc75794..9636b2fe 100644--- a/tests/unittest/test_pdf_render.py+++ b/tests/unittest/test_pdf_render.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom concurrent.futures import ThreadPoolExecutorfrom copy import deepcopyfrom io import BytesIO+from unittest.mock import MagicMockimport base64from PIL import Image@@ -13,6 +14,7 @@ import ziamathfrom _span_test_utils import inline as _inlinefrom mineru.render import render_pdf+from mineru.render._internal.pdf import assets as pdf_assetsfrom mineru.render._internal.pdf import formula as formula_modulefrom mineru.render._internal.pdf.formula import FormulaRenderer, FormulaVector, PdfFormulaErrorfrom mineru.types import (@@ -352,6 +354,38 @@ def test_pdf_uses_asset_resolver_and_replaces_missing_or_remote_images_with_placassert "page_idx=0, block_index=2, block_type=image_body" in text+def test_pdf_oversized_image_uses_placeholder_before_pixel_decode(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 PDF 超限 raster 在 load 前转为现有宽松 placeholder。"""+ image = MagicMock()+ image.__enter__.return_value = image+ image.format = "PNG"+ image.size = (4_001, 4_000)+ image.load.side_effect = AssertionError("oversized image must not be decoded")+ monkeypatch.setattr(pdf_assets.Image, "open", lambda _source: image)+ middle = _middle(+ _page(+ 0,+ ImageBlock(+ type="image",+ index=0,+ content=[+ ImageBodyBlock(+ type="image_body",+ index=0,+ content="Oversized image",+ image_path="images/oversized.png",+ )+ ],+ ),+ )+ )++ reader = _reader(render_pdf(middle, asset_resolver=lambda _path: b"oversized"))++ assert "image unavailable" in _page_text(reader, 0)+ image.load.assert_not_called()++def test_pdf_renders_tables_lists_indices_code_algorithm_and_annotations() -> None:"""验证原生表格合并、嵌套表、目录、列表、代码算法与说明的组合输出。"""table = TableBlock.model_validate(