Skip to content

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

fix: bound OFD and renderer resource handling

myhlolieeb59d34da0b
diff --git a/mineru/model/flash/ofd/constants.py b/mineru/model/flash/ofd/constants.py
index 52f67aa9..71c59be6 100644
--- a/mineru/model/flash/ofd/constants.py
+++ b/mineru/model/flash/ofd/constants.py
@@ -21,6 +21,7 @@ MAX_EXPANDED_TEXT_BYTES: Final = 64 * 1024 * 1024
MAX_EXPANDED_GLYPHS: Final = 2_000_000
MAX_PATH_COMMANDS: Final = 2_000_000
MAX_OBJECT_RECURSION: Final = 64
+MAX_DRAW_PARAM_INHERITANCE: Final = 64
MAX_FONT_BYTES: Final = 32 * 1024 * 1024
MM_TO_POINTS: Final = 72.0 / 25.4
@@ -28,6 +29,7 @@ MM_TO_POINTS: Final = 72.0 / 25.4
__all__ = [
"MAX_ASSET_TOTAL_BYTES",
+ "MAX_DRAW_PARAM_INHERITANCE",
"MAX_ENTRY_BYTES",
"MAX_ENTRY_COUNT",
"MAX_EXPANDED_GLYPHS",
diff --git a/mineru/model/flash/ofd/resources.py b/mineru/model/flash/ofd/resources.py
index d11fbde6..958ebfa7 100644
--- a/mineru/model/flash/ofd/resources.py
+++ b/mineru/model/flash/ofd/resources.py
@@ -5,6 +5,8 @@ from __future__ import annotations
from loguru import logger
+from .constants import MAX_DRAW_PARAM_INHERITANCE
+from .errors import OfdResourceLimitError
from .geometry import parse_numbers
from .models import CompositeResource, FontResource, MediaResource, ResourceRegistry
from .package import OfdPackage, element_text, first_child, local_name, parse_int
@@ -93,27 +95,27 @@ def merge_registries(*registries: ResourceRegistry) -> ResourceRegistry:
def resolve_draw_param(registry: ResourceRegistry, resource_id: int | None) -> dict[str, str]:
- """递归解析 DrawParam Relative 继承并检测循环。"""
+ """迭代解析 DrawParam Relative 继承,并限制深度、检测循环。"""
if resource_id is None:
return {}
- result: dict[str, str] = {}
- visiting: set[int] = set()
-
- def visit(current_id: int) -> None:
- """按父到子顺序合并一个 DrawParam。"""
- if current_id in visiting:
+ inheritance_chain: list[dict[str, str]] = []
+ visited: set[int] = set()
+ current_id: int | None = resource_id
+ while current_id is not None:
+ if current_id in visited:
raise ValueError(f"OFD DrawParam cycle detected at id={current_id}")
current = registry.draw_params.get(current_id)
if current is None:
- return
- visiting.add(current_id)
- parent = parse_int(current.get("Relative"))
- if parent is not None:
- visit(parent)
- result.update({key: value for key, value in current.items() if key not in {"ID", "Relative"}})
- visiting.remove(current_id)
+ break
+ if len(inheritance_chain) >= MAX_DRAW_PARAM_INHERITANCE:
+ raise OfdResourceLimitError(f"OFD resource limit exceeded: max_draw_param_inheritance={MAX_DRAW_PARAM_INHERITANCE}")
+ visited.add(current_id)
+ inheritance_chain.append(current)
+ current_id = parse_int(current.get("Relative"))
- visit(resource_id)
+ result: dict[str, str] = {}
+ for current in reversed(inheritance_chain):
+ result.update({key: value for key, value in current.items() if key not in {"ID", "Relative"}})
return result
diff --git a/mineru/model/flash/ofd/scene.py b/mineru/model/flash/ofd/scene.py
index b6af296a..023b1884 100644
--- a/mineru/model/flash/ofd/scene.py
+++ b/mineru/model/flash/ofd/scene.py
@@ -203,6 +203,8 @@ class OfdSceneBuilder:
style = dict(context.draw_style)
try:
style.update(resolve_draw_param(resources, parse_int(element.get("DrawParam"))))
+ except OfdResourceLimitError:
+ raise
except ValueError as exc:
raise OfdParseError(str(exc)) from exc
style.update({str(key): str(value) for key, value in element.attrib.items()})
diff --git a/mineru/model/flash/ofd/text.py b/mineru/model/flash/ofd/text.py
index bb6dac1b..c01ff637 100644
--- a/mineru/model/flash/ofd/text.py
+++ b/mineru/model/flash/ofd/text.py
@@ -340,11 +340,9 @@ def build_text_lines(
previous = origins[-1]
origins.append((previous[0] + delta_x[index], previous[1] + delta_y[index]))
glyph_items: list[GlyphItem] = []
- visible_text: list[str] = []
for index, (character, origin) in enumerate(zip(text, origins, strict=True)):
glyph_id = glyph_by_position.get(global_position + index)
resolved_character = font_metrics.resolve_character(font, glyph_id, character)
- visible_text.append(resolved_character)
advance_hint = None
if index + 1 < len(origins):
advance_hint = math.dist(origin, origins[index + 1])
@@ -363,7 +361,9 @@ def build_text_lines(
glyph_bbox = quad_bbox(quad)
if glyph_bbox is None:
continue
- clipped_glyph_bbox = bbox_intersection(glyph_bbox, object_clip) or glyph_bbox
+ clipped_glyph_bbox = bbox_intersection(glyph_bbox, object_clip)
+ if clipped_glyph_bbox is None:
+ continue
glyph_items.append(
GlyphItem(
text=resolved_character,
@@ -374,16 +374,16 @@ def build_text_lines(
)
)
global_position += len(text)
+ if not glyph_items:
+ continue
line_bbox = bbox_union(item.bbox for item in glyph_items)
if line_bbox is None:
- line_bbox = object_clip
- else:
- line_bbox = bbox_intersection(line_bbox, object_clip) or line_bbox
+ continue
if line_bbox[2] <= line_bbox[0] or line_bbox[3] <= line_bbox[1]:
continue
lines.append(
TextLine(
- text="".join(visible_text),
+ text="".join(item.text for item in glyph_items),
bbox=line_bbox,
glyphs=glyph_items,
angle=canonical_angle(transform_angle(direction_transform)),
diff --git a/mineru/render/_internal/epub/assets.py b/mineru/render/_internal/epub/assets.py
index 1719a28c..102cd98b 100644
--- a/mineru/render/_internal/epub/assets.py
+++ b/mineru/render/_internal/epub/assets.py
@@ -15,6 +15,8 @@ from PIL import Image, UnidentifiedImageError
from ...contracts import AssetResolver
from ....types import ImagePayloadBlock
from ....utils.image_payload import (
+ MAX_IMAGE_DATA_URI_BYTES,
+ MAX_IMAGE_PAYLOAD_BYTES,
extract_mineru_generated_svg_fallback,
normalize_image_extension,
parse_image_data_uri_strict,
@@ -109,6 +111,8 @@ class EpubAssetRegistry:
def _resolve_data_uri(self, data_uri: str) -> str | None:
"""严格解码图片 data URI,失败时返回可降级的空结果。"""
+ if len(data_uri) > MAX_IMAGE_DATA_URI_BYTES:
+ return None
cache_key = f"data:{hashlib.sha256(data_uri.encode('utf-8', errors='replace')).hexdigest()}"
if cache_key in self._source_cache:
return self._source_cache[cache_key]
@@ -138,6 +142,8 @@ def _prepare_epub_image(data: bytes, *, declared_extension: str | None) -> tuple
"""校验图片字节,并把非 PNG/JPEG/GIF 栅格统一转为 PNG。"""
if not isinstance(data, bytes) or not data:
raise ValueError("Image payload must contain bytes")
+ if len(data) > MAX_IMAGE_PAYLOAD_BYTES:
+ raise ValueError("Image payload exceeds its byte limit")
expected = normalize_image_extension(declared_extension or "") or None
if expected == "svg" or _SVG_START_RE.match(data[:4096]) is not None:
if expected not in {None, "svg"}:
diff --git a/mineru/render/_internal/pdf/assets.py b/mineru/render/_internal/pdf/assets.py
index 819f7b69..28c56d78 100644
--- a/mineru/render/_internal/pdf/assets.py
+++ b/mineru/render/_internal/pdf/assets.py
@@ -14,6 +14,7 @@ from PIL import Image, UnidentifiedImageError
from ...contracts import AssetResolver
from ....types import ImagePayloadBlock
from ....utils.image_payload import (
+ MAX_IMAGE_PAYLOAD_BYTES,
extract_mineru_generated_svg_fallback,
parse_image_data_uri_strict,
validate_decoded_raster_size,
@@ -88,6 +89,8 @@ def prepare_image_bytes(data: bytes, *, declared_extension: str | None = None) -
raise PdfAssetError("Image resolver must return bytes")
if not data:
raise PdfAssetError("Image payload must not be empty")
+ if len(data) > MAX_IMAGE_PAYLOAD_BYTES:
+ raise PdfAssetError("Image payload exceeds its byte limit")
expected_extension = _normalize_extension(declared_extension)
if expected_extension == "svg" or _looks_like_svg(data):
try:
diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.py
index 60783efa..f8fc4acd 100644
--- a/mineru/utils/image_payload.py
+++ b/mineru/utils/image_payload.py
@@ -14,7 +14,10 @@ INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;\"']+);base64,([^\"']+)",
_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_IMAGE_PAYLOAD_BYTES: Final = 64 * 1024 * 1024
+MAX_GENERATED_SVG_BYTES: Final = MAX_IMAGE_PAYLOAD_BYTES
+MAX_RASTER_IMAGE_BYTES: Final = MAX_IMAGE_PAYLOAD_BYTES
+MAX_IMAGE_DATA_URI_BYTES: Final = len("data:image/svg+xml;base64,") + ((MAX_IMAGE_PAYLOAD_BYTES + 2) // 3) * 4
MAX_DECODED_RASTER_DIMENSION: Final = 8_192
MAX_DECODED_RASTER_PIXELS: Final = 16_000_000
_MAX_GENERATED_SVG_NODES = 100_000
@@ -102,6 +105,8 @@ def _parse_svg_root_strict(payload: bytes) -> ElementTree.Element:
def parse_image_data_uri_strict(data_uri: str) -> tuple[bytes, str]:
"""严格解析图片 data URI,并同时校验 MIME 与文件签名是否一致。"""
+ if len(data_uri) > MAX_IMAGE_DATA_URI_BYTES:
+ raise ValueError("Image data URI exceeds its byte limit")
match = re.fullmatch(r"data:image/([^;]+);base64,([A-Za-z0-9+/]*={0,2})", data_uri)
if match is None:
raise ValueError("Invalid image data URI")
@@ -109,18 +114,23 @@ def parse_image_data_uri_strict(data_uri: str) -> tuple[bytes, str]:
mime_subtype = match.group(1).lower()
extension = normalize_image_extension(mime_subtype)
encoded_payload = match.group(2)
+ payload_limit = MAX_GENERATED_SVG_BYTES if extension == "svg" else MAX_RASTER_IMAGE_BYTES
+ max_encoded_bytes = ((payload_limit + 2) // 3) * 4
+ if len(encoded_payload) > max_encoded_bytes:
+ payload_kind = "SVG" if extension == "svg" else "Raster"
+ raise ValueError(f"{payload_kind} image payload exceeds its byte limit")
if extension == "svg":
if mime_subtype != "svg+xml":
raise ValueError(f"Unsupported image MIME subtype: {mime_subtype}")
- max_encoded_bytes = ((MAX_GENERATED_SVG_BYTES + 2) // 3) * 4
- if len(encoded_payload) > max_encoded_bytes:
- raise ValueError("SVG image payload exceeds its byte limit")
try:
payload = base64.b64decode(encoded_payload, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError("Invalid base64 image payload") from exc
if not payload:
raise ValueError("Image payload must not be empty")
+ if len(payload) > payload_limit:
+ payload_kind = "SVG" if extension == "svg" else "Raster"
+ raise ValueError(f"{payload_kind} image payload exceeds its byte limit")
if extension == "svg":
_parse_svg_root_strict(payload)
diff --git a/tests/unittest/test_epub_render.py b/tests/unittest/test_epub_render.py
index 442eef9e..d32557c3 100644
--- a/tests/unittest/test_epub_render.py
+++ b/tests/unittest/test_epub_render.py
@@ -41,6 +41,7 @@ from mineru.utils.image_payload import (
MAX_DECODED_RASTER_PIXELS,
validate_decoded_raster_size,
)
+from mineru.utils import image_payload as image_payload_utils
from _epub_test_utils import build_epub_fixture
from _span_test_utils import equation, hyperlink, inline
@@ -366,6 +367,35 @@ def test_decoded_raster_size_uses_shared_dimension_and_pixel_limits(width: int,
validate_decoded_raster_size(width, height)
+def test_image_data_uri_enforces_encoded_and_decoded_byte_budgets(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 raster data URI 会在 Base64 前后分别执行固定字节预算。"""
+ decode = MagicMock(return_value=b"\x89PNG\r\n\x1a\nx")
+ monkeypatch.setattr(image_payload_utils, "MAX_RASTER_IMAGE_BYTES", 8)
+ monkeypatch.setattr(image_payload_utils.base64, "b64decode", decode)
+
+ with pytest.raises(ValueError, match="Raster image payload exceeds its byte limit"):
+ image_payload_utils.parse_image_data_uri_strict("data:image/png;base64,AAAAAAAAAAAAAAAA")
+ decode.assert_not_called()
+
+ with pytest.raises(ValueError, match="Raster image payload exceeds its byte limit"):
+ image_payload_utils.parse_image_data_uri_strict("data:image/png;base64,AAAA")
+ decode.assert_called_once_with("AAAA", validate=True)
+
+
+def test_epub_oversized_data_uri_is_omitted_before_hashing(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 EPUB 在缓存键哈希前拒绝超过编码预算的 data URI。"""
+ digest = MagicMock(side_effect=AssertionError("oversized data URI must not be hashed"))
+ monkeypatch.setattr(epub_assets, "MAX_IMAGE_DATA_URI_BYTES", len(_PNG_URI) - 1)
+ monkeypatch.setattr(epub_assets.hashlib, "sha256", digest)
+ registry = epub_assets.EpubAssetRegistry(None)
+
+ href = registry.resolve_block(ImageBodyBlock(type="image_body", index=0, content="OCR", image_base64=_PNG_URI))
+
+ assert href is None
+ assert registry.assets == ()
+ digest.assert_not_called()
+
+
def test_epub_oversized_image_is_omitted_before_pixel_decode(monkeypatch: pytest.MonkeyPatch) -> None:
"""验证 EPUB 超限 raster 在 load 前省略且保留图片识别文字。"""
image = MagicMock()
diff --git a/tests/unittest/test_flash_ofd.py b/tests/unittest/test_flash_ofd.py
index 1dc26205..ddd31e0a 100644
--- a/tests/unittest/test_flash_ofd.py
+++ b/tests/unittest/test_flash_ofd.py
@@ -19,14 +19,16 @@ from mineru.doclib.core.fts import FTSManager
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 import OfdParseError, OfdResourceLimitError, detect_ofd
from mineru.model.flash.ofd import images as ofd_images
+from mineru.model.flash.ofd.constants import MAX_DRAW_PARAM_INHERITANCE
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.path import OfdPathBudget, _segments
from mineru.model.flash.ofd.reading_order import OfdReadingOrderProjector
+from mineru.model.flash.ofd.resources import resolve_draw_param
from mineru.model.flash.ofd.text import FontMetricResolver, OfdTextBudget, build_text_lines
from mineru.parser import MinerUParser
from mineru.parser import api_server
@@ -138,7 +140,7 @@ def test_ofd_cardinal_text_directions_keep_geometry_and_angle() -> None:
content = (
'<ofd:TextObject ID="8" Boundary="20 20 20 50" Font="1" Size="5" '
'ReadDirection="90" CharDirection="90">'
- '<ofd:TextCode X="2" Y="2" DeltaX="g 3 6">竖排文</ofd:TextCode>'
+ '<ofd:TextCode X="2" Y="-5" DeltaX="g 3 6">竖排文</ofd:TextCode>'
"</ofd:TextObject>"
)
_middle, model = doc_analyze(
@@ -183,6 +185,66 @@ def test_ofd_textcode_preserves_boundary_whitespace_and_glyph_positions() -> Non
assert [glyph.origin[0] for glyph in lines[0].glyphs] == pytest.approx([11.0, 16.0, 23.0])
+def test_ofd_textcode_discards_glyphs_outside_object_boundary() -> None:
+ """验证 TextObject Boundary 会裁掉完整位于边界外的字符和空行。"""
+ package_buffer = BytesIO()
+ with ZipFile(package_buffer, "w", ZIP_DEFLATED) as archive:
+ archive.writestr("OFD.xml", "<OFD/>")
+ package = OfdPackage(package_buffer.getvalue())
+ font_metrics = FontMetricResolver(package)
+ common = {
+ "parent_transform": Affine(),
+ "parent_clip": (0.0, 0.0, 100.0, 100.0),
+ "resources": ResourceRegistry(),
+ "package": package,
+ "font_metrics": font_metrics,
+ "budget": OfdTextBudget(),
+ "paint_order": 0,
+ "layer_type": "body",
+ "template_id": None,
+ }
+
+ partial = etree.fromstring(
+ b'<TextObject ID="10" Boundary="0 0 10 10" Size="5"><TextCode X="2" Y="5" DeltaX="20">AB</TextCode></TextObject>'
+ )
+ outside = etree.fromstring(
+ b'<TextObject ID="11" Boundary="0 0 10 10" Size="5"><TextCode X="20" Y="5">X</TextCode></TextObject>'
+ )
+
+ partial_lines = build_text_lines(partial, **common)
+ outside_lines = build_text_lines(outside, **common)
+
+ assert len(partial_lines) == 1
+ assert partial_lines[0].text == "A"
+ assert [glyph.text for glyph in partial_lines[0].glyphs] == ["A"]
+ assert outside_lines == []
+
+
+def test_ofd_draw_param_inheritance_is_ordered_and_bounded() -> None:
+ """验证 DrawParam 保持父到子覆盖顺序,并在继承链超限时受控失败。"""
+ ordered = ResourceRegistry(
+ draw_params={
+ 1: {"ID": "1", "Relative": "2", "LineWidth": "2"},
+ 2: {"ID": "2", "LineWidth": "1", "Color": "red"},
+ }
+ )
+ assert resolve_draw_param(ordered, 1) == {"LineWidth": "2", "Color": "red"}
+
+ chain_length = MAX_DRAW_PARAM_INHERITANCE + 1
+ oversized = ResourceRegistry(
+ draw_params={
+ resource_id: (
+ {"ID": str(resource_id), "Relative": str(resource_id + 1)}
+ if resource_id + 1 < chain_length
+ else {"ID": str(resource_id), "LineWidth": "1"}
+ )
+ for resource_id in range(chain_length)
+ }
+ )
+ with pytest.raises(OfdResourceLimitError, match="max_draw_param_inheritance"):
+ resolve_draw_param(oversized, 0)
+
+
@pytest.mark.parametrize(
("raw_angle", "expected_angle"),
[
diff --git a/tests/unittest/test_pdf_render.py b/tests/unittest/test_pdf_render.py
index 9636b2fe..5cdae468 100644
--- a/tests/unittest/test_pdf_render.py
+++ b/tests/unittest/test_pdf_render.py
@@ -386,6 +386,18 @@ def test_pdf_oversized_image_uses_placeholder_before_pixel_decode(monkeypatch: p
image.load.assert_not_called()
+def test_pdf_oversized_image_bytes_are_rejected_before_pillow(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 PDF 在 Pillow 识别前拒绝超过固定字节预算的图片。"""
+ open_image = MagicMock(side_effect=AssertionError("oversized image must not reach Pillow"))
+ monkeypatch.setattr(pdf_assets, "MAX_IMAGE_PAYLOAD_BYTES", 8)
+ monkeypatch.setattr(pdf_assets.Image, "open", open_image)
+
+ with pytest.raises(pdf_assets.PdfAssetError, match="Image payload exceeds its byte limit"):
+ pdf_assets.prepare_image_bytes(b"oversized")
+
+ open_image.assert_not_called()
+
+
def test_pdf_renders_tables_lists_indices_code_algorithm_and_annotations() -> None:
"""验证原生表格合并、嵌套表、目录、列表、代码算法与说明的组合输出。"""
table = TableBlock.model_validate(