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 metafile clipping and text bounds
myhloli6b5efff55c9f
diff --git a/mineru/model/flash/office/metafile/limits.py b/mineru/model/flash/office/metafile/limits.pyindex b145893b..1512ffe5 100644--- a/mineru/model/flash/office/metafile/limits.py+++ b/mineru/model/flash/office/metafile/limits.py@@ -11,6 +11,8 @@ MAX_TOTAL_POINTS: Final = 5_000_000MAX_COMMANDS: Final = 100_000MAX_OBJECTS: Final = 65_536MAX_STATE_DEPTH: Final = 64+MAX_CLIP_OPERATIONS: Final = 64+MAX_TOTAL_CLIP_OPERATIONS: Final = 100_000MAX_DIAGNOSTICS: Final = 256MAX_CANVAS_DIMENSION: Final = 8_192MAX_CANVAS_PIXELS: Final = 16_000_000@@ -22,6 +24,7 @@ MAX_FLATTENED_POINTS: Final = 5_000_000__all__ = ["MAX_CANVAS_DIMENSION","MAX_CANVAS_PIXELS",+ "MAX_CLIP_OPERATIONS","MAX_COMMANDS","MAX_DIAGNOSTICS","MAX_EMBEDDED_BITMAP_BYTES",@@ -33,4 +36,5 @@ __all__ = ["MAX_RENDER_WORK_PIXELS","MAX_STATE_DEPTH","MAX_TOTAL_POINTS",+ "MAX_TOTAL_CLIP_OPERATIONS",]diff --git a/mineru/model/flash/office/metafile/parser.py b/mineru/model/flash/office/metafile/parser.pyindex f8c85a15..33fb7d4e 100644--- a/mineru/model/flash/office/metafile/parser.py+++ b/mineru/model/flash/office/metafile/parser.py@@ -25,6 +25,7 @@ from .geometry import (from .limits import (MAX_CANVAS_DIMENSION,MAX_CANVAS_PIXELS,+ MAX_CLIP_OPERATIONS,MAX_COMMANDS,MAX_DIAGNOSTICS,MAX_EMBEDDED_BITMAP_BYTES,@@ -33,6 +34,7 @@ from .limits import (MAX_POINTS_PER_RECORD,MAX_RECORDS,MAX_STATE_DEPTH,+ MAX_TOTAL_CLIP_OPERATIONS,MAX_TOTAL_POINTS,)from .models import (@@ -170,6 +172,7 @@ class _Playback:self.path_ready = Falseself.partial = Falseself.total_points = 0+ self.total_clip_operations = 0self.record_type: int | None = Noneself.record_index: int | None = Noneself.record_offset: int | None = None@@ -204,6 +207,9 @@ class _Playback:"""在命令预算内追加一条统一绘图命令。"""if len(self.commands) >= MAX_COMMANDS:raise MetafileResourceLimitError(f"metafile exceeds max_commands={MAX_COMMANDS}")+ self.total_clip_operations += len(command.clip)+ if self.total_clip_operations > MAX_TOTAL_CLIP_OPERATIONS:+ raise MetafileResourceLimitError(f"metafile exceeds max_total_clip_operations={MAX_TOTAL_CLIP_OPERATIONS}")self.commands.append(command)def copy_state(self) -> GdiState:@@ -448,7 +454,13 @@ class _Playback:if mode == _RGN_COPY:self.state.clip = (operation,)else:- self.state.clip = (*self.state.clip, operation)+ self.state.clip = self.clip_with_operation(operation)++ def clip_with_operation(self, operation: ClipOperation) -> tuple[ClipOperation, ...]:+ """在固定 clip 深度预算内返回追加单次操作后的不可变栈。"""+ if len(self.state.clip) >= MAX_CLIP_OPERATIONS:+ raise MetafileResourceLimitError(f"metafile exceeds max_clip_operations={MAX_CLIP_OPERATIONS}")+ return (*self.state.clip, operation)def reset_clip(self) -> None:"""恢复为没有额外裁剪区域的初始状态。"""@@ -571,6 +583,15 @@ def _stock_object(index: int) -> Pen | Brush | Font | None:return None+def _horizontal_text_align_factor(text_align: int) -> float:+ """返回 LEFT/CENTER/RIGHT 文本 bounds 相对 origin 的左移比例。"""+ if text_align & _TA_CENTER == _TA_CENTER:+ return 0.5+ if text_align & _TA_RIGHT:+ return 1.0+ return 0.0++def _commands_bounds(commands: list[DrawCommand]) -> Rect | None:"""计算全部绘图命令的保守可见包围盒。"""rectangles: list[Rect | None] = []@@ -582,11 +603,15 @@ def _commands_bounds(commands: list[DrawCommand]) -> Rect | None:rectangles.append(command.bounds)else:estimated_width = max(command.font_height * 0.6 * len(command.text), command.font_height)+ if command.advance_end is not None:+ estimated_width = max(estimated_width, abs(command.advance_end[0] - command.origin[0]))+ align_factor = _horizontal_text_align_factor(command.text_align)+ left = command.origin[0] - estimated_width * align_factorrectangles.append(Rect(- command.origin[0],+ left,command.origin[1] - command.font_height,- command.origin[0] + estimated_width,+ left + estimated_width,command.origin[1] + command.font_height * 0.25,))@@ -1026,7 +1051,7 @@ def _emit_text()clip = playback.state.clipif mapped_bounds is not None and options & _ETO_CLIPPED:- clip = (*clip, ClipOperation(rectangle_path(mapped_bounds), "and"))+ clip = playback.clip_with_operation(ClipOperation(rectangle_path(mapped_bounds), "and"))playback.append_command(DrawTextCommand(text=text,diff --git a/mineru/model/flash/office/metafile/render.py b/mineru/model/flash/office/metafile/render.pyindex c4cff98d..146af63b 100644--- a/mineru/model/flash/office/metafile/render.py+++ b/mineru/model/flash/office/metafile/render.py@@ -794,7 +794,7 @@ def _supersample_factor(document: MetafileDocument) -> int:"""在画布、工作量预算内为纯矢量文档选择 1×、2× 或 4×。"""if any(isinstance(command, DrawImageCommand) for command in document.commands):return 1- command_count = max(len(document.commands), 1)+ work_units = _render_work_units(document)for factor in (4, 2):width = document.width * factorheight = document.height * factor@@ -802,17 +802,22 @@ def _supersample_factor(document: MetafileDocument) -> int:width <= 8192and height <= 8192and width * height <= MAX_CANVAS_PIXELS- and width * height * command_count <= MAX_RENDER_WORK_PIXELS+ and width * height * work_units <= MAX_RENDER_WORK_PIXELS):return factorreturn 1+def _render_work_units(document: MetafileDocument) -> int:+ """按绘图命令及其逐项 clip mask 合成次数计算渲染工作单元。"""+ return max(sum(1 + len(command.clip) for command in document.commands), 1)++def _render_pillow_once(document: MetafileDocument, raster_scale: int) -> Image.Image:"""按给定整数倍率执行一次不缩放的 Pillow 栅格化。"""width = document.width * raster_scaleheight = document.height * raster_scale- render_work = width * height * max(len(document.commands), 1)+ render_work = width * height * _render_work_units(document)if render_work > MAX_RENDER_WORK_PIXELS:raise MetafileResourceLimitError(f"metafile exceeds max_render_work_pixels={MAX_RENDER_WORK_PIXELS}")matrix = _document_matrix(document, raster_scale=raster_scale)diff --git a/tests/unittest/_metafile_test_utils.py b/tests/unittest/_metafile_test_utils.pyindex ac1986c8..491dbd17 100644--- a/tests/unittest/_metafile_test_utils.py+++ b/tests/unittest/_metafile_test_utils.py@@ -96,6 +96,11 @@ def emf_line_to(x: int, y: int) -> bytes:return emf_record(54, struct.pack("<2i", x, y))+def emf_intersect_clip_rect(left: int, top: int, right: int, bottom: int) -> bytes:+ """构造 EMR_INTERSECTCLIPRECT。"""+ return emf_record(30, struct.pack("<4i", left, top, right, bottom))++def emf_angle_arc(center_x: int, center_y: int, radius: int, start_angle: float, sweep_angle: float) -> bytes:"""构造 EMR_ANGLEARC。"""return emf_record(41, struct.pack("<iiIff", center_x, center_y, radius, start_angle, sweep_angle))@@ -260,6 +265,16 @@ def wmf_set_text_align(value: int) -> bytes:return wmf_record(0x012E, struct.pack("<H", value))+def wmf_set_map_mode(value: int) -> bytes:+ """构造 META_SETMAPMODE。"""+ return wmf_record(0x0103, struct.pack("<h", value))+++def wmf_rectangle(left: int, top: int, right: int, bottom: int) -> bytes:+ """构造 META_RECTANGLE。"""+ return wmf_record(0x041B, struct.pack("<hhhh", bottom, right, top, left))++def wmf_textout(text: str, x: int, y: int) -> bytes:"""构造没有显式字符 spacing 的 META_TEXTOUT。"""encoded = text.encode("cp1252")@@ -311,6 +326,7 @@ __all__ = ["emf_end_path","emf_fill_path","emf_font",+ "emf_intersect_clip_rect","emf_line_to","emf_move_to","emf_polybezier",@@ -330,7 +346,9 @@ __all__ = ["emf_text","emfplus_comment","wmf_move_to",+ "wmf_rectangle","wmf_record",+ "wmf_set_map_mode","wmf_set_text_align","wmf_textout",]diff --git a/tests/unittest/test_flash_office_metafile.py b/tests/unittest/test_flash_office_metafile.pyindex 81ad6e17..0f9b0b55 100644--- a/tests/unittest/test_flash_office_metafile.py+++ b/tests/unittest/test_flash_office_metafile.py@@ -64,6 +64,7 @@ from _metafile_test_utils import (emf_create_pen,emf_end_path,emf_font,+ emf_intersect_clip_rect,emf_line_to,emf_move_to,emf_polybezier,@@ -82,7 +83,9 @@ from _metafile_test_utils import (emf_text,emfplus_comment,wmf_move_to,+ wmf_rectangle,wmf_record,+ wmf_set_map_mode,wmf_set_text_align,wmf_textout,)@@ -645,6 +648,38 @@ def test_wmf_roundrect_uses_record_parameter_order() -> None:assert command.path.segments[0].points == ((250.0, 200.0),)[email protected]("text_align", [2, 6], ids=["right", "center"])+def test_standard_wmf_fallback_bounds_include_aligned_text(text_align: int) -> None:+ """验证无 placeable header 时 CENTER/RIGHT 文本 bounds 不会从 origin 单向向右估算。"""+ standard_wmf = build_placeable_wmf([wmf_set_text_align(text_align), wmf_textout("AB", 100, 50)])[22:]++ document = metafile_parser.parse_metafile(standard_wmf)++ assert document.bounds.left < 100.0+ if text_align == 2:+ assert document.bounds.right == pytest.approx(100.0)+ else:+ assert (document.bounds.left + document.bounds.right) / 2.0 == pytest.approx(100.0)+++ ("map_mode", "millimeters_per_unit"),+ [(2, 0.1), (3, 0.01), (4, 0.254), (5, 0.0254), (6, 25.4 / 1440.0)],+ ids=["lometric", "himetric", "loenglish", "hienglish", "twips"],+)+def test_fixed_wmf_map_modes_use_documented_physical_units(map_mode: int, millimeters_per_unit: float) -> None:+ """验证固定 map mode 已按 Windows 定义的毫米或英寸单位换算,防止误改 2.54 倍。"""+ data = build_placeable_wmf([wmf_set_map_mode(map_mode), wmf_rectangle(0, 0, 100, 100)])+ document = metafile_parser.parse_metafile(data, dpi=144)+ command = next(command for command in document.commands if isinstance(command, DrawPathCommand))+ bounds = path_bounds(command.path)++ assert bounds is not None+ expected = 100 * millimeters_per_unit * (144 / 25.4)+ assert abs(bounds.width) == pytest.approx(expected)+ assert abs(bounds.height) == pytest.approx(expected)++def test_vector_only_metafile_uses_4x_antialiasing_and_2x_svg_fallback() -> None:"""验证矢量公式保持逻辑尺寸,同时使用 4× 栅格和 2× DOCX fallback。"""document = metafile_parser.parse_metafile(basic_wmf())@@ -747,6 +782,22 @@ def test_fixed_record_point_and_state_limits_are_enforced(monkeypatch: pytest.Morender_metafile(build_emf([emf_rectangle(1, 1, 10, 10)]))+def test_clip_stack_and_render_work_use_fixed_budgets(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证累计 clip 操作受深度限制,渲染预算也计入逐项 mask 合成工作。"""+ clip = emf_intersect_clip_rect(0, 0, 100, 100)+ monkeypatch.setattr(metafile_parser, "MAX_CLIP_OPERATIONS", 2)+ with pytest.raises(MetafileResourceLimitError, match="max_clip_operations=2"):+ metafile_parser.parse_metafile(build_emf([clip, clip, clip, emf_rectangle(1, 1, 10, 10)]))++ monkeypatch.setattr(metafile_parser, "MAX_CLIP_OPERATIONS", 64)+ monkeypatch.setattr(metafile_parser, "MAX_TOTAL_CLIP_OPERATIONS", 1)+ with pytest.raises(MetafileResourceLimitError, match="max_total_clip_operations=1"):+ metafile_parser.parse_metafile(build_emf([clip, emf_rectangle(1, 1, 10, 10), emf_rectangle(20, 20, 30, 30)]))++ document = metafile_parser.parse_metafile(build_emf([clip, emf_rectangle(1, 1, 10, 10)]))+ assert metafile_render._render_work_units(document) == 2++def test_svg_text_escapes_markup_characters() -> None:"""验证 EMF 文字无法把脚本或 XML 标签注入 SVG。"""data = build_emf([emf_font(1), emf_select_object(1), emf_text("<script>&", 5, 30)])