Skip to content

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

fix: handle oversized generated SVG by degrading to PNG and improve resource limit checks

myhloli878de7c4545d
diff --git a/mineru/model/flash/office/image.py b/mineru/model/flash/office/image.py
index f869a10a..2780b75d 100644
--- a/mineru/model/flash/office/image.py
+++ b/mineru/model/flash/office/image.py
@@ -13,7 +13,7 @@ from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
from ....utils.platform import is_windows_environment
from .._shared.image import image_to_b64str
-from .metafile import MetafileError, render_metafile
+from .metafile import MetafileError, MetafileResourceLimitError, render_metafile
VECTOR_IMAGE_FORMATS = frozenset({"WMF", "EMF"})
VECTOR_IMAGE_EXTENSIONS = frozenset({".wmf", ".emf"})
@@ -232,6 +232,18 @@ def _serialize_cross_platform_metafile(
dpi=VECTOR_IMAGE_RENDER_DPI,
size_hint=size_hint,
)
+ except MetafileResourceLimitError as exc:
+ logger.warning(f"Generated {image_format} SVG cannot be consumed safely: {exc}. Falling back to PNG.")
+ try:
+ rendered = render_metafile(
+ image_data,
+ output_format="png",
+ dpi=VECTOR_IMAGE_RENDER_DPI,
+ size_hint=size_hint,
+ )
+ except MetafileError as png_exc:
+ logger.warning(f"Failed to render {image_format} PNG fallback with MinerU: {png_exc}. Using placeholder instead.")
+ return None
except MetafileError as exc:
logger.warning(f"Failed to render {image_format} image with MinerU: {exc}. Using placeholder instead.")
return None
diff --git a/mineru/model/flash/office/metafile/render.py b/mineru/model/flash/office/metafile/render.py
index c36fd05c..a9fcd3e3 100644
--- a/mineru/model/flash/office/metafile/render.py
+++ b/mineru/model/flash/office/metafile/render.py
@@ -11,6 +11,7 @@ from math import ceil, floor, hypot
from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont, UnidentifiedImageError
import pyclipper
+from .....utils.image_payload import MAX_GENERATED_SVG_BYTES
from .font import load_font
from .geometry import FlattenBudget, flatten_path, transform_path
from .limits import MAX_CANVAS_PIXELS, MAX_EMBEDDED_BITMAP_BYTES, MAX_RENDER_WORK_PIXELS
@@ -180,18 +181,15 @@ def _clipper_paths(subpaths: list[tuple[list[Point], bool]]) -> list[list[tuple[
def _paint_polytree(mask: Image.Image, tree: pyclipper.PyPolyNode, budget: FlattenBudget | None = None) -> None:
"""按 PolyTree 层级依次绘制外轮廓、孔洞和孔洞中的岛。"""
draw = ImageDraw.Draw(mask)
-
- def paint(node: pyclipper.PyPolyNode) -> None:
- """递归绘制当前节点的全部子轮廓。"""
- for child in node.Childs:
- if budget is not None:
- budget.charge(len(child.Contour))
- points = [(x / _CLIPPER_SCALE, y / _CLIPPER_SCALE) for x, y in child.Contour]
- if len(points) >= 3:
- draw.polygon(points, fill=0 if child.IsHole else 255)
- paint(child)
-
- paint(tree)
+ stack: list[pyclipper.PyPolyNode] = list(reversed(tree.Childs))
+ while stack:
+ child = stack.pop()
+ if budget is not None:
+ budget.charge(len(child.Contour))
+ points = [(x / _CLIPPER_SCALE, y / _CLIPPER_SCALE) for x, y in child.Contour]
+ if len(points) >= 3:
+ draw.polygon(points, fill=0 if child.IsHole else 255)
+ stack.extend(reversed(child.Childs))
def _path_mask(
@@ -962,11 +960,11 @@ def _svg_requires_raster(document: MetafileDocument) -> bool:
def _svg_fallback_scale(document: MetafileDocument) -> int:
- """为纯矢量 SVG fallback 选择最高 8× 的安全像素密度。"""
+ """为纯矢量 SVG fallback 选择最高 2× 的安全像素密度。"""
if any(isinstance(command, DrawImageCommand) for command in document.commands):
return 1
command_count = max(len(document.commands), 1)
- for factor in (8, 4, 2):
+ for factor in (2,):
width = document.width * factor
height = document.height * factor
if (
@@ -992,9 +990,24 @@ def _svg_fallback_metadata(encoded_png: str) -> str:
return f'<metadata id="mineru-raster-fallback" data-mime="image/png">{encoded_png}</metadata>'
+def _encode_svg_markup(markup: str) -> bytes:
+ """编码 SVG 并保证生成结果不会超过下游安全消费者的字节上限。"""
+ output = markup.encode("utf-8")
+ if len(output) > MAX_GENERATED_SVG_BYTES:
+ raise MetafileResourceLimitError(f"generated SVG exceeds max_generated_svg_bytes={MAX_GENERATED_SVG_BYTES}")
+ return output
+
+
+def _check_svg_size_budget(estimated_bytes: int) -> None:
+ """在继续编码昂贵 SVG element 前执行保守的消费者字节预算。"""
+ if estimated_bytes > MAX_GENERATED_SVG_BYTES:
+ raise MetafileResourceLimitError(f"generated SVG exceeds max_generated_svg_bytes={MAX_GENERATED_SVG_BYTES}")
+
+
def _raster_wrapped_svg(document: MetafileDocument) -> bytes:
"""把 Pillow 结果封装为没有外部引用的单图片 SVG。"""
encoded = base64.b64encode(_png_fallback_bytes(document)).decode("ascii")
+ _check_svg_size_budget(len(encoded) * 2)
markup = (
f'<svg xmlns="http://www.w3.org/2000/svg" width="{document.width}" height="{document.height}" '
f'viewBox="0 0 {document.width} {document.height}" data-mineru-generated="wmf-emf">'
@@ -1002,7 +1015,7 @@ def _raster_wrapped_svg(document: MetafileDocument) -> bytes:
f'<image width="{document.width}" height="{document.height}" href="data:image/png;base64,{encoded}"/>'
"</svg>"
)
- return markup.encode("utf-8")
+ return _encode_svg_markup(markup)
def render_svg(document: MetafileDocument) -> bytes:
@@ -1013,6 +1026,9 @@ def render_svg(document: MetafileDocument) -> bytes:
definitions, clip_ids = _svg_clip_definitions(document, matrix)
fallback_scale = _svg_fallback_scale(document)
fallback = base64.b64encode(_png_fallback_bytes(document, pixel_scale=fallback_scale)).decode("ascii")
+ fallback_metadata = _svg_fallback_metadata(fallback)
+ estimated_bytes = len(fallback_metadata) + 256
+ _check_svg_size_budget(estimated_bytes)
elements: list[str] = []
for command in document.commands:
if isinstance(command, DrawPathCommand):
@@ -1024,13 +1040,15 @@ def render_svg(document: MetafileDocument) -> bytes:
else:
element = _svg_image_element(command, matrix)
elements.append(_wrap_svg_clip(element, command.clip, clip_ids))
+ estimated_bytes += len(elements[-1].encode("utf-8"))
+ _check_svg_size_budget(estimated_bytes)
defs = f"<defs>{''.join(definitions)}</defs>" if definitions else ""
markup = (
f'<svg xmlns="http://www.w3.org/2000/svg" width="{document.width}" height="{document.height}" '
f'viewBox="0 0 {document.width} {document.height}" data-mineru-generated="wmf-emf">'
- f"{_svg_fallback_metadata(fallback)}{defs}{''.join(elements)}</svg>"
+ f"{fallback_metadata}{defs}{''.join(elements)}</svg>"
)
- return markup.encode("utf-8")
+ return _encode_svg_markup(markup)
def encode_document(document: MetafileDocument, output_format: MetafileOutputFormat) -> tuple[bytes, str]:
diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.py
index 624f3471..aeb9f07b 100644
--- a/mineru/utils/image_payload.py
+++ b/mineru/utils/image_payload.py
@@ -12,7 +12,7 @@ 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_GENERATED_SVG_BYTES = 64 * 1024 * 1024
_MAX_GENERATED_SVG_NODES = 100_000
_SAFE_SVG_ATTRIBUTES: dict[str, set[str]] = {
"svg": {"width", "height", "viewBox", "data-mineru-generated"},
@@ -144,7 +144,7 @@ def _validate_generated_svg_attribute(tag: str, name: str, value: str) -> None:
def extract_mineru_generated_svg_fallback(payload: bytes) -> tuple[bytes, int, int]:
"""验证 MinerU 生成 SVG,并返回 PNG fallback 与逻辑像素尺寸。"""
- if not isinstance(payload, bytes) or not payload or len(payload) > _MAX_GENERATED_SVG_BYTES:
+ if not isinstance(payload, bytes) or not payload or len(payload) > MAX_GENERATED_SVG_BYTES:
raise ValueError("Generated SVG payload is empty or exceeds its byte limit")
try:
parser = ElementTree.XMLParser(target=_RejectingSvgTreeBuilder())
diff --git a/tests/unittest/test_flash_office_metafile.py b/tests/unittest/test_flash_office_metafile.py
index 325d02d8..b0cb90a6 100644
--- a/tests/unittest/test_flash_office_metafile.py
+++ b/tests/unittest/test_flash_office_metafile.py
@@ -11,6 +11,7 @@ import zlib
from zipfile import ZIP_DEFLATED, ZipFile
from PIL import Image
+import pyclipper
import pytest
import pptx
@@ -384,6 +385,28 @@ def test_compound_path_masks_preserve_nonzero_and_evenodd_topology() -> None:
assert self_intersecting.getpixel((50, 25)) == 255
+def test_polytree_paint_handles_deep_nesting_without_python_recursion() -> None:
+ """验证恶意深层 PolyTree 使用显式栈绘制且继续计入 flatten 预算。"""
+ root = pyclipper.PyPolyNode()
+ parent = root
+ for index in range(1100):
+ child = pyclipper.PyPolyNode()
+ child.Contour = [
+ (index, index),
+ (2201 - index, index),
+ (2201 - index, 2201 - index),
+ (index, 2201 - index),
+ ]
+ child.IsHole = bool(index & 1)
+ parent.Childs.append(child)
+ parent = child
+ budget = FlattenBudget(limit=5000)
+
+ metafile_render._paint_polytree(Image.new("L", (10, 10)), root, budget)
+
+ assert budget.used == 4400
+
+
def test_clip_mask_reuses_compound_path_topology_and_combine_modes() -> None:
"""验证裁剪 copy/and/or/xor/diff 与路径填充共享同一 winding 结果。"""
outer = _compound_square_path(inner_reversed=False)
@@ -528,18 +551,36 @@ def test_wmf_roundrect_uses_record_parameter_order() -> None:
assert command.path.segments[0].points == ((250.0, 200.0),)
-def test_vector_only_metafile_uses_4x_antialiasing_and_8x_svg_fallback() -> None:
- """验证矢量公式保持逻辑尺寸,同时使用 4× 栅格和 8× DOCX fallback。"""
+def test_vector_only_metafile_uses_4x_antialiasing_and_2x_svg_fallback() -> None:
+ """验证矢量公式保持逻辑尺寸,同时使用 4× 栅格和 2× DOCX fallback。"""
document = metafile_parser.parse_metafile(basic_wmf())
svg = render_metafile(basic_wmf(), output_format="svg").data
fallback, logical_width, logical_height = extract_mineru_generated_svg_fallback(svg)
assert metafile_render._supersample_factor(document) == 4
- assert metafile_render._svg_fallback_scale(document) == 8
+ assert metafile_render._svg_fallback_scale(document) == 2
assert (logical_width, logical_height) == (144, 144)
with Image.open(BytesIO(fallback)) as image:
- assert image.size == (1152, 1152)
- assert image.info["dpi"][0] == pytest.approx(768, abs=1)
+ assert image.size == (288, 288)
+ assert image.info["dpi"][0] == pytest.approx(192, abs=1)
+
+
+def test_oversized_generated_svg_degrades_to_png_for_office_consumers(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证超过消费者上限的内部 SVG 不会进入 HTML/DOCX,而是降级为 PNG。"""
+ data = build_emf([emf_stretch_dib()])
+ image_element = Mock(side_effect=AssertionError("oversized fallback should stop before bitmap SVG encoding"))
+ monkeypatch.setattr(metafile_render, "MAX_GENERATED_SVG_BYTES", 1)
+ monkeypatch.setattr(metafile_render, "_svg_image_element", image_element)
+ monkeypatch.setattr(office_image, "is_windows_environment", lambda: False)
+
+ with pytest.raises(MetafileResourceLimitError, match="max_generated_svg_bytes"):
+ render_metafile(data, output_format="svg")
+
+ data_uri = office_image.serialize_office_image(data, part_name="image.wmf", content_type="image/wmf")
+
+ assert data_uri is not None
+ assert data_uri.startswith("data:image/png;base64,")
+ image_element.assert_not_called()
def test_emfplus_dual_uses_emf_fallback_and_only_is_rejected() -> None:
@@ -666,7 +707,7 @@ def test_officeart_emu_size_controls_standard_wmf_output(monkeypatch: pytest.Mon
assert data_uri is not None
fallback, logical_size, _svg = _svg_data_uri_fallback(data_uri)
assert logical_size == (144, 72)
- assert fallback.size == (1152, 576)
+ assert fallback.size == (288, 144)
def test_officeart_metafile_header_preserves_payload_and_emu_size() -> None:
@@ -792,7 +833,7 @@ def test_legacy_office_models_emit_rendered_wmf_svg(
assert all(image.startswith("data:image/svg+xml;base64,") for image in images)
fallback, logical_size, _svg = _svg_data_uri_fallback(images[0])
assert logical_size == (144, 144)
- assert fallback.size == (1152, 1152)
+ assert fallback.size == (288, 288)
def test_rtf_model_emf_picture_emits_rendered_svg(monkeypatch: pytest.MonkeyPatch) -> None: