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
Extract metafile rendering into standalone dependency
myhlolie1505ebca005
diff --git a/mineru/model/flash/office/image.py b/mineru/model/flash/office/image.pyindex 2780b75d..0fd119b1 100644--- a/mineru/model/flash/office/image.py+++ b/mineru/model/flash/office/image.py@@ -2,18 +2,18 @@"""Flash Office 文档的图片识别、转码与占位图生成。"""import base64+import structfrom functools import lru_cachefrom io import BytesIOfrom pathlib import PurePosixPath-import structfrom typing import Finalfrom loguru import logger+from metafile_render import MetafileError, MetafileResourceLimitError, render_metafilefrom PIL import Image, ImageDraw, ImageFont, UnidentifiedImageErrorfrom ....utils.platform import is_windows_environmentfrom .._shared.image import image_to_b64str-from .metafile import MetafileError, MetafileResourceLimitError, render_metafileVECTOR_IMAGE_FORMATS = frozenset({"WMF", "EMF"})VECTOR_IMAGE_EXTENSIONS = frozenset({".wmf", ".emf"})@@ -203,7 +203,7 @@ def _serialize_native_metafile(image_data: bytes, image_format: str) -> str | Nopil_image.load(dpi=VECTOR_IMAGE_RENDER_DPI)return image_to_b64str(pil_image, image_format="PNG")except PIL_IMAGE_LOAD_ERRORS as exc:- logger.warning(f"Native Windows rendering failed for {image_format}: {exc}. Falling back to MinerU renderer.")+ logger.warning(f"Native Windows rendering failed for {image_format}: {exc}.")return None@@ -224,7 +224,7 @@ def _serialize_cross_platform_metafile(*,size_hint: tuple[int, int] | None = None,) -> str | None:- """调用 MinerU 内部 WMF/EMF 引擎并生成带 PNG fallback 的 SVG。"""+ """调用 metafile-render WMF/EMF 引擎并生成带 PNG fallback 的 SVG。"""try:rendered = render_metafile(image_data,@@ -242,15 +242,17 @@ def _serialize_cross_platform_metafile(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.")+ logger.warning(+ f"Failed to render {image_format} PNG fallback with metafile-render: {png_exc}. Using placeholder instead."+ )return Noneexcept MetafileError as exc:- logger.warning(f"Failed to render {image_format} image with MinerU: {exc}. Using placeholder instead.")+ logger.warning(f"Failed to render {image_format} image with metafile-render: {exc}. Using placeholder instead.")return Noneif rendered.partial:diagnostic_codes = sorted({diagnostic.code for diagnostic in rendered.diagnostics})logger.warning(- f"Rendered partial {image_format} image with MinerU, diagnostics={diagnostic_codes[:16]}, "+ f"Rendered partial {image_format} image with metafile-render, diagnostics={diagnostic_codes[:16]}, "f"size={rendered.width}x{rendered.height}")encoded = base64.b64encode(rendered.data).decode("ascii")diff --git a/mineru/model/flash/office/metafile/__init__.py b/mineru/model/flash/office/metafile/__init__.pydeleted file mode 100644index ff233b68..00000000--- a/mineru/model/flash/office/metafile/__init__.py+++ /dev/null@@ -1,22 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""Office WMF/EMF 的跨平台内部渲染能力。"""--from .api import render_metafile-from .models import (- MetafileDiagnostic,- MetafileError,- MetafileMalformedError,- MetafileRenderResult,- MetafileResourceLimitError,- MetafileUnsupportedError,-)--__all__ = [- "MetafileDiagnostic",- "MetafileError",- "MetafileMalformedError",- "MetafileRenderResult",- "MetafileResourceLimitError",- "MetafileUnsupportedError",- "render_metafile",-]diff --git a/mineru/model/flash/office/metafile/api.py b/mineru/model/flash/office/metafile/api.pydeleted file mode 100644index 87078cb7..00000000--- a/mineru/model/flash/office/metafile/api.py+++ /dev/null@@ -1,36 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""WMF/EMF 内部渲染入口。"""--from __future__ import annotations--from .models import MetafileOutputFormat, MetafileRenderResult-from .parser import parse_metafile-from .render import encode_document---def render_metafile(- data: bytes,- *,- output_format: MetafileOutputFormat = "png",- dpi: int = 144,- size_hint: tuple[int, int] | None = None,-) -> MetafileRenderResult:- """把 WMF/EMF 字节渲染为 PNG、JPEG 或安全 SVG。"""- if output_format not in {"png", "jpeg", "svg"}:- raise ValueError(f"unsupported metafile output format: {output_format}")- document = parse_metafile(data, dpi=dpi, size_hint=size_hint)- output, media_type = encode_document(document, output_format)- return MetafileRenderResult(- data=output,- output_format=output_format,- media_type=media_type,- width=document.width,- height=document.height,- source_format=document.source_format,- emfplus_mode=document.emfplus_mode,- partial=document.partial,- diagnostics=document.diagnostics,- )---__all__ = ["render_metafile"]diff --git a/mineru/model/flash/office/metafile/binary.py b/mineru/model/flash/office/metafile/binary.pydeleted file mode 100644index 42876dc5..00000000--- a/mineru/model/flash/office/metafile/binary.py+++ /dev/null@@ -1,76 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""WMF/EMF 使用的严格有界二进制读取器。"""--from __future__ import annotations--import struct--from .models import MetafileMalformedError---class BoundedReader:- """在固定 memoryview 边界内读取小端标量和切片。"""-- def __init__(self, data: bytes | memoryview, *, base_offset: int = 0) -> None:- """保存输入视图与用于诊断的绝对起始偏移。"""- self.data = memoryview(data)- self.base_offset = base_offset-- def _require(self, offset: int, size: int) -> None:- """验证读取范围,不允许负数或越过当前视图。"""- if offset < 0 or size < 0 or offset > len(self.data) - size:- raise MetafileMalformedError(- f"metafile field exceeds record boundary: offset={self.base_offset + offset}, size={size}"- )-- def u8(self, offset: int) -> int:- """读取小端无符号 8 位整数。"""- self._require(offset, 1)- return int(self.data[offset])-- def i16(self, offset: int) -> int:- """读取小端有符号 16 位整数。"""- self._require(offset, 2)- return int(struct.unpack_from("<h", self.data, offset)[0])-- def u16(self, offset: int) -> int:- """读取小端无符号 16 位整数。"""- self._require(offset, 2)- return int(struct.unpack_from("<H", self.data, offset)[0])-- def i32(self, offset: int) -> int:- """读取小端有符号 32 位整数。"""- self._require(offset, 4)- return int(struct.unpack_from("<i", self.data, offset)[0])-- def u32(self, offset: int) -> int:- """读取小端无符号 32 位整数。"""- self._require(offset, 4)- return int(struct.unpack_from("<I", self.data, offset)[0])-- def f32(self, offset: int) -> float:- """读取小端 IEEE-754 单精度浮点数。"""- self._require(offset, 4)- return float(struct.unpack_from("<f", self.data, offset)[0])-- def bytes(self, offset: int, size: int) -> bytes:- """返回经过边界校验的不可变字节切片。"""- self._require(offset, size)- return self.data[offset : offset + size].tobytes()-- def subreader(self, offset: int, size: int) -> BoundedReader:- """返回继承绝对偏移信息的有界子读取器。"""- self._require(offset, size)- return BoundedReader(self.data[offset : offset + size], base_offset=self.base_offset + offset)-- def remaining(self, offset: int) -> int:- """返回从指定位置到当前视图末尾的剩余字节数。"""- self._require(offset, 0)- return len(self.data) - offset-- def __len__(self) -> int:- """返回当前视图的总字节数。"""- return len(self.data)---__all__ = ["BoundedReader"]diff --git a/mineru/model/flash/office/metafile/font.py b/mineru/model/flash/office/metafile/font.pydeleted file mode 100644index 78a014d2..00000000--- a/mineru/model/flash/office/metafile/font.py+++ /dev/null@@ -1,111 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""WMF/EMF parser 与 renderer 共享的跨平台字体解析和度量。"""--from __future__ import annotations--from functools import lru_cache-from pathlib import Path-import platform--from PIL import ImageFont--from .models import Font---def _font_search_roots() -> tuple[Path, ...]:- """返回当前平台常见字体目录,不在模块导入时访问文件系统。"""- system = platform.system()- roots: list[Path] = []- if system == "Darwin":- roots.extend((Path("/System/Library/Fonts"), Path("/Library/Fonts"), Path.home() / "Library/Fonts"))- elif system == "Windows":- import os-- windows_dir = Path(os.environ.get("WINDIR", "C:/Windows"))- roots.append(windows_dir / "Fonts")- else:- roots.extend(- (- Path("/usr/share/fonts"),- Path("/usr/local/share/fonts"),- Path.home() / ".fonts",- Path.home() / ".local/share/fonts",- )- )- return tuple(root for root in roots if root.is_dir())---@lru_cache(maxsize=1)-def _font_file_index() -> dict[str, str]:- """惰性建立字体文件名索引,避免 import 时扫描系统目录。"""- index: dict[str, str] = {}- for root in _font_search_roots():- try:- candidates = root.rglob("*")- for candidate in candidates:- if candidate.suffix.lower() not in {".ttf", ".ttc", ".otf"}:- continue- index.setdefault(candidate.stem.casefold().replace(" ", ""), str(candidate))- except OSError:- continue- return index---def _font_aliases(face_name: str, charset: int) -> tuple[str, ...]:- """返回 Windows 字体名在 Linux/macOS 上的固定替代顺序。"""- normalized = face_name.casefold().replace(" ", "")- alias_map = {- "arial": ("Arial", "LiberationSans-Regular", "DejaVuSans"),- "calibri": ("Calibri", "Carlito-Regular", "Arial", "DejaVuSans"),- "cambria": ("Cambria", "Caladea-Regular", "DejaVuSerif"),- "timesnewroman": ("Times New Roman", "LiberationSerif-Regular", "DejaVuSerif"),- "couriernew": ("Courier New", "LiberationMono-Regular", "DejaVuSansMono"),- "simsun": ("SimSun", "Songti SC", "NotoSerifCJKsc-Regular", "DejaVuSans"),- "microsoftyahei": ("Microsoft YaHei", "PingFang SC", "NotoSansCJKsc-Regular", "DejaVuSans"),- }- aliases = alias_map.get(normalized, (face_name,))- if charset in {128, 129, 134, 136}:- aliases = (*aliases, "PingFang SC", "NotoSansCJKsc-Regular", "NotoSansCJK-Regular", "DejaVuSans")- return tuple(dict.fromkeys((*aliases, "DejaVuSans")))---@lru_cache(maxsize=256)-def load_font(- face_name: str,- size: int,- weight: int,- italic: bool,- charset: int,-) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:- """按字体名、别名和文件索引加载 Pillow 字体。"""- normalized_size = max(1, min(size, 4096))- index = _font_file_index()- for alias in _font_aliases(face_name, charset):- keys = [alias.casefold().replace(" ", "")]- if weight >= 700:- keys.insert(0, f"{keys[0]}bold")- if italic:- keys.insert(0, f"{keys[0]}italic")- candidates = [alias, f"{alias}.ttf", *(index[key] for key in keys if key in index)]- for candidate in candidates:- try:- return ImageFont.truetype(candidate, normalized_size)- except OSError:- continue- return ImageFont.load_default(size=normalized_size)---def measure_text_advance(font: Font, text: str) -> float:- """用 renderer 同款字体回退规则估算无显式 spacing 的逻辑 advance。"""- if not text:- return 0.0- font_size = max(1, round(abs(font.height or -12.0)))- loaded = load_font(font.face_name, font_size, font.weight, font.italic, font.charset)- advance = float(loaded.getlength(text))- if font.width:- natural_width = max(float(loaded.getlength("0")), 1e-9)- advance *= abs(font.width) / natural_width- return max(advance, 0.0)---__all__ = ["load_font", "measure_text_advance"]diff --git a/mineru/model/flash/office/metafile/geometry.py b/mineru/model/flash/office/metafile/geometry.pydeleted file mode 100644index df97e501..00000000--- a/mineru/model/flash/office/metafile/geometry.py+++ /dev/null@@ -1,409 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""WMF/EMF 跨后端复用的路径与几何计算。"""--from __future__ import annotations--from dataclasses import dataclass-from math import atan2, ceil, cos, hypot, pi, sin-from typing import Iterable--from .limits import MAX_FLATTENED_POINTS-from .models import GraphicsPath, Matrix, MetafileResourceLimitError, PathSegment, Point, Rect---_ELLIPSE_KAPPA = 0.5522847498307936-_DEFAULT_FLATNESS = 0.25-_MAX_CUBIC_DEPTH = 12---@dataclass(slots=True)-class FlattenBudget:- """累计单次文档渲染产生的折线点数并执行固定预算。"""-- limit: int = MAX_FLATTENED_POINTS- used: int = 0-- def charge(self, count: int = 1) -> None:- """累计离散点数,超过固定预算时终止渲染。"""- self.used += count- if self.used > self.limit:- raise MetafileResourceLimitError(f"metafile exceeds max_flattened_points={self.limit}")---class PathBuilder:- """以可变列表构造最终不可变的 GraphicsPath。"""-- def __init__(self) -> None:- """创建空路径并清除当前点与子路径起点。"""- self._segments: list[PathSegment] = []- self.current: Point | None = None- self.subpath_start: Point | None = None- self._figure_closed = False-- def move_to(self, point: Point) -> None:- """移动当前点并开始新的子路径。"""- self._segments.append(PathSegment("M", (point,)))- self.current = point- self.subpath_start = point- self._figure_closed = False-- def line_to(self, point: Point) -> None:- """从当前点追加直线;空路径会先建立起点。"""- if self.current is None:- self.move_to(point)- return- if self._figure_closed:- self.move_to(self.current)- self._segments.append(PathSegment("L", (point,)))- self.current = point-- def cubic_to(self, control1: Point, control2: Point, endpoint: Point) -> None:- """从当前点追加三次贝塞尔曲线。"""- if self.current is None:- self.move_to(endpoint)- return- if self._figure_closed:- self.move_to(self.current)- self._segments.append(PathSegment("C", (control1, control2, endpoint)))- self.current = endpoint-- def close(self) -> None:- """闭合当前子路径并把当前点恢复到其起点。"""- if self.current is None or self.subpath_start is None or self._figure_closed:- return- self._segments.append(PathSegment("Z"))- self.current = self.subpath_start- self._figure_closed = True-- @property- def figure_open(self) -> bool:- """返回当前是否存在可由 CloseFigure 闭合的开放 figure。"""- return self.current is not None and self.subpath_start is not None and not self._figure_closed-- def extend(self, path: GraphicsPath) -> None:- """按顺序追加另一条路径的全部片段。"""- for segment in path.segments:- if segment.verb == "M":- self.move_to(segment.points[0])- elif segment.verb == "L":- self.line_to(segment.points[0])- elif segment.verb == "C":- self.cubic_to(*segment.points)- elif segment.verb == "Z":- self.close()-- def build(self) -> GraphicsPath:- """冻结并返回当前路径片段。"""- return GraphicsPath(tuple(self._segments))-- def clear(self) -> None:- """清空全部路径片段与当前点。"""- self._segments.clear()- self.current = None- self.subpath_start = None- self._figure_closed = False---def colorref_to_rgb(value: int) -> tuple[int, int, int]:- """把 GDI COLORREF 的 BGR 字节序转换为 RGB。"""- return value & 0xFF, (value >> 8) & 0xFF, (value >> 16) & 0xFF---def transform_path(path: GraphicsPath, matrix: Matrix) -> GraphicsPath:- """把路径中的所有控制点应用到同一仿射变换。"""- segments: list[PathSegment] = []- for segment in path.segments:- segments.append(PathSegment(segment.verb, tuple(matrix.transform_point(point) for point in segment.points)))- return GraphicsPath(tuple(segments))---def rectangle_path(rect: Rect) -> GraphicsPath:- """把矩形转换为闭合路径。"""- normalized = rect.normalized()- builder = PathBuilder()- builder.move_to((normalized.left, normalized.top))- builder.line_to((normalized.right, normalized.top))- builder.line_to((normalized.right, normalized.bottom))- builder.line_to((normalized.left, normalized.bottom))- builder.close()- return builder.build()---def round_rectangle_path(rect: Rect, radius_x: float, radius_y: float) -> GraphicsPath:- """把圆角矩形转换为包含三次曲线的闭合路径。"""- normalized = rect.normalized()- radius_x = min(abs(radius_x), abs(normalized.width) / 2.0)- radius_y = min(abs(radius_y), abs(normalized.height) / 2.0)- if radius_x <= 0.0 or radius_y <= 0.0:- return rectangle_path(normalized)- kx = radius_x * _ELLIPSE_KAPPA- ky = radius_y * _ELLIPSE_KAPPA- left, top, right, bottom = normalized.left, normalized.top, normalized.right, normalized.bottom- builder = PathBuilder()- builder.move_to((left + radius_x, top))- builder.line_to((right - radius_x, top))- builder.cubic_to((right - radius_x + kx, top), (right, top + radius_y - ky), (right, top + radius_y))- builder.line_to((right, bottom - radius_y))- builder.cubic_to((right, bottom - radius_y + ky), (right - radius_x + kx, bottom), (right - radius_x, bottom))- builder.line_to((left + radius_x, bottom))- builder.cubic_to((left + radius_x - kx, bottom), (left, bottom - radius_y + ky), (left, bottom - radius_y))- builder.line_to((left, top + radius_y))- builder.cubic_to((left, top + radius_y - ky), (left + radius_x - kx, top), (left + radius_x, top))- builder.close()- return builder.build()---def ellipse_path(rect: Rect) -> GraphicsPath:- """把椭圆转换为四段三次贝塞尔曲线。"""- normalized = rect.normalized()- center_x = (normalized.left + normalized.right) / 2.0- center_y = (normalized.top + normalized.bottom) / 2.0- radius_x = normalized.width / 2.0- radius_y = normalized.height / 2.0- if radius_x <= 0.0 or radius_y <= 0.0:- return GraphicsPath(())- kx = radius_x * _ELLIPSE_KAPPA- ky = radius_y * _ELLIPSE_KAPPA- builder = PathBuilder()- builder.move_to((center_x + radius_x, center_y))- builder.cubic_to(- (center_x + radius_x, center_y + ky),- (center_x + kx, center_y + radius_y),- (center_x, center_y + radius_y),- )- builder.cubic_to(- (center_x - kx, center_y + radius_y),- (center_x - radius_x, center_y + ky),- (center_x - radius_x, center_y),- )- builder.cubic_to(- (center_x - radius_x, center_y - ky),- (center_x - kx, center_y - radius_y),- (center_x, center_y - radius_y),- )- builder.cubic_to(- (center_x + kx, center_y - radius_y),- (center_x + radius_x, center_y - ky),- (center_x + radius_x, center_y),- )- builder.close()- return builder.build()---def arc_path(- rect: Rect,- start: Point,- end: Point,- *,- direction: int,- close_mode: str = "open",-) -> GraphicsPath:- """按 GDI 椭圆边界与方向生成 arc、pie 或 chord 路径。"""- normalized = rect.normalized()- center_x = (normalized.left + normalized.right) / 2.0- center_y = (normalized.top + normalized.bottom) / 2.0- radius_x = normalized.width / 2.0- radius_y = normalized.height / 2.0- if radius_x <= 0.0 or radius_y <= 0.0:- return GraphicsPath(())- start_angle = atan2((start[1] - center_y) / radius_y, (start[0] - center_x) / radius_x)- end_angle = atan2((end[1] - center_y) / radius_y, (end[0] - center_x) / radius_x)- if direction == 1:- while end_angle >= start_angle:- end_angle -= 2.0 * pi- else:- while end_angle <= start_angle:- end_angle += 2.0 * pi- sweep = end_angle - start_angle- steps = max(4, min(256, int(ceil(abs(sweep) / (pi / 24.0)))))- points = [- (- center_x + radius_x * cos(start_angle + sweep * index / steps),- center_y + radius_y * sin(start_angle + sweep * index / steps),- )- for index in range(steps + 1)- ]- builder = PathBuilder()- if close_mode == "pie":- builder.move_to((center_x, center_y))- builder.line_to(points[0])- else:- builder.move_to(points[0])- for point in points[1:]:- builder.line_to(point)- if close_mode in {"pie", "chord"}:- builder.close()- return builder.build()---def path_bounds(path: GraphicsPath) -> Rect | None:- """返回包含路径全部端点和控制点的保守包围盒。"""- points = [point for segment in path.segments for point in segment.points]- if not points:- return None- xs = [point[0] for point in points]- ys = [point[1] for point in points]- return Rect(min(xs), min(ys), max(xs), max(ys))---def close_open_subpaths(path: GraphicsPath) -> GraphicsPath:- """为 StrokeAndFillPath 显式闭合路径中的全部开放 figure。"""- segments: list[PathSegment] = []- figure_open = False- for segment in path.segments:- if segment.verb == "M":- if figure_open:- segments.append(PathSegment("Z"))- figure_open = True- elif segment.verb == "Z":- figure_open = False- segments.append(segment)- if figure_open:- segments.append(PathSegment("Z"))- return GraphicsPath(tuple(segments))---def union_rectangles(rectangles: Iterable[Rect | None]) -> Rect | None:- """合并所有非空矩形并返回整体包围盒。"""- present = [rectangle.normalized() for rectangle in rectangles if rectangle is not None]- if not present:- return None- return Rect(- min(rectangle.left for rectangle in present),- min(rectangle.top for rectangle in present),- max(rectangle.right for rectangle in present),- max(rectangle.bottom for rectangle in present),- )---def _point_line_distance(point: Point, start: Point, end: Point) -> float:- """返回点到无限直线的距离,退化直线按点距处理。"""- delta_x = end[0] - start[0]- delta_y = end[1] - start[1]- length = hypot(delta_x, delta_y)- if length <= 1e-12:- return hypot(point[0] - start[0], point[1] - start[1])- return abs(delta_y * point[0] - delta_x * point[1] + end[0] * start[1] - end[1] * start[0]) / length---def _split_cubic(- start: Point,- control1: Point,- control2: Point,- endpoint: Point,-) -> tuple[tuple[Point, ...], tuple[Point, ...]]:- """按 de Casteljau 中点算法把三次贝塞尔曲线二分。"""- first = ((start[0] + control1[0]) / 2.0, (start[1] + control1[1]) / 2.0)- second = ((control1[0] + control2[0]) / 2.0, (control1[1] + control2[1]) / 2.0)- third = ((control2[0] + endpoint[0]) / 2.0, (control2[1] + endpoint[1]) / 2.0)- fourth = ((first[0] + second[0]) / 2.0, (first[1] + second[1]) / 2.0)- fifth = ((second[0] + third[0]) / 2.0, (second[1] + third[1]) / 2.0)- midpoint = ((fourth[0] + fifth[0]) / 2.0, (fourth[1] + fifth[1]) / 2.0)- return (start, first, fourth, midpoint), (midpoint, fifth, third, endpoint)---def _flatten_cubic(- start: Point,- control1: Point,- control2: Point,- endpoint: Point,- *,- flatness: float,- max_depth: int,- budget: FlattenBudget,-) -> list[Point]:- """按输出空间误差自适应离散单条三次贝塞尔曲线。"""- result: list[Point] = []- stack: list[tuple[Point, Point, Point, Point, int]] = [(start, control1, control2, endpoint, 0)]- while stack:- current_start, current_control1, current_control2, current_endpoint, depth = stack.pop()- error = max(- _point_line_distance(current_control1, current_start, current_endpoint),- _point_line_distance(current_control2, current_start, current_endpoint),- )- if error <= flatness or depth >= max_depth:- budget.charge()- result.append(current_endpoint)- continue- left, right = _split_cubic(current_start, current_control1, current_control2, current_endpoint)- stack.append((*right, depth + 1))- stack.append((*left, depth + 1))- return result---def flatten_path(- path: GraphicsPath,- *,- flatness: float = _DEFAULT_FLATNESS,- max_depth: int = _MAX_CUBIC_DEPTH,- budget: FlattenBudget | None = None,-) -> list[tuple[list[Point], bool]]:- """把曲线路径按输出像素误差离散成 Pillow 可绘制的折线子路径。"""- if flatness <= 0.0:- raise ValueError("flatness must be positive")- if max_depth < 0:- raise ValueError("max_depth must not be negative")- active_budget = budget or FlattenBudget()- subpaths: list[tuple[list[Point], bool]] = []- current_points: list[Point] = []- current_point: Point | None = None- closed = False- for segment in path.segments:- if segment.verb == "M":- if current_points:- subpaths.append((current_points, closed))- current_points = [segment.points[0]]- active_budget.charge()- current_point = segment.points[0]- closed = False- elif segment.verb == "L":- if current_point is None:- current_points = [segment.points[0]]- else:- current_points.append(segment.points[0])- active_budget.charge()- current_point = segment.points[0]- elif segment.verb == "C" and current_point is not None:- control1, control2, endpoint = segment.points- current_points.extend(- _flatten_cubic(- current_point,- control1,- control2,- endpoint,- flatness=flatness,- max_depth=max_depth,- budget=active_budget,- )- )- current_point = endpoint- elif segment.verb == "Z":- closed = True- if current_points and current_points[-1] != current_points[0]:- current_points.append(current_points[0])- active_budget.charge()- if current_points:- subpaths.append((current_points, closed))- return subpaths---def vector_length(vector: Point) -> float:- """返回二维向量的欧氏长度。"""- return hypot(vector[0], vector[1])---__all__ = [- "FlattenBudget",- "PathBuilder",- "arc_path",- "close_open_subpaths",- "colorref_to_rgb",- "ellipse_path",- "flatten_path",- "path_bounds",- "rectangle_path",- "round_rectangle_path",- "transform_path",- "union_rectangles",- "vector_length",-]diff --git a/mineru/model/flash/office/metafile/limits.py b/mineru/model/flash/office/metafile/limits.pydeleted file mode 100644index 1512ffe5..00000000--- a/mineru/model/flash/office/metafile/limits.py+++ /dev/null@@ -1,40 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""WMF/EMF 解析与渲染的固定安全预算。"""--from typing import Final---MAX_METAFILE_BYTES: Final = 128 * 1024 * 1024-MAX_RECORDS: Final = 1_000_000-MAX_POINTS_PER_RECORD: Final = 1_000_000-MAX_TOTAL_POINTS: Final = 5_000_000-MAX_COMMANDS: Final = 100_000-MAX_OBJECTS: Final = 65_536-MAX_STATE_DEPTH: Final = 64-MAX_CLIP_OPERATIONS: Final = 64-MAX_TOTAL_CLIP_OPERATIONS: Final = 100_000-MAX_DIAGNOSTICS: Final = 256-MAX_CANVAS_DIMENSION: Final = 8_192-MAX_CANVAS_PIXELS: Final = 16_000_000-MAX_RENDER_WORK_PIXELS: Final = 512_000_000-MAX_EMBEDDED_BITMAP_BYTES: Final = 128 * 1024 * 1024-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",- "MAX_FLATTENED_POINTS",- "MAX_METAFILE_BYTES",- "MAX_OBJECTS",- "MAX_POINTS_PER_RECORD",- "MAX_RECORDS",- "MAX_RENDER_WORK_PIXELS",- "MAX_STATE_DEPTH",- "MAX_TOTAL_POINTS",- "MAX_TOTAL_CLIP_OPERATIONS",-]diff --git a/mineru/model/flash/office/metafile/models.py b/mineru/model/flash/office/metafile/models.pydeleted file mode 100644index 5f3985bd..00000000--- a/mineru/model/flash/office/metafile/models.py+++ /dev/null@@ -1,342 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""WMF/EMF 回放状态、绘图 IR 与结果模型。"""--from __future__ import annotations--from dataclasses import dataclass, field-from typing import Literal, TypeAlias---MetafileSourceFormat: TypeAlias = Literal["wmf", "emf"]-MetafileOutputFormat: TypeAlias = Literal["png", "jpeg", "svg"]-EmfPlusMode: TypeAlias = Literal["none", "dual", "only"]-DiagnosticLevel: TypeAlias = Literal["info", "warning", "error"]-Point: TypeAlias = tuple[float, float]---class MetafileError(ValueError):- """WMF/EMF 渲染错误基类,并携带稳定错误码。"""-- code = "metafile_error"---class MetafileMalformedError(MetafileError):- """WMF/EMF 头部或记录流不满足格式边界。"""-- code = "malformed"---class MetafileResourceLimitError(MetafileError):- """WMF/EMF 输入或输出超过固定安全预算。"""-- code = "resource_limit"---class MetafileUnsupportedError(MetafileError):- """输入使用无法安全降级的 WMF/EMF 能力。"""-- code = "unsupported"---@dataclass(frozen=True, slots=True)-class MetafileDiagnostic:- """记录单个可定位、可聚合的 WMF/EMF 渲染诊断。"""-- code: str- level: DiagnosticLevel- message: str- record_type: int | None = None- record_index: int | None = None- offset: int | None = None---@dataclass(frozen=True, slots=True)-class Color:- """保存标准 RGBA 颜色分量。"""-- red: int- green: int- blue: int- alpha: int = 255-- def rgba(self) -> tuple[int, int, int, int]:- """返回 Pillow 可直接消费的 RGBA 元组。"""- return self.red, self.green, self.blue, self.alpha-- def svg(self) -> str:- """返回不含透明度的 SVG 十六进制颜色。"""- return f"#{self.red:02x}{self.green:02x}{self.blue:02x}"---BLACK = Color(0, 0, 0)-WHITE = Color(255, 255, 255)-TRANSPARENT = Color(0, 0, 0, 0)---@dataclass(frozen=True, slots=True)-class Rect:- """保存规范化前后均可使用的浮点矩形。"""-- left: float- top: float- right: float- bottom: float-- @property- def width(self) -> float:- """返回矩形的有符号宽度。"""- return self.right - self.left-- @property- def height(self) -> float:- """返回矩形的有符号高度。"""- return self.bottom - self.top-- def normalized(self) -> Rect:- """返回左右、上下均按升序排列的矩形。"""- return Rect(- min(self.left, self.right),- min(self.top, self.bottom),- max(self.left, self.right),- max(self.top, self.bottom),- )---@dataclass(frozen=True, slots=True)-class Matrix:- """保存二维仿射变换,采用 SVG/Pillow 常用的六参数表示。"""-- a: float = 1.0- b: float = 0.0- c: float = 0.0- d: float = 1.0- e: float = 0.0- f: float = 0.0-- def transform_point(self, point: Point) -> Point:- """把单点应用到当前仿射变换。"""- x, y = point- return self.a * x + self.c * y + self.e, self.b * x + self.d * y + self.f-- def transform_vector(self, vector: Point) -> Point:- """只应用线性部分,避免平移污染长度和方向。"""- x, y = vector- return self.a * x + self.c * y, self.b * x + self.d * y-- def then(self, following: Matrix) -> Matrix:- """返回先应用当前矩阵、再应用 following 的组合矩阵。"""- return Matrix(- a=following.a * self.a + following.c * self.b,- b=following.b * self.a + following.d * self.b,- c=following.a * self.c + following.c * self.d,- d=following.b * self.c + following.d * self.d,- e=following.a * self.e + following.c * self.f + following.e,- f=following.b * self.e + following.d * self.f + following.f,- )---@dataclass(frozen=True, slots=True)-class Pen:- """保存已经解析的 GDI 画笔。"""-- color: Color = BLACK- width: float = 1.0- style: int = 0- cosmetic: bool = True- null: bool = False- cap: Literal["round", "square", "flat"] = "round"- join: Literal["round", "bevel", "miter"] = "round"- dashes: tuple[float, ...] = ()---@dataclass(frozen=True, slots=True)-class Brush:- """保存已经解析的 GDI 画刷。"""-- kind: Literal["solid", "null", "hatch", "pattern"] = "solid"- color: Color = WHITE- hatch: int = 0- pattern: bytes | None = None---@dataclass(frozen=True, slots=True)-class Font:- """保存 GDI LOGFONT 中与跨平台绘制有关的字段。"""-- face_name: str = "Arial"- height: float = -12.0- width: float = 0.0- weight: int = 400- italic: bool = False- underline: bool = False- strikeout: bool = False- charset: int = 1- escapement: float = 0.0- orientation: float = 0.0---@dataclass(frozen=True, slots=True)-class PathSegment:- """保存单个 move/line/cubic/close 路径片段。"""-- verb: Literal["M", "L", "C", "Z"]- points: tuple[Point, ...] = ()---@dataclass(frozen=True, slots=True)-class GraphicsPath:- """保存不可变的跨后端绘图路径。"""-- segments: tuple[PathSegment, ...]---@dataclass(frozen=True, slots=True)-class ClipOperation:- """保存按 GDI 顺序应用的单次裁剪区域操作。"""-- path: GraphicsPath- mode: Literal["and", "or", "xor", "diff", "copy"]- fill_rule: Literal["evenodd", "nonzero"] = "evenodd"---ClipStack: TypeAlias = tuple[ClipOperation, ...]---@dataclass(frozen=True, slots=True)-class DrawPathCommand:- """保存一次路径填充和描边操作。"""-- path: GraphicsPath- pen: Pen- brush: Brush- stroke: bool- fill: bool- fill_rule: Literal["evenodd", "nonzero"]- clip: ClipStack- rop2: int- miter_limit: float = 10.0---@dataclass(frozen=True, slots=True)-class DrawTextCommand:- """保存一次 GDI 文字输出及其显式字符位置。"""-- text: str- origin: Point- positions: tuple[Point, ...]- font: Font- font_height: float- rotation: float- text_align: int- color: Color- background_color: Color- opaque: bool- bounds: Rect | None- clip: ClipStack- advance_end: Point | None = None---@dataclass(frozen=True, slots=True)-class DrawImageCommand:- """保存一次 DIB/位图绘制及其 GDI 合成参数。"""-- dib_header: bytes- bits: bytes- destination: tuple[Point, Point, Point, Point]- source: Rect | None- rop: int- stretch_mode: int = 3- constant_alpha: int = 255- use_source_alpha: bool = False- clip: ClipStack = ()---DrawCommand: TypeAlias = DrawPathCommand | DrawTextCommand | DrawImageCommand---@dataclass(frozen=True, slots=True)-class MetafileDocument:- """保存解析完成、可被多个后端消费的统一图元文档。"""-- source_format: MetafileSourceFormat- emfplus_mode: EmfPlusMode- bounds: Rect- width: int- height: int- commands: tuple[DrawCommand, ...]- diagnostics: tuple[MetafileDiagnostic, ...]- partial: bool---@dataclass(frozen=True, slots=True)-class MetafileRenderResult:- """保存最终图片字节、尺寸与解析诊断。"""-- data: bytes- output_format: MetafileOutputFormat- media_type: str- width: int- height: int- source_format: MetafileSourceFormat- emfplus_mode: EmfPlusMode- partial: bool- diagnostics: tuple[MetafileDiagnostic, ...]---@dataclass(slots=True)-class GdiState:- """保存 WMF/EMF 当前 playback device context。"""-- pen: Pen = field(default_factory=Pen)- brush: Brush = field(default_factory=Brush)- font: Font = field(default_factory=Font)- text_color: Color = BLACK- background_color: Color = WHITE- background_mode: int = 2- text_align: int = 0- map_mode: int = 1- window_origin: Point = (0.0, 0.0)- window_extent: Point = (1.0, 1.0)- viewport_origin: Point = (0.0, 0.0)- viewport_extent: Point = (1.0, 1.0)- world_transform: Matrix = field(default_factory=Matrix)- current_position: Point = (0.0, 0.0)- polygon_fill_mode: int = 1- rop2: int = 13- stretch_mode: int = 1- arc_direction: int = 2- miter_limit: float = 10.0- brush_origin: Point = (0.0, 0.0)- clip: ClipStack = ()- device_pixels_per_mm: Point = (96.0 / 25.4, 96.0 / 25.4)---__all__ = [- "BLACK",- "WHITE",- "Brush",- "ClipOperation",- "Color",- "DrawCommand",- "DrawImageCommand",- "DrawPathCommand",- "DrawTextCommand",- "EmfPlusMode",- "Font",- "GdiState",- "GraphicsPath",- "Matrix",- "MetafileDiagnostic",- "MetafileDocument",- "MetafileError",- "MetafileMalformedError",- "MetafileOutputFormat",- "MetafileRenderResult",- "MetafileResourceLimitError",- "MetafileSourceFormat",- "MetafileUnsupportedError",- "PathSegment",- "Pen",- "Point",- "Rect",-]diff --git a/mineru/model/flash/office/metafile/parser.py b/mineru/model/flash/office/metafile/parser.pydeleted file mode 100644index 0cb0e309..00000000--- a/mineru/model/flash/office/metafile/parser.py+++ /dev/null@@ -1,2017 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""WMF/EMF 有界解析与 GDI 状态回放。"""--from __future__ import annotations--from dataclasses import dataclass, replace-from math import atan2, cos, degrees, isfinite, radians, sin-import struct--from .binary import BoundedReader-from .font import measure_text_advance-from .geometry import (- PathBuilder,- arc_path,- close_open_subpaths,- colorref_to_rgb,- ellipse_path,- path_bounds,- rectangle_path,- round_rectangle_path,- transform_path,- union_rectangles,- vector_length,-)-from .limits import (- MAX_CANVAS_DIMENSION,- MAX_CANVAS_PIXELS,- MAX_CLIP_OPERATIONS,- MAX_COMMANDS,- MAX_DIAGNOSTICS,- MAX_EMBEDDED_BITMAP_BYTES,- MAX_METAFILE_BYTES,- MAX_OBJECTS,- MAX_POINTS_PER_RECORD,- MAX_RECORDS,- MAX_STATE_DEPTH,- MAX_TOTAL_CLIP_OPERATIONS,- MAX_TOTAL_POINTS,-)-from .models import (- BLACK,- WHITE,- Brush,- ClipOperation,- Color,- DrawCommand,- DrawImageCommand,- DrawPathCommand,- DrawTextCommand,- EmfPlusMode,- Font,- GdiState,- GraphicsPath,- Matrix,- MetafileDiagnostic,- MetafileDocument,- MetafileMalformedError,- MetafileResourceLimitError,- MetafileSourceFormat,- MetafileUnsupportedError,- Pen,- Point,- Rect,-)---_EMF_SIGNATURE = 0x464D4520-_EMFPLUS_SIGNATURE = 0x2B464D45-_PLACEABLE_WMF_KEY = 0x9AC6CDD7--_RGN_AND = 1-_RGN_OR = 2-_RGN_XOR = 3-_RGN_DIFF = 4-_RGN_COPY = 5--_ETO_OPAQUE = 0x0002-_ETO_CLIPPED = 0x0004-_ETO_GLYPH_INDEX = 0x0010-_ETO_PDY = 0x2000-_TA_UPDATECP = 0x0001-_TA_RIGHT = 0x0002-_TA_CENTER = 0x0006--_SRCCOPY = 0x00CC0020-_SUPPORTED_ROP3 = {- _SRCCOPY,- 0x008800C6,- 0x00EE0086,- 0x00660046,- 0x00550009,- 0x00000042,- 0x00FF0062,-}---@dataclass(frozen=True, slots=True)-class _HeaderInfo:- """保存格式头部解析出的记录边界、坐标边界和输出尺寸。"""-- source_format: MetafileSourceFormat- record_start: int- record_end: int- bounds: Rect | None- pixel_size: tuple[int, int] | None- emfplus_mode: EmfPlusMode = "none"- device_pixels_per_mm: Point = (96.0 / 25.4, 96.0 / 25.4)- wmf_object_count: int = 0---class _DiagnosticSink:- """收集有界诊断并聚合超出预算的重复项目。"""-- def __init__(self) -> None:- """创建空诊断列表和截断计数器。"""- self.items: list[MetafileDiagnostic] = []- self.omitted = 0-- def add(- self,- code: str,- level: str,- message: str,- *,- record_type: int | None = None,- record_index: int | None = None,- offset: int | None = None,- ) -> None:- """在预算内追加诊断,超出时只累计省略数量。"""- if len(self.items) >= MAX_DIAGNOSTICS:- self.omitted += 1- return- normalized_level = level if level in {"info", "warning", "error"} else "warning"- self.items.append(- MetafileDiagnostic(- code=code,- level=normalized_level, # type: ignore[arg-type]- message=message,- record_type=record_type,- record_index=record_index,- offset=offset,- )- )-- def freeze(self) -> tuple[MetafileDiagnostic, ...]:- """冻结诊断,并在需要时追加一条截断摘要。"""- if self.omitted:- self.items.append(- MetafileDiagnostic(- code="diagnostics_truncated",- level="warning",- message=f"omitted {self.omitted} additional metafile diagnostics",- )- )- return tuple(self.items)---class _Playback:- """把 WMF/EMF records 回放为统一绘图命令。"""-- def __init__(self, header: _HeaderInfo, diagnostics: _DiagnosticSink) -> None:- """初始化 GDI 状态、对象表、路径与资源计数。"""- self.header = header- self.diagnostics = diagnostics- self.state = GdiState(device_pixels_per_mm=header.device_pixels_per_mm)- self.state_stack: list[GdiState] = []- self.emf_objects: dict[int, Pen | Brush | Font] = {}- self.wmf_objects: list[Pen | Brush | Font | None] = [None] * min(header.wmf_object_count, MAX_OBJECTS)- self.commands: list[DrawCommand] = []- self.path_builder = PathBuilder()- self.path_active = False- self.path_ready = False- self.partial = False- self.total_points = 0- self.total_clip_operations = 0- self.record_type: int | None = None- self.record_index: int | None = None- self.record_offset: int | None = None-- def set_record_context(self, record_type: int, record_index: int, offset: int) -> None:- """更新后续诊断所使用的当前记录定位信息。"""- self.record_type = record_type- self.record_index = record_index- self.record_offset = offset-- def warn(self, code: str, message: str, *, partial: bool = True) -> None:- """为当前记录追加警告,并按需标记输出不完整。"""- self.partial = self.partial or partial- self.diagnostics.add(- code,- "warning",- message,- record_type=self.record_type,- record_index=self.record_index,- offset=self.record_offset,- )-- def charge_points(self, count: int) -> None:- """累计点数并执行单记录与全文件预算。"""- if count < 0 or count > MAX_POINTS_PER_RECORD:- raise MetafileResourceLimitError(f"metafile record exceeds max_points_per_record={MAX_POINTS_PER_RECORD}")- self.total_points += count- if self.total_points > MAX_TOTAL_POINTS:- raise MetafileResourceLimitError(f"metafile exceeds max_total_points={MAX_TOTAL_POINTS}")-- def append_command(self, command: DrawCommand) -> None:- """在命令预算内追加一条统一绘图命令。"""- 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:- """复制当前可由 SaveDC/RestoreDC 恢复的 GDI 状态。"""- return replace(self.state)-- def save_dc(self) -> None:- """把当前 GDI 状态压入有界栈。"""- if len(self.state_stack) >= MAX_STATE_DEPTH:- raise MetafileResourceLimitError(f"metafile exceeds max_state_depth={MAX_STATE_DEPTH}")- self.state_stack.append(self.copy_state())-- def restore_dc(self, level: int) -> None:- """按 GDI 相对或绝对层级恢复已保存状态。"""- if not self.state_stack:- self.warn("restore_dc_underflow", "RestoreDC ignored because the state stack is empty")- return- if level < 0:- target = len(self.state_stack) + level- elif level > 0:- target = level - 1- else:- self.warn("restore_dc_zero", "RestoreDC level 0 is invalid")- return- if target < 0 or target >= len(self.state_stack):- self.warn("restore_dc_out_of_range", f"RestoreDC level is out of range: {level}")- return- self.state = self.state_stack[target]- del self.state_stack[target:]-- def _mapping_matrix(self) -> Matrix:- """根据 mapping mode、window 和 viewport 计算 page-to-device 变换。"""- mode = self.state.map_mode- window_x, window_y = self.state.window_origin- viewport_x, viewport_y = self.state.viewport_origin- if mode in {7, 8}:- window_width, window_height = self.state.window_extent- viewport_width, viewport_height = self.state.viewport_extent- if window_width == 0.0 or window_height == 0.0:- self.warn("zero_window_extent", "zero window extent was replaced by identity mapping")- scale_x = scale_y = 1.0- else:- scale_x = viewport_width / window_width- scale_y = viewport_height / window_height- elif mode == 2:- scale_x = self.state.device_pixels_per_mm[0] / 10.0- scale_y = -self.state.device_pixels_per_mm[1] / 10.0- elif mode == 3:- scale_x = self.state.device_pixels_per_mm[0] / 100.0- scale_y = -self.state.device_pixels_per_mm[1] / 100.0- elif mode == 4:- scale_x = self.state.device_pixels_per_mm[0] * 25.4 / 100.0- scale_y = -self.state.device_pixels_per_mm[1] * 25.4 / 100.0- elif mode == 5:- scale_x = self.state.device_pixels_per_mm[0] * 25.4 / 1000.0- scale_y = -self.state.device_pixels_per_mm[1] * 25.4 / 1000.0- elif mode == 6:- scale_x = self.state.device_pixels_per_mm[0] * 25.4 / 1440.0- scale_y = -self.state.device_pixels_per_mm[1] * 25.4 / 1440.0- else:- scale_x = scale_y = 1.0- return Matrix(- a=scale_x,- d=scale_y,- e=viewport_x - window_x * scale_x,- f=viewport_y - window_y * scale_y,- )-- def logical_matrix(self) -> Matrix:- """返回 world-to-page 与 page-to-device 的组合变换。"""- return self.state.world_transform.then(self._mapping_matrix())-- def map_point(self, point: Point) -> Point:- """把 GDI 逻辑点转换为统一 device 坐标。"""- mapped = self.logical_matrix().transform_point(point)- if not all(isfinite(value) and abs(value) <= 1e12 for value in mapped):- raise MetafileResourceLimitError("metafile coordinate is non-finite or unreasonably large")- return mapped-- def map_vector(self, vector: Point) -> Point:- """把不含平移的 GDI 逻辑向量转换为 device 向量。"""- mapped = self.logical_matrix().transform_vector(vector)- if not all(isfinite(value) and abs(value) <= 1e12 for value in mapped):- raise MetafileResourceLimitError("metafile vector is non-finite or unreasonably large")- return mapped-- def resolved_pen(self) -> Pen:- """把当前画笔宽度解析为 device 单位并保留 cosmetic 语义。"""- pen = self.state.pen- if pen.null:- return pen- if pen.cosmetic:- return replace(pen, width=max(1.0, pen.width))- width = vector_length(self.map_vector((pen.width or 1.0, 0.0)))- return replace(pen, width=max(width, 1.0))-- def emit_path(self, path: GraphicsPath, *, stroke: bool, fill: bool) -> None:- """把路径追加到当前 path bracket 或直接生成绘图命令。"""- if self.path_active:- self.path_builder.extend(path)- return- if not path.segments:- return- self.append_command(- DrawPathCommand(- path=path,- pen=self.resolved_pen(),- brush=self.state.brush,- stroke=stroke and not self.state.pen.null,- fill=fill and self.state.brush.kind != "null",- fill_rule="evenodd" if self.state.polygon_fill_mode == 1 else "nonzero",- clip=self.state.clip,- rop2=self.state.rop2,- miter_limit=self.state.miter_limit,- )- )-- def emit_logical_path(self, path: GraphicsPath, *, stroke: bool, fill: bool) -> None:- """把逻辑坐标路径变换后交给统一路径输出。"""- self.emit_path(transform_path(path, self.logical_matrix()), stroke=stroke, fill=fill)-- def move_to(self, point: Point) -> None:- """更新 GDI current position,并在活动 path 中开始新 figure。"""- self.state.current_position = point- if self.path_active:- self.path_builder.move_to(self.map_point(point))-- def _ensure_active_path_current(self) -> None:- """保证活动 path 的下一条 To 记录从 GDI current position 起笔。"""- mapped = self.map_point(self.state.current_position)- if self.path_builder.current != mapped:- self.path_builder.move_to(mapped)-- def line_to(self, endpoint: Point) -> None:- """按 LineTo 语义追加直线并更新 GDI current position。"""- if self.path_active:- self._ensure_active_path_current()- self.path_builder.line_to(self.map_point(endpoint))- else:- self.emit_path(- _path_from_device_points(- [self.map_point(self.state.current_position), self.map_point(endpoint)],- close=False,- ),- stroke=True,- fill=False,- )- self.state.current_position = endpoint-- def polyline_to(self, points: list[Point]) -> None:- """按 PolylineTo 语义连续追加折线并更新 GDI current position。"""- if not points:- return- if self.path_active:- self._ensure_active_path_current()- for point in points:- self.path_builder.line_to(self.map_point(point))- else:- mapped = [self.map_point(self.state.current_position), *(self.map_point(point) for point in points)]- self.emit_path(_path_from_device_points(mapped, close=False), stroke=True, fill=False)- self.state.current_position = points[-1]-- def polybezier_to(self, points: list[Point]) -> None:- """按 PolyBezierTo 语义连续追加三次曲线并更新 GDI current position。"""- if not points:- return- remaining = points- if len(remaining) % 3:- self.warn("invalid_bezier_points", "PolyBezierTo point count is not a multiple of three")- remaining = remaining[: len(remaining) - len(remaining) % 3]- if not remaining:- return- builder = self.path_builder if self.path_active else PathBuilder()- if self.path_active:- self._ensure_active_path_current()- else:- builder.move_to(self.map_point(self.state.current_position))- for index in range(0, len(remaining), 3):- builder.cubic_to(- self.map_point(remaining[index]),- self.map_point(remaining[index + 1]),- self.map_point(remaining[index + 2]),- )- if not self.path_active:- self.emit_path(builder.build(), stroke=True, fill=False)- self.state.current_position = remaining[-1]-- def connected_arc(self, path: GraphicsPath) -> None:- """绘制 current-to-projected-start 连线和圆弧,并更新到 projected endpoint。"""- if not path.segments:- return- mapped_path = transform_path(path, self.logical_matrix())- mapped_start = mapped_path.segments[0].points[0]- tail = GraphicsPath(mapped_path.segments[1:])- if self.path_active:- self._ensure_active_path_current()- self.path_builder.line_to(mapped_start)- self.path_builder.extend(tail)- else:- builder = PathBuilder()- builder.move_to(self.map_point(self.state.current_position))- builder.line_to(mapped_start)- builder.extend(tail)- self.emit_path(builder.build(), stroke=True, fill=False)- self.state.current_position = path.segments[-1].points[-1]-- def begin_path(self) -> None:- """开始新的 GDI path bracket 并清除旧路径。"""- if self.path_active:- self.warn("begin_path_while_active", "BeginPath replaced an already active path bracket")- self.path_builder.clear()- self.path_active = True- self.path_ready = False-- def end_path(self) -> None:- """结束 path bracket 并保留路径供后续 fill/stroke/clip。"""- if not self.path_active:- self.warn("end_path_without_begin", "EndPath ignored without a matching BeginPath")- return- self.path_active = False- self.path_ready = True-- def consume_path(self) -> GraphicsPath:- """返回并清除已经结束的当前路径。"""- if not self.path_ready:- self.warn("path_not_ready", "path operation ignored because no completed path exists")- return GraphicsPath(())- path = self.path_builder.build()- self.path_builder.clear()- self.path_ready = False- return path-- def add_clip(self, path: GraphicsPath, mode: int) -> None:- """把 GDI region combine mode 转换为不可变裁剪操作。"""- mode_name = _clip_mode_name(mode)- if mode_name is None:- self.warn("unsupported_clip_mode", f"unsupported clip combine mode: {mode}")- return- operation = ClipOperation(- path=path,- mode=mode_name,- fill_rule="evenodd" if self.state.polygon_fill_mode == 1 else "nonzero",- )- if mode == _RGN_COPY:- self.state.clip = (operation,)- else:- 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:- """恢复为没有额外裁剪区域的初始状态。"""- self.state.clip = ()-- def create_wmf_object(self, value: Pen | Brush | Font) -> None:- """按 WMF 首个空槽规则登记图形对象。"""- for index, existing in enumerate(self.wmf_objects):- if existing is None:- self.wmf_objects[index] = value- return- if len(self.wmf_objects) >= MAX_OBJECTS:- raise MetafileResourceLimitError(f"WMF object table exceeds max_objects={MAX_OBJECTS}")- self.wmf_objects.append(value)-- def select_object(self, value: Pen | Brush | Font) -> None:- """按对象实际类型更新当前选中画笔、画刷或字体。"""- if isinstance(value, Pen):- self.state.pen = value- elif isinstance(value, Brush):- self.state.brush = value- else:- self.state.font = value-- def select_emf_handle(self, handle: int) -> None:- """选择 EMF 显式 handle 或 stock object。"""- if handle & 0x80000000:- stock = _stock_object(handle & 0x7FFFFFFF)- if stock is None:- self.warn("unknown_stock_object", f"unknown EMF stock object: {handle:#x}")- return- self.select_object(stock)- return- value = self.emf_objects.get(handle)- if value is None:- self.warn("missing_object", f"EMF object handle does not exist: {handle}")- return- self.select_object(value)-- def select_wmf_handle(self, handle: int) -> None:- """选择 WMF 对象槽或兼容的 stock object。"""- if handle & 0x8000:- stock = _stock_object(handle & 0x7FFF)- if stock is None:- self.warn("unknown_stock_object", f"unknown WMF stock object: {handle:#x}")- return- self.select_object(stock)- return- if handle >= len(self.wmf_objects) or self.wmf_objects[handle] is None:- self.warn("missing_object", f"WMF object handle does not exist: {handle}")- return- self.select_object(self.wmf_objects[handle]) # type: ignore[arg-type]-- def finalize(self, size_hint: tuple[int, int] | None) -> MetafileDocument:- """解析最终边界、输出尺寸并冻结统一图元文档。"""- command_bounds = _commands_bounds(self.commands)- bounds = self.header.bounds- if bounds is None or abs(bounds.width) < 1e-9 or abs(bounds.height) < 1e-9:- bounds = command_bounds- if bounds is None or abs(bounds.width) < 1e-9 or abs(bounds.height) < 1e-9:- raise MetafileUnsupportedError("metafile contains no visible output")- bounds = bounds.normalized()- requested = size_hint or self.header.pixel_size- if requested is None:- requested = max(1, round(bounds.width)), max(1, round(bounds.height))- width, height, downscaled = _bounded_canvas_size(requested)- if downscaled:- self.diagnostics.add(- "canvas_downscaled",- "warning",- f"metafile canvas was downscaled from {requested[0]}x{requested[1]} to {width}x{height}",- )- return MetafileDocument(- source_format=self.header.source_format,- emfplus_mode=self.header.emfplus_mode,- bounds=bounds,- width=width,- height=height,- commands=tuple(self.commands),- diagnostics=self.diagnostics.freeze(),- partial=self.partial,- )---def _clip_mode_name(mode: int) -> str | None:- """把 GDI RegionMode 数值转换为内部裁剪操作名称。"""- return {- _RGN_AND: "and",- _RGN_OR: "or",- _RGN_XOR: "xor",- _RGN_DIFF: "diff",- _RGN_COPY: "copy",- }.get(mode)---def _stock_object(index: int) -> Pen | Brush | Font | None:- """返回常见 GDI stock object 的确定性跨平台表示。"""- brushes: dict[int, Brush] = {- 0: Brush(color=WHITE),- 1: Brush(color=Color(192, 192, 192)),- 2: Brush(color=Color(128, 128, 128)),- 3: Brush(color=Color(64, 64, 64)),- 4: Brush(color=BLACK),- 5: Brush(kind="null"),- 6: Brush(kind="null"),- 18: Brush(color=WHITE),- }- if index in brushes:- return brushes[index]- pens: dict[int, Pen] = {- 7: Pen(color=WHITE),- 8: Pen(color=BLACK),- 9: Pen(null=True),- 19: Pen(color=BLACK),- }- if index in pens:- return pens[index]- if 10 <= index <= 17:- return Font(face_name="Courier New" if index in {10, 11, 16} else "Arial")- 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] = []- for command in commands:- if isinstance(command, DrawPathCommand):- rectangles.append(path_bounds(command.path))- elif isinstance(command, DrawTextCommand):- if command.bounds is not None and abs(command.bounds.width) > 0 and abs(command.bounds.height) > 0:- 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_factor- rectangles.append(- Rect(- left,- command.origin[1] - command.font_height,- left + estimated_width,- command.origin[1] + command.font_height * 0.25,- )- )- else:- xs = [point[0] for point in command.destination]- ys = [point[1] for point in command.destination]- rectangles.append(Rect(min(xs), min(ys), max(xs), max(ys)))- return union_rectangles(rectangles)---def _bounded_canvas_size(requested: tuple[int, int]) -> tuple[int, int, bool]:- """按单边和总像素预算等比收缩画布尺寸。"""- width, height = requested- if width <= 0 or height <= 0:- raise MetafileMalformedError(f"metafile canvas must be positive: {width}x{height}")- scale = min(1.0, MAX_CANVAS_DIMENSION / width, MAX_CANVAS_DIMENSION / height)- if width * height * scale * scale > MAX_CANVAS_PIXELS:- scale = min(scale, (MAX_CANVAS_PIXELS / (width * height)) ** 0.5)- bounded_width = max(1, round(width * scale))- bounded_height = max(1, round(height * scale))- return bounded_width, bounded_height, scale < 1.0---def _parse_rect_i32(reader: BoundedReader, offset: int) -> Rect:- """读取四个有符号 32 位坐标组成的 RectL。"""- return Rect(reader.i32(offset), reader.i32(offset + 4), reader.i32(offset + 8), reader.i32(offset + 12))---def _parse_rect_i16(reader: BoundedReader, offset: int) -> Rect:- """读取四个有符号 16 位坐标组成的 WMF 矩形。"""- return Rect(reader.i16(offset), reader.i16(offset + 2), reader.i16(offset + 4), reader.i16(offset + 6))---def _parse_xform(reader: BoundedReader, offset: int) -> Matrix:- """读取 EMF XForm 六个浮点参数并拒绝非有限值。"""- values = tuple(reader.f32(offset + index * 4) for index in range(6))- if not all(isfinite(value) and abs(value) <= 1e12 for value in values):- raise MetafileMalformedError("EMF XForm contains non-finite or unreasonably large values")- return Matrix(a=values[0], b=values[1], c=values[2], d=values[3], e=values[4], f=values[5])---def _parse_color(value: int, *, alpha: int = 255) -> Color:- """把 GDI COLORREF 转换为带指定透明度的内部颜色。"""- red, green, blue = colorref_to_rgb(value)- return Color(red, green, blue, alpha)---def _detect_source_format(data: bytes) -> MetafileSourceFormat:- """只依据实际文件签名区分 WMF 与 EMF。"""- if (- len(data) >= 44- and struct.unpack_from("<I", data, 0)[0] == 1- and struct.unpack_from("<I", data, 40)[0] == _EMF_SIGNATURE- ):- return "emf"- wmf_offset = 22 if len(data) >= 22 and struct.unpack_from("<I", data, 0)[0] == _PLACEABLE_WMF_KEY else 0- if len(data) >= wmf_offset + 18:- file_type, header_size = struct.unpack_from("<HH", data, wmf_offset)- if file_type in {1, 2} and header_size == 9:- return "wmf"- raise MetafileMalformedError("input does not contain a valid WMF or EMF signature")---def _scan_emfplus_mode(data: bytes, start: int, end: int) -> EmfPlusMode:- """预扫描 EMR_COMMENT 中的 EMF+ header 并识别 Only/Dual。"""- offset = start- found_header = False- found_dual = False- record_count = 0- while offset + 8 <= end:- record_type, record_size = struct.unpack_from("<II", data, offset)- record_count += 1- if record_count > MAX_RECORDS:- raise MetafileResourceLimitError(f"EMF exceeds max_records={MAX_RECORDS}")- if record_size < 8 or record_size % 4 or record_size > end - offset:- raise MetafileMalformedError(f"invalid EMF record while scanning comments: offset={offset}, size={record_size}")- if record_type == 70 and record_size >= 28:- data_size = struct.unpack_from("<I", data, offset + 8)[0]- if data_size <= record_size - 12 and struct.unpack_from("<I", data, offset + 12)[0] == _EMFPLUS_SIGNATURE:- payload_offset = offset + 16- payload_end = offset + 12 + data_size- while payload_offset + 12 <= payload_end:- plus_type, flags, plus_size, plus_data_size = struct.unpack_from("<HHII", data, payload_offset)- if plus_size < 12 or plus_size > payload_end - payload_offset or plus_data_size > plus_size - 12:- break- if plus_type == 0x4001:- found_header = True- found_dual = found_dual or bool(flags & 1)- payload_offset += plus_size- offset += record_size- if record_type == 14:- break- if not found_header:- return "none"- return "dual" if found_dual else "only"---def _parse_emf_header(data: bytes, dpi: int, size_hint: tuple[int, int] | None) -> _HeaderInfo:- """解析 EMR_HEADER、声明文件边界和物理输出尺寸。"""- reader = BoundedReader(data)- if len(reader) < 88 or reader.u32(0) != 1:- raise MetafileMalformedError("EMF header is truncated or has the wrong record type")- header_size = reader.u32(4)- if header_size < 88 or header_size % 4 or header_size > len(reader):- raise MetafileMalformedError(f"invalid EMF header size: {header_size}")- if reader.u32(40) != _EMF_SIGNATURE:- raise MetafileMalformedError("invalid EMF signature")- declared_bytes = reader.u32(48)- declared_records = reader.u32(52)- if declared_bytes < header_size or declared_bytes > len(reader):- raise MetafileMalformedError(f"invalid EMF declared byte size: {declared_bytes}")- if declared_records == 0 or declared_records > MAX_RECORDS:- raise MetafileResourceLimitError(f"invalid or excessive EMF record count: {declared_records}")- bounds = _parse_rect_i32(reader, 8)- frame = _parse_rect_i32(reader, 24)- device_x, device_y = reader.i32(72), reader.i32(76)- millimeter_x, millimeter_y = reader.i32(80), reader.i32(84)- if millimeter_x > 0 and millimeter_y > 0 and device_x > 0 and device_y > 0:- device_scale = device_x / millimeter_x, device_y / millimeter_y- else:- device_scale = dpi / 25.4, dpi / 25.4- pixel_size = size_hint- if pixel_size is None and frame.width != 0 and frame.height != 0:- pixel_size = max(1, round(abs(frame.width) * dpi / 2540.0)), max(1, round(abs(frame.height) * dpi / 2540.0))- if pixel_size is None and bounds.width != 0 and bounds.height != 0:- pixel_size = max(1, round(abs(bounds.width))), max(1, round(abs(bounds.height)))- emfplus_mode = _scan_emfplus_mode(data, 0, declared_bytes)- return _HeaderInfo(- source_format="emf",- record_start=0,- record_end=declared_bytes,- bounds=bounds,- pixel_size=pixel_size,- emfplus_mode=emfplus_mode,- device_pixels_per_mm=device_scale,- )---def _parse_wmf_header(data: bytes, dpi: int, size_hint: tuple[int, int] | None) -> _HeaderInfo:- """解析 placeable/standard WMF 头部、对象表大小与输出尺寸。"""- reader = BoundedReader(data)- record_start = 0- bounds: Rect | None = None- pixel_size = size_hint- if len(reader) >= 22 and reader.u32(0) == _PLACEABLE_WMF_KEY:- checksum = 0- for offset in range(0, 20, 2):- checksum ^= reader.u16(offset)- if checksum != reader.u16(20):- raise MetafileMalformedError("placeable WMF checksum does not match")- bounds = Rect(reader.i16(6), reader.i16(8), reader.i16(10), reader.i16(12))- units_per_inch = reader.u16(14)- if units_per_inch == 0:- raise MetafileMalformedError("placeable WMF units-per-inch must be nonzero")- if pixel_size is None:- pixel_size = (- max(1, round(abs(bounds.width) * dpi / units_per_inch)),- max(1, round(abs(bounds.height) * dpi / units_per_inch)),- )- record_start = 22- if len(reader) < record_start + 18:- raise MetafileMalformedError("standard WMF header is truncated")- header = reader.subreader(record_start, 18)- if header.u16(0) not in {1, 2} or header.u16(2) != 9:- raise MetafileMalformedError("invalid standard WMF header")- declared_bytes = header.u32(6) * 2- if declared_bytes < 18 or declared_bytes > len(reader) - record_start:- raise MetafileMalformedError(f"invalid WMF declared byte size: {declared_bytes}")- object_count = header.u16(10)- if object_count > MAX_OBJECTS:- raise MetafileResourceLimitError(f"WMF object table exceeds max_objects={MAX_OBJECTS}")- return _HeaderInfo(- source_format="wmf",- record_start=record_start + 18,- record_end=record_start + declared_bytes,- bounds=bounds,- pixel_size=pixel_size,- device_pixels_per_mm=(dpi / 25.4, dpi / 25.4),- wmf_object_count=object_count,- )---def parse_metafile(- data: bytes,- *,- dpi: int = 144,- size_hint: tuple[int, int] | None = None,-) -> MetafileDocument:- """检测并解析 WMF/EMF,返回跨后端统一图元文档。"""- if not isinstance(data, bytes):- raise TypeError("metafile data must be bytes")- if not data:- raise MetafileMalformedError("metafile data must not be empty")- if len(data) > MAX_METAFILE_BYTES:- raise MetafileResourceLimitError(f"metafile exceeds max_metafile_bytes={MAX_METAFILE_BYTES}")- if not isinstance(dpi, int) or dpi < 1 or dpi > 1200:- raise ValueError("dpi must be an integer between 1 and 1200")- if size_hint is not None and (- len(size_hint) != 2 or not all(isinstance(value, int) for value in size_hint) or size_hint[0] <= 0 or size_hint[1] <= 0- ):- raise ValueError("size_hint must contain two positive integers")- source_format = _detect_source_format(data)- header = _parse_emf_header(data, dpi, size_hint) if source_format == "emf" else _parse_wmf_header(data, dpi, size_hint)- if header.emfplus_mode == "only":- raise MetafileUnsupportedError("EMF+ Only metafiles are not supported")- diagnostics = _DiagnosticSink()- playback = _Playback(header, diagnostics)- if source_format == "emf":- _play_emf(data, header, playback)- else:- _play_wmf(data, header, playback)- return playback.finalize(size_hint)---def _pen_dash_pattern(style: int, width: float) -> tuple[float, ...]:- """把常见 GDI pen style 转换为 device 单位虚线模式。"""- unit = max(width, 1.0)- return {- 1: (6.0 * unit, 3.0 * unit),- 2: (unit, 2.0 * unit),- 3: (6.0 * unit, 2.0 * unit, unit, 2.0 * unit),- 4: (6.0 * unit, 2.0 * unit, unit, 2.0 * unit, unit, 2.0 * unit),- 8: (unit, unit),- }.get(style & 0xF, ())---def _make_pen(style: int, width: float, color_value: int, *, extended: bool = False) -> Pen:- """从 LOGPEN/EXTLOGPEN 字段构造统一画笔。"""- basic_style = style & 0xF- cap = "square" if style & 0x100 else "flat" if style & 0x200 else "round"- join = "bevel" if style & 0x1000 else "miter" if style & 0x2000 else "round"- geometric = bool(style & 0x10000) if extended else abs(width) > 1.0- normalized_width = max(abs(width), 1.0)- return Pen(- color=_parse_color(color_value),- width=normalized_width,- style=style,- cosmetic=not geometric,- null=basic_style == 5,- cap=cap,- join=join,- dashes=_pen_dash_pattern(style, normalized_width),- )---def _make_brush(style: int, color_value: int, hatch: int = 0, pattern: bytes | None = None) -> Brush:- """从 LOGBRUSH 字段构造统一画刷。"""- if style == 1:- return Brush(kind="null")- if style == 2:- return Brush(kind="hatch", color=_parse_color(color_value), hatch=hatch)- if style in {3, 5, 6, 7, 8}:- return Brush(kind="pattern", color=_parse_color(color_value), hatch=hatch, pattern=pattern)- return Brush(kind="solid", color=_parse_color(color_value), hatch=hatch)---def _decode_font_name(raw: bytes, *, wide: bool) -> str:- """解码 LOGFONT face name 并移除结尾 NUL。"""- if wide:- if len(raw) % 2:- raw = raw[:-1]- text = raw.decode("utf-16le", errors="replace")- else:- text = raw.decode("cp1252", errors="replace")- return text.split("\x00", 1)[0].strip() or "Arial"---def _parse_emf_font(record: BoundedReader) -> Font:- """解析 EMR_EXTCREATEFONTINDIRECTW 的 LOGFONTW 首部。"""- return Font(- face_name=_decode_font_name(record.bytes(40, 64), wide=True),- height=float(record.i32(12)),- width=float(record.i32(16)),- escapement=float(record.i32(20)),- orientation=float(record.i32(24)),- weight=record.i32(28),- italic=bool(record.u8(32)),- underline=bool(record.u8(33)),- strikeout=bool(record.u8(34)),- charset=record.u8(35),- )---def _parse_wmf_font(payload: BoundedReader) -> Font:- """解析 META_CREATEFONTINDIRECT 的 16 位 LOGFONT。"""- if len(payload) < 18:- raise MetafileMalformedError("WMF LOGFONT is truncated")- face_size = min(32, max(0, len(payload) - 18))- return Font(- face_name=_decode_font_name(payload.bytes(18, face_size), wide=False),- height=float(payload.i16(0)),- width=float(payload.i16(2)),- escapement=float(payload.i16(4)),- orientation=float(payload.i16(6)),- weight=payload.i16(8),- italic=bool(payload.u8(10)),- underline=bool(payload.u8(11)),- strikeout=bool(payload.u8(12)),- charset=payload.u8(13),- )---def _charset_codec(charset: int) -> str:- """把常见 Windows LOGFONT charset 映射为 Python codec。"""- return {- 0: "cp1252",- 1: "cp1252",- 2: "cp1252",- 128: "shift_jis",- 129: "cp949",- 134: "gb18030",- 136: "big5",- 161: "cp1253",- 162: "cp1254",- 163: "cp1258",- 177: "cp1255",- 178: "cp1256",- 186: "cp1257",- 204: "cp1251",- 222: "cp874",- 238: "cp1250",- 255: "cp437",- }.get(charset, "cp1252")---def _decode_ansi_text(raw: bytes, charset: int) -> str:- """按当前 LOGFONT charset 尽力解码 GDI ANSI 文本。"""- return raw.decode(_charset_codec(charset), errors="replace")---def _path_from_device_points(points: list[Point], *, close: bool) -> GraphicsPath:- """从 device 坐标点列构造单个折线路径。"""- if not points:- return GraphicsPath(())- builder = PathBuilder()- builder.move_to(points[0])- for point in points[1:]:- builder.line_to(point)- if close:- builder.close()- return builder.build()---def _read_emf_points(record: BoundedReader, count: int, offset: int, *, compact: bool) -> list[Point]:- """读取 EMF PointL/PointS 数组并保留逻辑坐标。"""- stride = 4 if compact else 8- if count < 0 or count > MAX_POINTS_PER_RECORD or count > record.remaining(offset) // stride:- raise MetafileMalformedError(f"EMF point array exceeds record boundary: count={count}")- if compact:- return [(float(record.i16(offset + index * 4)), float(record.i16(offset + index * 4 + 2))) for index in range(count)]- return [(float(record.i32(offset + index * 8)), float(record.i32(offset + index * 8 + 4))) for index in range(count)]---def _read_wmf_points(payload: BoundedReader, count: int, offset: int) -> list[Point]:- """读取 WMF PointS 数组并保留逻辑坐标。"""- if count < 0 or count > MAX_POINTS_PER_RECORD or count > payload.remaining(offset) // 4:- raise MetafileMalformedError(f"WMF point array exceeds record boundary: count={count}")- return [(float(payload.i16(offset + index * 4)), float(payload.i16(offset + index * 4 + 2))) for index in range(count)]---def _emit_polybezier(playback: _Playback, points: list[Point], *, to: bool) -> None:- """把 PolyBezier/PolyBezierTo 点列追加为三次路径。"""- if not points:- return- if to:- playback.polybezier_to(points)- return- builder = PathBuilder()- builder.move_to(playback.map_point(points[0]))- remaining = points[1:]- if len(remaining) % 3:- playback.warn("invalid_bezier_points", "PolyBezier point count is not a multiple of three")- remaining = remaining[: len(remaining) - len(remaining) % 3]- for index in range(0, len(remaining), 3):- builder.cubic_to(- playback.map_point(remaining[index]),- playback.map_point(remaining[index + 1]),- playback.map_point(remaining[index + 2]),- )- playback.emit_path(builder.build(), stroke=True, fill=False)---def _emit_text(- playback: _Playback,- *,- text: str,- reference: Point,- options: int,- bounds: Rect | None,- advances: list[Point] | None,-) -> None:- """把 GDI 文字和显式 advance 转换为统一文字命令。"""- if not text:- return- if options & _ETO_GLYPH_INDEX:- playback.warn("glyph_index_text", "glyph-index text was replaced with visible placeholder glyphs")- text = "□" * len(text)- update_current = bool(playback.state.text_align & _TA_UPDATECP)- logical_origin = playback.state.current_position if update_current else reference- origin = playback.map_point(logical_origin)- positions: list[Point] = []- advance_end: Point | None = None- font = playback.state.font- if advances:- cursor_x, cursor_y = logical_origin- for index, _character in enumerate(text):- positions.append(playback.map_point((cursor_x, cursor_y)))- if index < len(advances):- cursor_x += advances[index][0]- cursor_y += advances[index][1]- advance_end = playback.map_point((cursor_x, cursor_y))- if update_current:- playback.state.current_position = (cursor_x, cursor_y)- elif update_current:- advance = measure_text_advance(font, text)- angle = radians(font.escapement / 10.0)- playback.state.current_position = (- logical_origin[0] + advance * cos(angle),- logical_origin[1] - advance * sin(angle),- )- mapped_height = vector_length(playback.map_vector((0.0, font.height or -12.0)))- baseline_vector = playback.map_vector((1.0, 0.0))- rotation = degrees(atan2(baseline_vector[1], baseline_vector[0])) + font.escapement / 10.0- mapped_bounds: Rect | None = None- if bounds is not None and (options & (_ETO_OPAQUE | _ETO_CLIPPED)):- corners = [- playback.map_point((bounds.left, bounds.top)),- playback.map_point((bounds.right, bounds.top)),- playback.map_point((bounds.right, bounds.bottom)),- playback.map_point((bounds.left, bounds.bottom)),- ]- mapped_bounds = Rect(- min(point[0] for point in corners),- min(point[1] for point in corners),- max(point[0] for point in corners),- max(point[1] for point in corners),- )- clip = playback.state.clip- if mapped_bounds is not None and options & _ETO_CLIPPED:- clip = playback.clip_with_operation(ClipOperation(rectangle_path(mapped_bounds), "and"))- playback.append_command(- DrawTextCommand(- text=text,- origin=origin,- positions=tuple(positions),- font=font,- font_height=max(mapped_height, 1.0),- rotation=rotation,- text_align=playback.state.text_align,- color=playback.state.text_color,- background_color=playback.state.background_color,- opaque=bool(options & _ETO_OPAQUE) or playback.state.background_mode == 2,- bounds=mapped_bounds,- clip=clip,- advance_end=advance_end,- )- )---def _append_image_command(- playback: _Playback,- record: BoundedReader,- *,- off_bmi: int,- cb_bmi: int,- off_bits: int,- cb_bits: int,- destination: Rect,- source: Rect | None,- rop: int,- constant_alpha: int = 255,- use_source_alpha: bool = False,-) -> None:- """校验 DIB 子区间并追加统一位图命令。"""- if cb_bmi <= 0 or cb_bits <= 0:- playback.warn("empty_dib", "bitmap record does not contain a DIB header and pixel payload")- return- if rop not in _SUPPORTED_ROP3:- playback.warn("unsupported_rop3", f"unsupported ROP3 will use source-over approximation: {rop:#x}")- if (- cb_bmi > MAX_EMBEDDED_BITMAP_BYTES- or cb_bits > MAX_EMBEDDED_BITMAP_BYTES- or cb_bmi + cb_bits > MAX_EMBEDDED_BITMAP_BYTES- ):- raise MetafileResourceLimitError(f"embedded bitmap exceeds max_embedded_bitmap_bytes={MAX_EMBEDDED_BITMAP_BYTES}")- dib_header = record.bytes(off_bmi, cb_bmi)- bits = record.bytes(off_bits, cb_bits)- corners = (- playback.map_point((destination.left, destination.top)),- playback.map_point((destination.right, destination.top)),- playback.map_point((destination.right, destination.bottom)),- playback.map_point((destination.left, destination.bottom)),- )- playback.append_command(- DrawImageCommand(- dib_header=dib_header,- bits=bits,- destination=corners,- source=source,- rop=rop,- stretch_mode=playback.state.stretch_mode,- constant_alpha=max(0, min(constant_alpha, 255)),- use_source_alpha=use_source_alpha,- clip=playback.state.clip,- )- )---def _play_emf(data: bytes, header: _HeaderInfo, playback: _Playback) -> None:- """按文件顺序验证并回放全部 EMF records。"""- offset = header.record_start- record_index = 0- saw_eof = False- while offset < header.record_end:- if offset + 8 > header.record_end:- raise MetafileMalformedError(f"truncated EMF record header at offset={offset}")- record_type, record_size = struct.unpack_from("<II", data, offset)- record_index += 1- if record_index > MAX_RECORDS:- raise MetafileResourceLimitError(f"EMF exceeds max_records={MAX_RECORDS}")- if record_size < 8 or record_size % 4 or record_size > header.record_end - offset:- raise MetafileMalformedError(f"invalid EMF record size at offset={offset}: {record_size}")- playback.set_record_context(record_type, record_index, offset)- record = BoundedReader(memoryview(data)[offset : offset + record_size], base_offset=offset)- _handle_emf_record(record_type, record, playback)- offset += record_size- if record_type == 14:- saw_eof = True- break- if not saw_eof:- raise MetafileMalformedError("EMF record stream does not contain EMR_EOF")---def _play_wmf(data: bytes, header: _HeaderInfo, playback: _Playback) -> None:- """按文件顺序验证并回放全部 WMF records。"""- offset = header.record_start- record_index = 0- saw_eof = False- while offset < header.record_end:- if offset + 6 > header.record_end:- raise MetafileMalformedError(f"truncated WMF record header at offset={offset}")- size_words = struct.unpack_from("<I", data, offset)[0]- function = struct.unpack_from("<H", data, offset + 4)[0]- record_size = size_words * 2- record_index += 1- if record_index > MAX_RECORDS:- raise MetafileResourceLimitError(f"WMF exceeds max_records={MAX_RECORDS}")- if size_words < 3 or record_size > header.record_end - offset:- raise MetafileMalformedError(f"invalid WMF record size at offset={offset}: words={size_words}")- playback.set_record_context(function, record_index, offset)- payload = BoundedReader(memoryview(data)[offset + 6 : offset + record_size], base_offset=offset + 6)- _handle_wmf_record(function, payload, playback)- offset += record_size- if function == 0:- saw_eof = True- break- if not saw_eof:- raise MetafileMalformedError("WMF record stream does not contain META_EOF")---def _handle_emf_poly(record_type: int, record: BoundedReader, playback: _Playback) -> bool:- """处理 EMF 32/16 位折线、多边形与贝塞尔记录。"""- simple_types = {2, 3, 4, 5, 6, 85, 86, 87, 88, 89}- poly_types = {7, 8, 90, 91}- if record_type not in simple_types | poly_types:- return False- compact = record_type >= 85- if record_type in simple_types:- count = record.u32(24)- playback.charge_points(count)- points = _read_emf_points(record, count, 28, compact=compact)- if record_type in {2, 5, 85, 88}:- _emit_polybezier(playback, points, to=record_type in {5, 88})- return True- mapped = [playback.map_point(point) for point in points]- if record_type in {6, 89}:- playback.polyline_to(points)- return True- playback.emit_path(- _path_from_device_points(mapped, close=record_type in {3, 86}),- stroke=True,- fill=record_type in {3, 86},- )- return True-- polygon_count = record.u32(24)- total_count = record.u32(28)- if polygon_count > MAX_POINTS_PER_RECORD or polygon_count > record.remaining(32) // 4:- raise MetafileMalformedError(f"EMF polygon count array exceeds record boundary: count={polygon_count}")- counts = [record.u32(32 + index * 4) for index in range(polygon_count)]- if sum(counts) != total_count:- raise MetafileMalformedError("EMF poly-polygon counts do not equal total point count")- playback.charge_points(total_count)- points_offset = 32 + polygon_count * 4- points = _read_emf_points(record, total_count, points_offset, compact=compact)- builder = PathBuilder()- cursor = 0- close = record_type in {8, 91}- for count in counts:- mapped = [playback.map_point(point) for point in points[cursor : cursor + count]]- builder.extend(_path_from_device_points(mapped, close=close))- cursor += count- playback.emit_path(builder.build(), stroke=True, fill=close)- return True---def _handle_emf_record(record_type: int, record: BoundedReader, playback: _Playback) -> None:- """分派并执行单条 EMF record,未知绘图记录按规范跳过。"""- if record_type in {1, 14, 70}:- return- if _handle_emf_poly(record_type, record, playback):- return-- if record_type == 9:- playback.state.window_extent = float(record.i32(8)), float(record.i32(12))- return- if record_type == 10:- playback.state.window_origin = float(record.i32(8)), float(record.i32(12))- return- if record_type == 11:- playback.state.viewport_extent = float(record.i32(8)), float(record.i32(12))- return- if record_type == 12:- playback.state.viewport_origin = float(record.i32(8)), float(record.i32(12))- return- if record_type == 13:- playback.state.brush_origin = float(record.i32(8)), float(record.i32(12))- return- if record_type == 17:- playback.state.map_mode = record.i32(8)- return- if record_type == 18:- playback.state.background_mode = record.u32(8)- return- if record_type == 19:- playback.state.polygon_fill_mode = record.u32(8)- return- if record_type == 20:- rop2 = record.u32(8)- if not 1 <= rop2 <= 16:- playback.warn("unsupported_rop2", f"invalid ROP2 will use COPYPEN approximation: {rop2}")- rop2 = 13- playback.state.rop2 = rop2- return- if record_type == 21:- playback.state.stretch_mode = record.u32(8)- return- if record_type == 22:- playback.state.text_align = record.u32(8)- return- if record_type == 24:- playback.state.text_color = _parse_color(record.u32(8))- return- if record_type == 25:- playback.state.background_color = _parse_color(record.u32(8))- return- if record_type == 26:- offset = playback.map_vector((float(record.i32(8)), float(record.i32(12))))- translation = Matrix(e=offset[0], f=offset[1])- playback.state.clip = tuple(- replace(operation, path=transform_path(operation.path, translation)) for operation in playback.state.clip- )- return- if record_type == 27:- point = float(record.i32(8)), float(record.i32(12))- playback.move_to(point)- return- if record_type == 28:- playback.reset_clip()- return- if record_type in {29, 30}:- logical = _parse_rect_i32(record, 8)- mapped = transform_path(rectangle_path(logical), playback.logical_matrix())- playback.add_clip(mapped, _RGN_DIFF if record_type == 29 else _RGN_AND)- return- if record_type in {31, 32}:- x_num, x_den = record.i32(8), record.i32(12)- y_num, y_den = record.i32(16), record.i32(20)- if x_den == 0 or y_den == 0:- playback.warn("zero_scale_denominator", "viewport/window scale record has a zero denominator")- return- if record_type == 31:- width, height = playback.state.viewport_extent- playback.state.viewport_extent = width * x_num / x_den, height * y_num / y_den- else:- width, height = playback.state.window_extent- playback.state.window_extent = width * x_num / x_den, height * y_num / y_den- return- if record_type == 33:- playback.save_dc()- return- if record_type == 34:- playback.restore_dc(record.i32(8))- return- if record_type == 35:- playback.state.world_transform = _parse_xform(record, 8)- return- if record_type == 36:- transform = _parse_xform(record, 8)- mode = record.u32(32)- if mode == 1:- playback.state.world_transform = Matrix()- elif mode == 2:- playback.state.world_transform = playback.state.world_transform.then(transform)- elif mode == 3:- playback.state.world_transform = transform.then(playback.state.world_transform)- elif mode == 4:- playback.state.world_transform = transform- else:- playback.warn("unsupported_transform_mode", f"unsupported ModifyWorldTransform mode: {mode}")- return- if record_type == 37:- playback.select_emf_handle(record.u32(8))- return- if record_type == 38:- handle = record.u32(8)- _validate_emf_handle(handle)- playback.emf_objects[handle] = _make_pen(record.u32(12), float(record.i32(16)), record.u32(24))- return- if record_type == 39:- handle = record.u32(8)- _validate_emf_handle(handle)- playback.emf_objects[handle] = _make_brush(record.u32(12), record.u32(16), record.u32(20))- return- if record_type == 40:- playback.emf_objects.pop(record.u32(8), None)- return- if record_type == 57:- playback.state.arc_direction = record.u32(8)- return- if record_type == 58:- value = record.f32(8)- if isfinite(value) and value > 0:- playback.state.miter_limit = value- else:- playback.warn("invalid_miter_limit", f"invalid miter limit: {value}")- return-- if record_type == 15:- point = playback.map_point((float(record.i32(8)), float(record.i32(12))))- color = _parse_color(record.u32(16))- playback.append_command(- DrawPathCommand(- path=rectangle_path(Rect(point[0], point[1], point[0] + 1.0, point[1] + 1.0)),- pen=Pen(null=True),- brush=Brush(color=color),- stroke=False,- fill=True,- fill_rule="evenodd",- clip=playback.state.clip,- rop2=13,- )- )- return- if record_type == 54:- endpoint = float(record.i32(8)), float(record.i32(12))- playback.line_to(endpoint)- return- if record_type in {42, 43, 44}:- rect = _parse_rect_i32(record, 8)- if record_type == 42:- path = ellipse_path(rect)- elif record_type == 44:- path = round_rectangle_path(rect, abs(record.i32(24)) / 2.0, abs(record.i32(28)) / 2.0)- else:- path = rectangle_path(rect)- playback.emit_logical_path(path, stroke=True, fill=True)- return- if record_type in {45, 46, 47, 55}:- rect = _parse_rect_i32(record, 8)- start = float(record.i32(24)), float(record.i32(28))- end = float(record.i32(32)), float(record.i32(36))- close_mode = "chord" if record_type == 46 else "pie" if record_type == 47 else "open"- path = arc_path(rect, start, end, direction=playback.state.arc_direction, close_mode=close_mode)- if record_type == 55:- playback.connected_arc(path)- else:- playback.emit_logical_path(path, stroke=True, fill=close_mode != "open")- return- if record_type == 41:- center = float(record.i32(8)), float(record.i32(12))- radius = abs(float(record.u32(16)))- start_angle = record.f32(20)- sweep_angle = record.f32(24)- from math import cos, radians, sin-- start = (- center[0] + radius * cos(radians(start_angle)),- center[1] - radius * sin(radians(start_angle)),- )- end_angle = start_angle + sweep_angle- end = (- center[0] + radius * cos(radians(end_angle)),- center[1] - radius * sin(radians(end_angle)),- )- direction = 1 if sweep_angle >= 0 else 2- playback.connected_arc(- arc_path(- Rect(center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius),- start,- end,- direction=direction,- ),- )- return-- if record_type == 59:- playback.begin_path()- return- if record_type == 60:- playback.end_path()- return- if record_type == 61:- if playback.path_active and playback.path_builder.figure_open:- playback.path_builder.close()- else:- playback.warn("close_figure_without_path", "CloseFigure ignored without an active path")- return- if record_type in {62, 63, 64}:- path = playback.consume_path()- if record_type == 63:- path = close_open_subpaths(path)- playback.emit_path(path, stroke=record_type in {63, 64}, fill=record_type in {62, 63})- return- if record_type == 67:- path = playback.consume_path()- if path.segments:- playback.add_clip(path, record.u32(8))- return- if record_type == 68:- playback.path_builder.clear()- playback.path_active = False- playback.path_ready = False- return-- if record_type == 75:- _handle_emf_region_clip(record, playback)- return- if record_type in {76, 77, 80, 81, 114}:- _handle_emf_bitmap(record_type, record, playback)- return- if record_type == 82:- handle = record.u32(8)- _validate_emf_handle(handle)- playback.emf_objects[handle] = _parse_emf_font(record)- return- if record_type in {83, 84}:- _handle_emf_text(record_type, record, playback)- return- if record_type == 94:- handle = record.u32(8)- _validate_emf_handle(handle)- cb_bmi, cb_bits = record.u32(20), record.u32(28)- pattern = b""- if cb_bmi + cb_bits <= MAX_EMBEDDED_BITMAP_BYTES:- pattern = record.bytes(record.u32(16), cb_bmi) + record.bytes(record.u32(24), cb_bits)- playback.emf_objects[handle] = Brush(kind="pattern", pattern=pattern)- playback.warn("pattern_brush_approximation", "DIB pattern brush will use a solid-color approximation")- return- if record_type == 95:- handle = record.u32(8)- _validate_emf_handle(handle)- style = record.u32(28)- width = float(record.u32(32))- pen = _make_pen(style, width, record.u32(40), extended=True)- style_count = record.u32(48)- if style_count and style_count <= record.remaining(52) // 4:- dashes = tuple(max(1.0, float(record.u32(52 + index * 4))) for index in range(style_count))- pen = replace(pen, dashes=dashes)- playback.emf_objects[handle] = pen- return- if record_type == 120:- playback.state.brush = replace(playback.state.brush, color=_parse_color(record.u32(8)))- return- if record_type == 121:- playback.state.pen = replace(playback.state.pen, color=_parse_color(record.u32(8)))- return-- harmless_state_records = {- 16,- 23,- 48,- 49,- 50,- 51,- 52,- 98,- 99,- 100,- 101,- 104,- 107,- 109,- 110,- 111,- 112,- 113,- 115,- 117,- 119,- }- if record_type in harmless_state_records:- playback.warn("ignored_state_record", f"EMF state/control record was ignored: {record_type}", partial=False)- return- playback.warn("unsupported_emf_record", f"unsupported EMF record was skipped: {record_type}")---def _validate_emf_handle(handle: int) -> None:- """拒绝保留 handle、stock handle 和超出固定对象预算的值。"""- if handle == 0 or handle & 0x80000000 or handle > MAX_OBJECTS:- raise MetafileResourceLimitError(f"invalid or excessive EMF object handle: {handle}")---def _handle_emf_region_clip(record: BoundedReader, playback: _Playback) -> None:- """解析 EMR_EXTSELECTCLIPRGN 的矩形 region 数据。"""- data_size = record.u32(8)- mode = record.u32(12)- if data_size == 0:- if mode == _RGN_COPY:- playback.reset_clip()- else:- playback.warn("empty_clip_region", f"empty clip region used with combine mode {mode}")- return- if data_size > record.remaining(16) or data_size < 32:- raise MetafileMalformedError(f"EMF region data exceeds record boundary: size={data_size}")- region = record.subreader(16, data_size)- header_size = region.u32(0)- region_type = region.u32(4)- rectangle_count = region.u32(8)- region_bytes = region.u32(12)- if header_size < 32 or region_type != 1:- raise MetafileMalformedError("EMF region header is invalid")- if rectangle_count > MAX_POINTS_PER_RECORD or region_bytes > region.remaining(header_size):- raise MetafileMalformedError("EMF region rectangle data exceeds its declared boundary")- if rectangle_count > region.remaining(header_size) // 16:- raise MetafileMalformedError("EMF region rectangle count exceeds record boundary")- playback.charge_points(rectangle_count * 4)- builder = PathBuilder()- for index in range(rectangle_count):- rect = _parse_rect_i32(region, header_size + index * 16)- builder.extend(transform_path(rectangle_path(rect), playback.logical_matrix()))- path = builder.build()- if path.segments:- playback.add_clip(path, mode)---def _handle_emf_bitmap(record_type: int, record: BoundedReader, playback: _Playback) -> None:- """解析常见 EMF DIB、BitBlt、StretchBlt 与 AlphaBlend 记录。"""- if record_type in {76, 77}:- destination = Rect(- float(record.i32(24)),- float(record.i32(28)),- float(record.i32(24) + record.i32(32)),- float(record.i32(28) + record.i32(36)),- )- source_width = record.i32(100) if record_type == 77 and len(record) >= 108 else record.i32(32)- source_height = record.i32(104) if record_type == 77 and len(record) >= 108 else record.i32(36)- source = Rect(- float(record.i32(44)),- float(record.i32(48)),- float(record.i32(44) + source_width),- float(record.i32(48) + source_height),- )- _append_image_command(- playback,- record,- off_bmi=record.u32(84),- cb_bmi=record.u32(88),- off_bits=record.u32(92),- cb_bits=record.u32(96),- destination=destination,- source=source,- rop=record.u32(40),- )- return- if record_type == 81:- destination = Rect(- float(record.i32(24)),- float(record.i32(28)),- float(record.i32(24) + record.i32(72)),- float(record.i32(28) + record.i32(76)),- )- source = Rect(- float(record.i32(32)),- float(record.i32(36)),- float(record.i32(32) + record.i32(40)),- float(record.i32(36) + record.i32(44)),- )- _append_image_command(- playback,- record,- off_bmi=record.u32(48),- cb_bmi=record.u32(52),- off_bits=record.u32(56),- cb_bits=record.u32(60),- destination=destination,- source=source,- rop=record.u32(68),- )- return- if record_type == 80:- width, height = record.i32(40), record.i32(44)- destination = Rect(- float(record.i32(24)),- float(record.i32(28)),- float(record.i32(24) + width),- float(record.i32(28) + height),- )- source = Rect(- float(record.i32(32)),- float(record.i32(36)),- float(record.i32(32) + width),- float(record.i32(36) + height),- )- _append_image_command(- playback,- record,- off_bmi=record.u32(48),- cb_bmi=record.u32(52),- off_bits=record.u32(56),- cb_bits=record.u32(60),- destination=destination,- source=source,- rop=_SRCCOPY,- )- return- destination = Rect(- float(record.i32(24)),- float(record.i32(28)),- float(record.i32(24) + record.i32(32)),- float(record.i32(28) + record.i32(36)),- )- source = Rect(- float(record.i32(44)),- float(record.i32(48)),- float(record.i32(44) + record.i32(100)),- float(record.i32(48) + record.i32(104)),- )- _append_image_command(- playback,- record,- off_bmi=record.u32(84),- cb_bmi=record.u32(88),- off_bits=record.u32(92),- cb_bits=record.u32(96),- destination=destination,- source=source,- rop=_SRCCOPY,- constant_alpha=record.u8(42),- use_source_alpha=bool(record.u8(43) & 1),- )---def _handle_emf_text(record_type: int, record: BoundedReader, playback: _Playback) -> None:- """解析 EMR_EXTTEXTOUTA/W 文字、bounds 与显式 advance。"""- if len(record) < 76:- raise MetafileMalformedError("EMF ExtTextOut record is truncated")- reference = float(record.i32(36)), float(record.i32(40))- character_count = record.u32(44)- if character_count > MAX_POINTS_PER_RECORD:- raise MetafileResourceLimitError(f"EMF text exceeds max characters={MAX_POINTS_PER_RECORD}")- string_offset = record.u32(48)- options = record.u32(52)- bounds = _parse_rect_i32(record, 56)- dx_offset = record.u32(72)- char_bytes = 2 if record_type == 84 else 1- raw = record.bytes(string_offset, character_count * char_bytes)- text = (- raw.decode("utf-16le", errors="replace") if record_type == 84 else _decode_ansi_text(raw, playback.state.font.charset)- )- advances: list[Point] | None = None- if dx_offset:- values_per_character = 2 if options & _ETO_PDY else 1- value_count = character_count * values_per_character- if value_count > record.remaining(dx_offset) // 4:- raise MetafileMalformedError("EMF ExtTextOut advance array exceeds record boundary")- advances = []- for index in range(character_count):- dx = float(record.i32(dx_offset + index * values_per_character * 4))- dy = float(record.i32(dx_offset + (index * values_per_character + 1) * 4)) if values_per_character == 2 else 0.0- advances.append((dx, dy))- playback.charge_points(character_count)- _emit_text(- playback,- text=text,- reference=reference,- options=options,- bounds=bounds,- advances=advances,- )---def _handle_wmf_record(function: int, payload: BoundedReader, playback: _Playback) -> None:- """分派并执行单条 WMF record,未知绘图记录按规范跳过。"""- if function == 0:- return- if function == 0x0201:- playback.state.background_color = _parse_color(payload.u32(0))- return- if function == 0x0102:- playback.state.background_mode = payload.u16(0)- return- if function == 0x0103:- playback.state.map_mode = payload.i16(0)- return- if function == 0x0104:- rop2 = payload.u16(0)- if not 1 <= rop2 <= 16:- playback.warn("unsupported_rop2", f"invalid WMF ROP2 will use COPYPEN approximation: {rop2}")- rop2 = 13- playback.state.rop2 = rop2- return- if function == 0x0106:- playback.state.polygon_fill_mode = payload.u16(0)- return- if function == 0x0107:- playback.state.stretch_mode = payload.u16(0)- return- if function == 0x0209:- playback.state.text_color = _parse_color(payload.u32(0))- return- if function == 0x020B:- playback.state.window_origin = float(payload.i16(2)), float(payload.i16(0))- return- if function == 0x020C:- playback.state.window_extent = float(payload.i16(2)), float(payload.i16(0))- return- if function == 0x020D:- playback.state.viewport_origin = float(payload.i16(2)), float(payload.i16(0))- return- if function == 0x020E:- playback.state.viewport_extent = float(payload.i16(2)), float(payload.i16(0))- return- if function == 0x020F:- x, y = playback.state.window_origin- playback.state.window_origin = x + payload.i16(2), y + payload.i16(0)- return- if function == 0x0211:- x, y = playback.state.viewport_origin- playback.state.viewport_origin = x + payload.i16(2), y + payload.i16(0)- return- if function in {0x0410, 0x0412}:- y_num, y_den, x_num, x_den = payload.i16(0), payload.i16(2), payload.i16(4), payload.i16(6)- if x_den == 0 or y_den == 0:- playback.warn("zero_scale_denominator", "WMF viewport/window scale record has a zero denominator")- return- if function == 0x0410:- width, height = playback.state.window_extent- playback.state.window_extent = width * x_num / x_den, height * y_num / y_den- else:- width, height = playback.state.viewport_extent- playback.state.viewport_extent = width * x_num / x_den, height * y_num / y_den- return- if function == 0x001E:- playback.save_dc()- return- if function == 0x0127:- playback.restore_dc(payload.i16(0))- return- if function == 0x012E:- playback.state.text_align = payload.u16(0)- return- if function == 0x012D:- playback.select_wmf_handle(payload.u16(0))- return- if function == 0x01F0:- handle = payload.u16(0)- if handle < len(playback.wmf_objects):- playback.wmf_objects[handle] = None- return- if function == 0x02FA:- playback.create_wmf_object(_make_pen(payload.u16(0), float(payload.i16(2)), payload.u32(6)))- return- if function == 0x02FC:- playback.create_wmf_object(_make_brush(payload.u16(0), payload.u32(2), payload.u16(6)))- return- if function == 0x02FB:- playback.create_wmf_object(_parse_wmf_font(payload))- return-- if function == 0x0214:- point = float(payload.i16(2)), float(payload.i16(0))- playback.move_to(point)- return- if function == 0x0213:- endpoint = float(payload.i16(2)), float(payload.i16(0))- playback.line_to(endpoint)- return- if function in {0x0324, 0x0325}:- count = payload.u16(0)- playback.charge_points(count)- points = _read_wmf_points(payload, count, 2)- playback.emit_path(- _path_from_device_points([playback.map_point(point) for point in points], close=function == 0x0324),- stroke=True,- fill=function == 0x0324,- )- return- if function == 0x0538:- polygon_count = payload.u16(0)- if polygon_count > MAX_POINTS_PER_RECORD or polygon_count > payload.remaining(2) // 2:- raise MetafileMalformedError("WMF PolyPolygon count array exceeds record boundary")- counts = [payload.u16(2 + index * 2) for index in range(polygon_count)]- total_count = sum(counts)- playback.charge_points(total_count)- points = _read_wmf_points(payload, total_count, 2 + polygon_count * 2)- builder = PathBuilder()- cursor = 0- for count in counts:- builder.extend(- _path_from_device_points(- [playback.map_point(point) for point in points[cursor : cursor + count]],- close=True,- )- )- cursor += count- playback.emit_path(builder.build(), stroke=True, fill=True)- return- if function == 0x061C:- rect = Rect(float(payload.i16(10)), float(payload.i16(8)), float(payload.i16(6)), float(payload.i16(4)))- path = round_rectangle_path(rect, abs(payload.i16(2)) / 2.0, abs(payload.i16(0)) / 2.0)- playback.emit_logical_path(path, stroke=True, fill=True)- return- if function in {0x0418, 0x041B}:- rect = Rect(float(payload.i16(6)), float(payload.i16(4)), float(payload.i16(2)), float(payload.i16(0)))- if function == 0x0418:- path = ellipse_path(rect)- else:- path = rectangle_path(rect)- playback.emit_logical_path(path, stroke=True, fill=True)- return- if function in {0x0817, 0x081A, 0x0830}:- end = float(payload.i16(2)), float(payload.i16(0))- start = float(payload.i16(6)), float(payload.i16(4))- rect = Rect(float(payload.i16(14)), float(payload.i16(12)), float(payload.i16(10)), float(payload.i16(8)))- close_mode = "pie" if function == 0x081A else "chord" if function == 0x0830 else "open"- playback.emit_logical_path(- arc_path(rect, start, end, direction=2, close_mode=close_mode),- stroke=True,- fill=close_mode != "open",- )- return- if function == 0x041F:- point = playback.map_point((float(payload.i16(6)), float(payload.i16(4))))- color = _parse_color(payload.u32(0))- playback.append_command(- DrawPathCommand(- path=rectangle_path(Rect(point[0], point[1], point[0] + 1.0, point[1] + 1.0)),- pen=Pen(null=True),- brush=Brush(color=color),- stroke=False,- fill=True,- fill_rule="evenodd",- clip=playback.state.clip,- rop2=13,- )- )- return- if function in {0x0415, 0x0416}:- rect = Rect(float(payload.i16(6)), float(payload.i16(4)), float(payload.i16(2)), float(payload.i16(0)))- playback.add_clip(- transform_path(rectangle_path(rect), playback.logical_matrix()),- _RGN_DIFF if function == 0x0415 else _RGN_AND,- )- return-- if function in {0x0521, 0x0A32}:- _handle_wmf_text(function, payload, playback)- return- if function == 0x0F43:- _handle_wmf_stretchdib(payload, playback)- return- if function in {0x0940, 0x0B41}:- playback.warn("unsupported_wmf_dib_record", f"WMF DIB record will be skipped: {function:#x}")- return-- harmless_records = {- 0x0108,- 0x020A,- 0x0231,- 0x0626,- 0x0234,- 0x0035,- 0x0436,- 0x0037,- 0x0139,- }- if function in harmless_records:- playback.warn("ignored_wmf_state_record", f"WMF state/control record was ignored: {function:#x}", partial=False)- return- playback.warn("unsupported_wmf_record", f"unsupported WMF record was skipped: {function:#x}")---def _handle_wmf_text(function: int, payload: BoundedReader, playback: _Playback) -> None:- """解析 WMF TextOut/ExtTextOut 字符串、矩形和 advance。"""- if function == 0x0521:- count = payload.u16(0)- if count > payload.remaining(2):- raise MetafileMalformedError("WMF TextOut string exceeds record boundary")- raw = payload.bytes(2, count)- coordinate_offset = 2 + count + (count & 1)- reference = float(payload.i16(coordinate_offset + 2)), float(payload.i16(coordinate_offset))- playback.charge_points(count)- _emit_text(- playback,- text=_decode_ansi_text(raw, playback.state.font.charset),- reference=reference,- options=0,- bounds=None,- advances=None,- )- return- reference = float(payload.i16(2)), float(payload.i16(0))- count = payload.u16(4)- options = payload.u16(6)- offset = 8- bounds: Rect | None = None- if options & (_ETO_OPAQUE | _ETO_CLIPPED):- bounds = _parse_rect_i16(payload, offset)- offset += 8- if count > payload.remaining(offset):- raise MetafileMalformedError("WMF ExtTextOut string exceeds record boundary")- raw = payload.bytes(offset, count)- offset += count + (count & 1)- advances: list[Point] | None = None- if payload.remaining(offset) >= count * 2:- advances = [(float(payload.i16(offset + index * 2)), 0.0) for index in range(count)]- playback.charge_points(count)- _emit_text(- playback,- text=_decode_ansi_text(raw, playback.state.font.charset),- reference=reference,- options=options,- bounds=bounds,- advances=advances,- )---def _handle_wmf_stretchdib(payload: BoundedReader, playback: _Playback) -> None:- """解析 META_STRETCHDIB 的内联 DIB 与源/目标矩形。"""- if len(payload) < 22:- raise MetafileMalformedError("WMF StretchDIB record is truncated")- rop = payload.u32(0)- source_height, source_width = payload.i16(6), payload.i16(8)- source_y, source_x = payload.i16(10), payload.i16(12)- destination_height, destination_width = payload.i16(14), payload.i16(16)- destination_y, destination_x = payload.i16(18), payload.i16(20)- dib = payload.bytes(22, payload.remaining(22))- if len(dib) < 12:- raise MetafileMalformedError("WMF StretchDIB payload does not contain a DIB header")- header_size = struct.unpack_from("<I", dib, 0)[0]- if header_size < 12 or header_size > len(dib):- raise MetafileMalformedError(f"invalid WMF DIB header size: {header_size}")- bits_offset = _dib_bits_offset(dib)- if bits_offset > len(dib):- raise MetafileMalformedError("WMF DIB pixel offset exceeds record boundary")- header = dib[:bits_offset]- bits = dib[bits_offset:]- corners = (- playback.map_point((float(destination_x), float(destination_y))),- playback.map_point((float(destination_x + destination_width), float(destination_y))),- playback.map_point((float(destination_x + destination_width), float(destination_y + destination_height))),- playback.map_point((float(destination_x), float(destination_y + destination_height))),- )- playback.append_command(- DrawImageCommand(- dib_header=header,- bits=bits,- destination=corners,- source=Rect(- float(source_x),- float(source_y),- float(source_x + source_width),- float(source_y + source_height),- ),- rop=rop,- stretch_mode=playback.state.stretch_mode,- clip=playback.state.clip,- )- )---def _dib_bits_offset(dib: bytes) -> int:- """根据 DIB header、bit depth 和 palette 推导像素起始偏移。"""- reader = BoundedReader(dib)- header_size = reader.u32(0)- if header_size == 12:- bit_count = reader.u16(10)- palette_entries = 1 << bit_count if bit_count <= 8 else 0- return header_size + palette_entries * 3- if header_size < 40:- return header_size- bit_count = reader.u16(14)- compression = reader.u32(16)- colors_used = reader.u32(32)- palette_entries = colors_used or ((1 << bit_count) if bit_count <= 8 else 0)- bitfields = 12 if compression == 3 and header_size == 40 else 16 if compression == 6 and header_size == 40 else 0- return header_size + bitfields + palette_entries * 4---__all__ = ["parse_metafile"]diff --git a/mineru/model/flash/office/metafile/render.py b/mineru/model/flash/office/metafile/render.pydeleted file mode 100644index 146af63b..00000000--- a/mineru/model/flash/office/metafile/render.py+++ /dev/null@@ -1,1143 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""统一 WMF/EMF 图元文档的 Pillow 与安全 SVG 后端。"""--from __future__ import annotations--import base64-from html import escape-from io import BytesIO-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-from .models import (- Brush,- ClipOperation,- ClipStack,- Color,- DrawImageCommand,- DrawPathCommand,- DrawTextCommand,- GraphicsPath,- Matrix,- MetafileDocument,- MetafileMalformedError,- MetafileOutputFormat,- MetafileResourceLimitError,- Pen,- Point,- Rect,-)---_SRCCOPY = 0x00CC0020-_SRCAND = 0x008800C6-_SRCPAINT = 0x00EE0086-_SRCINVERT = 0x00660046-_DSTINVERT = 0x00550009-_BLACKNESS = 0x00000042-_WHITENESS = 0x00FF0062--_TA_RIGHT = 0x0002-_TA_CENTER = 0x0006-_TA_BOTTOM = 0x0008-_TA_BASELINE = 0x0018--_CLIPPER_SCALE = 256-_CLIPPER_COORD_LIMIT = (1 << 61) / _CLIPPER_SCALE---def _document_matrix(document: MetafileDocument, *, raster_scale: int = 1) -> Matrix:- """把统一 device 坐标映射到最终输出像素。"""- bounds = document.bounds.normalized()- scale_x = document.width * raster_scale / bounds.width- scale_y = document.height * raster_scale / bounds.height- return Matrix(a=scale_x, d=scale_y, e=-bounds.left * scale_x, f=-bounds.top * scale_y)---def _mapped_rect(rect: Rect, matrix: Matrix) -> Rect:- """把矩形四角变换后返回轴对齐像素包围盒。"""- corners = [- matrix.transform_point((rect.left, rect.top)),- matrix.transform_point((rect.right, rect.top)),- matrix.transform_point((rect.right, rect.bottom)),- matrix.transform_point((rect.left, rect.bottom)),- ]- return Rect(- min(point[0] for point in corners),- min(point[1] for point in corners),- max(point[0] for point in corners),- max(point[1] for point in corners),- )---def _dib_to_bmp(command: DrawImageCommand) -> bytes:- """为分离的 DIB header 和像素数据补齐 BMP 文件头。"""- if len(command.dib_header) < 4:- raise MetafileMalformedError("DIB header is truncated")- pixel_offset = 14 + len(command.dib_header)- total_size = pixel_offset + len(command.bits)- if total_size > MAX_EMBEDDED_BITMAP_BYTES + 14:- raise MetafileResourceLimitError("decoded BMP exceeds the embedded bitmap byte budget")- import struct-- return b"BM" + struct.pack("<IHHI", total_size, 0, 0, pixel_offset) + command.dib_header + command.bits---def _decode_raw_alpha_dib(command: DrawImageCommand) -> Image.Image | None:- """对 AC_SRC_ALPHA 的常见 32 位 DIB 保留原始 alpha 字节。"""- header = command.dib_header- if len(header) < 40:- return None- import struct-- header_size, width, signed_height = struct.unpack_from("<Iii", header, 0)- bit_count = struct.unpack_from("<H", header, 14)[0]- compression = struct.unpack_from("<I", header, 16)[0]- if header_size < 40 or width <= 0 or signed_height == 0 or bit_count != 32 or compression not in {0, 3, 6}:- return None- height = abs(signed_height)- if width * height > MAX_CANVAS_PIXELS or len(command.bits) < width * height * 4:- raise MetafileResourceLimitError("32-bit DIB exceeds pixel budget or is truncated")- orientation = -1 if signed_height > 0 else 1- try:- premultiplied = Image.frombytes(- "RGBa",- (width, height),- command.bits[: width * height * 4],- "raw",- "BGRa",- width * 4,- orientation,- )- return premultiplied.convert("RGBA")- except (OSError, ValueError) as exc:- raise MetafileMalformedError("32-bit DIB alpha payload cannot be decoded") from exc---def _validate_dib_dimensions(header: bytes) -> None:- """在进入 Pillow decoder 前验证 DIB 声明尺寸与固定像素预算。"""- if len(header) < 12:- raise MetafileMalformedError("DIB header is truncated")- import struct-- header_size = struct.unpack_from("<I", header, 0)[0]- if header_size == 12:- width, height = struct.unpack_from("<HH", header, 4)- elif header_size >= 40 and len(header) >= 40:- width, signed_height = struct.unpack_from("<ii", header, 4)- height = abs(signed_height)- else:- raise MetafileMalformedError(f"unsupported or truncated DIB header size: {header_size}")- if width <= 0 or height <= 0 or width * height > MAX_CANVAS_PIXELS:- raise MetafileResourceLimitError(f"DIB dimensions exceed pixel budget: {width}x{height}")---def _decode_dib(command: DrawImageCommand) -> Image.Image:- """严格解码 DIB,并在需要时恢复源 alpha。"""- _validate_dib_dimensions(command.dib_header)- if command.use_source_alpha:- raw_alpha = _decode_raw_alpha_dib(command)- if raw_alpha is not None:- return raw_alpha- try:- with Image.open(BytesIO(_dib_to_bmp(command))) as image:- width, height = image.size- if width <= 0 or height <= 0 or width * height > MAX_CANVAS_PIXELS:- raise MetafileResourceLimitError(f"DIB dimensions exceed pixel budget: {width}x{height}")- image.load()- decoded = image.convert("RGBA")- except MetafileResourceLimitError:- raise- except (Image.DecompressionBombError, UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:- raise MetafileMalformedError("embedded DIB cannot be decoded by Pillow") from exc- if not command.use_source_alpha:- decoded.putalpha(255)- return decoded---def _clipper_paths(subpaths: list[tuple[list[Point], bool]]) -> list[list[tuple[int, int]]]:- """把浮点子路径量化为 Clipper 闭合轮廓并过滤退化输入。"""- result: list[list[tuple[int, int]]] = []- for points, _closed in subpaths:- converted: list[tuple[int, int]] = []- for x, y in points:- if abs(x) > _CLIPPER_COORD_LIMIT or abs(y) > _CLIPPER_COORD_LIMIT:- raise MetafileResourceLimitError("flattened path coordinate exceeds Clipper range")- point = round(x * _CLIPPER_SCALE), round(y * _CLIPPER_SCALE)- if not converted or converted[-1] != point:- converted.append(point)- if converted and converted[0] == converted[-1]:- converted.pop()- if len(converted) >= 3:- result.append(converted)- return result---def _paint_polytree(mask: Image.Image, tree: pyclipper.PyPolyNode, budget: FlattenBudget | None = None) -> None:- """按 PolyTree 层级依次绘制外轮廓、孔洞和孔洞中的岛。"""- draw = ImageDraw.Draw(mask)- 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(- path: GraphicsPath,- matrix: Matrix,- size: tuple[int, int],- fill_rule: str,- budget: FlattenBudget | None = None,-) -> Image.Image:- """按 GDI winding/alternate 规则把复合路径转换为 L 模式 mask。"""- transformed = transform_path(path, matrix)- subpaths = flatten_path(transformed, budget=budget)- mask = Image.new("L", size, 0)- paths = _clipper_paths(subpaths)- if not paths:- return mask- fill_type = pyclipper.PFT_EVENODD if fill_rule == "evenodd" else pyclipper.PFT_NONZERO- try:- clipper = pyclipper.Pyclipper()- clipper.AddPaths(paths, pyclipper.PT_SUBJECT, True)- tree = clipper.Execute2(pyclipper.CT_UNION, fill_type, fill_type)- except pyclipper.ClipperException as exc:- raise MetafileMalformedError("compound path cannot be resolved") from exc- _paint_polytree(mask, tree, budget)- return mask---def _clip_mask(- clip: ClipStack,- matrix: Matrix,- size: tuple[int, int],- budget: FlattenBudget | None = None,-) -> Image.Image | None:- """按 GDI combine mode 顺序合成最终裁剪 mask。"""- if not clip:- return None- current = Image.new("L", size, 255)- for operation in clip:- incoming = _path_mask(operation.path, matrix, size, operation.fill_rule, budget)- if operation.mode == "copy":- current = incoming- elif operation.mode == "and":- current = ImageChops.multiply(current, incoming)- elif operation.mode == "or":- current = ImageChops.lighter(current, incoming)- elif operation.mode == "xor":- current = ImageChops.logical_xor(current.convert("1"), incoming.convert("1")).convert("L")- else:- current = ImageChops.subtract(current, incoming)- return current---def _apply_clip(layer: Image.Image, clip: ClipStack, matrix: Matrix, budget: FlattenBudget | None = None) -> None:- """把命令级裁剪 mask 乘入 RGBA layer 的 alpha 通道。"""- mask = _clip_mask(clip, matrix, layer.size, budget)- if mask is None:- return- alpha = layer.getchannel("A")- layer.putalpha(ImageChops.multiply(alpha, mask))---def _hatch_layer(size: tuple[int, int], brush: Brush) -> Image.Image:- """为常见 GDI hatch brush 生成确定性 RGBA 图案层。"""- layer = Image.new("RGBA", size, (0, 0, 0, 0))- draw = ImageDraw.Draw(layer)- color = brush.color.rgba()- spacing = 8- width, height = size- if brush.hatch in {0, 4, 5}:- for y in range(0, height + spacing, spacing):- draw.line((0, y, width, y), fill=color)- if brush.hatch in {1, 4, 5}:- for x in range(0, width + spacing, spacing):- draw.line((x, 0, x, height), fill=color)- if brush.hatch in {2, 4}:- for offset in range(-height, width + height, spacing):- draw.line((offset, 0, offset + height, height), fill=color)- if brush.hatch in {3, 5}:- for offset in range(0, width + height * 2, spacing):- draw.line((offset, 0, offset - height, height), fill=color)- return layer---def _dash_polyline(- points: list[Point],- *,- dashes: tuple[float, ...],- closed: bool,-) -> list[list[Point]]:- """按连续路径长度把折线切分为需要描绘的 dash 子段。"""- if len(points) < 2:- return []- if not dashes:- return [points]- pattern = tuple(max(0.5, value) for value in dashes)- pattern_index = 0- pattern_remaining = pattern[0]- drawing = True- visible: list[list[Point]] = []- current: list[Point] | None = None- for start, end in zip(points, points[1:]):- delta_x, delta_y = end[0] - start[0], end[1] - start[1]- length = hypot(delta_x, delta_y)- if length <= 1e-9:- continue- consumed = 0.0- while consumed < length:- advance = min(pattern_remaining, length - consumed)- if drawing and advance > 0:- first = (- start[0] + delta_x * consumed / length,- start[1] + delta_y * consumed / length,- )- second = (- start[0] + delta_x * (consumed + advance) / length,- start[1] + delta_y * (consumed + advance) / length,- )- if current is None:- current = [first]- elif current[-1] != first:- current.append(first)- current.append(second)- consumed += advance- pattern_remaining -= advance- if pattern_remaining <= 1e-9:- if drawing and current is not None:- visible.append(current)- current = None- pattern_index = (pattern_index + 1) % len(pattern)- pattern_remaining = pattern[pattern_index]- drawing = not drawing- if current is not None:- visible.append(current)- if closed and len(visible) > 1 and visible[0][0] == points[0] and visible[-1][-1] == points[-1]:- visible[0] = [*visible[-1][:-1], *visible[0]]- visible.pop()- return visible---def _quantize_stroke_path(points: list[Point], *, closed: bool) -> list[tuple[int, int]]:- """把描边折线量化为 Clipper 坐标并移除重复端点。"""- converted: list[tuple[int, int]] = []- for x, y in points:- if abs(x) > _CLIPPER_COORD_LIMIT or abs(y) > _CLIPPER_COORD_LIMIT:- raise MetafileResourceLimitError("stroke coordinate exceeds Clipper range")- point = round(x * _CLIPPER_SCALE), round(y * _CLIPPER_SCALE)- if not converted or converted[-1] != point:- converted.append(point)- if closed and len(converted) > 1 and converted[0] == converted[-1]:- converted.pop()- return converted---def _offset_stroke_path(- points: list[Point],- *,- closed: bool,- width: float,- pen: Pen,- miter_limit: float,- size: tuple[int, int],- budget: FlattenBudget,-) -> Image.Image:- """把单条折线扩张成遵守 GDI cap、join 和 miter limit 的描边 mask。"""- mask = Image.new("L", size, 0)- converted = _quantize_stroke_path(points, closed=closed)- if len(converted) < (3 if closed else 2):- return mask- join_type = {- "round": pyclipper.JT_ROUND,- "bevel": pyclipper.JT_SQUARE,- "miter": pyclipper.JT_MITER,- }[pen.join]- end_type = (- pyclipper.ET_CLOSEDLINE- if closed- else {- "round": pyclipper.ET_OPENROUND,- "square": pyclipper.ET_OPENSQUARE,- "flat": pyclipper.ET_OPENBUTT,- }[pen.cap]- )- try:- offset = pyclipper.PyclipperOffset(max(miter_limit, 1.0), _CLIPPER_SCALE * 0.1)- offset.AddPath(converted, join_type, end_type)- tree = offset.Execute2(max(width, 1.0) * _CLIPPER_SCALE / 2.0)- except pyclipper.ClipperException as exc:- raise MetafileMalformedError("stroke path cannot be widened") from exc- _paint_polytree(mask, tree, budget)- return mask---def _stroke_mask(- subpaths: list[tuple[list[Point], bool]],- *,- size: tuple[int, int],- width: float,- pen: Pen,- dashes: tuple[float, ...],- miter_limit: float,- budget: FlattenBudget,-) -> Image.Image:- """把全部描边子路径合成为统一 L 模式覆盖 mask。"""- mask = Image.new("L", size, 0)- for points, closed in subpaths:- visible = _dash_polyline(points, dashes=dashes, closed=closed)- for segment in visible:- segment_closed = closed and not dashes- current = _offset_stroke_path(- segment,- closed=segment_closed,- width=width,- pen=pen,- miter_limit=miter_limit,- size=size,- budget=budget,- )- mask = ImageChops.lighter(mask, current)- return mask---def _render_path_command(- command: DrawPathCommand,- matrix: Matrix,- size: tuple[int, int],- raster_scale: int,- budget: FlattenBudget,-) -> Image.Image:- """把单条路径命令绘制到独立透明 RGBA layer。"""- layer = Image.new("RGBA", size, (0, 0, 0, 0))- transformed = transform_path(command.path, matrix)- subpaths = flatten_path(transformed, budget=budget)- if command.fill and command.brush.kind != "null":- fill_mask = _path_mask(command.path, matrix, size, command.fill_rule, budget)- if command.brush.kind == "hatch":- fill_layer = _hatch_layer(size, command.brush)- fill_layer.putalpha(ImageChops.multiply(fill_layer.getchannel("A"), fill_mask))- else:- fill_layer = Image.new("RGBA", size, command.brush.color.rgba())- fill_layer.putalpha(ImageChops.multiply(fill_layer.getchannel("A"), fill_mask))- layer.alpha_composite(fill_layer)- if command.stroke and not command.pen.null:- scale = (abs(matrix.a) + abs(matrix.d)) / 2.0- pen_width = command.pen.width * raster_scale if command.pen.cosmetic else command.pen.width * max(scale, 1e-9)- width = max(1.0, min(pen_width, max(size) * 2.0))- dash_scale = raster_scale if command.pen.cosmetic else scale- stroke_mask = _stroke_mask(- subpaths,- size=size,- width=width,- pen=command.pen,- dashes=tuple(value * dash_scale for value in command.pen.dashes),- miter_limit=command.miter_limit,- budget=budget,- )- stroke_layer = Image.new("RGBA", size, command.pen.color.rgba())- stroke_layer.putalpha(ImageChops.multiply(stroke_layer.getchannel("A"), stroke_mask))- layer.alpha_composite(stroke_layer)- _apply_clip(layer, command.clip, matrix, budget)- return layer---def _text_anchor(text_align: int) -> str:- """把 GDI TextAlignmentMode 转换为 Pillow anchor。"""- horizontal = "r" if text_align & _TA_CENTER == _TA_CENTER else "r" if text_align & _TA_RIGHT else "l"- if text_align & _TA_CENTER == _TA_CENTER:- horizontal = "m"- vertical = "s" if text_align & _TA_BASELINE == _TA_BASELINE else "d" if text_align & _TA_BOTTOM else "a"- return horizontal + vertical---def _aligned_text_positions(- command: DrawTextCommand,- matrix: Matrix,- positions: list[Point],-) -> tuple[list[Point], bool]:- """把显式字符位置按整串 CENTER/RIGHT alignment 平移一次。"""- if not command.positions or command.advance_end is None:- return positions, False- factor = 0.5 if command.text_align & _TA_CENTER == _TA_CENTER else 1.0 if command.text_align & _TA_RIGHT else 0.0- mapped_origin = matrix.transform_point(command.origin)- mapped_end = matrix.transform_point(command.advance_end)- offset_x = (mapped_end[0] - mapped_origin[0]) * factor- offset_y = (mapped_end[1] - mapped_origin[1]) * factor- return [(position[0] - offset_x, position[1] - offset_y) for position in positions], True---def _draw_rotated_text(- layer: Image.Image,- position: Point,- text: str,- *,- font: ImageFont.FreeTypeFont | ImageFont.ImageFont,- fill: tuple[int, int, int, int],- anchor: str,- rotation: float,- underline: bool,- strikeout: bool,-) -> tuple[int, int]:- """在指定 anchor 绘制可旋转文字,并返回未旋转文字尺寸。"""- draw = ImageDraw.Draw(layer)- bbox = draw.textbbox((0, 0), text, font=font, anchor=anchor)- width = max(1, bbox[2] - bbox[0])- height = max(1, bbox[3] - bbox[1])- line_width = max(1, round(height / 14.0))-- def draw_decorations(target_draw: ImageDraw.ImageDraw, reference: Point) -> None:- """围绕同一文字 reference 绘制下划线和删除线。"""- left = reference[0] + bbox[0]- right = reference[0] + bbox[2]- if underline:- y = reference[1] + bbox[3] + line_width- target_draw.line((left, y, right, y), fill=fill, width=line_width)- if strikeout:- y = reference[1] + (bbox[1] + bbox[3]) / 2.0- target_draw.line((left, y, right, y), fill=fill, width=line_width)-- if abs(rotation) < 1e-6:- draw.text(position, text, font=font, fill=fill, anchor=anchor)- draw_decorations(draw, position)- return width, height- padding = max(4, ceil(max(width, height) * 0.1))- bottom = bbox[3] + line_width * 2 if underline else bbox[3]- radius = ceil(max(hypot(x, y) for x in (bbox[0], bbox[2]) for y in (bbox[1], bottom))) + padding- patch = Image.new("RGBA", (radius * 2 + 1, radius * 2 + 1), (0, 0, 0, 0))- patch_draw = ImageDraw.Draw(patch)- reference = float(radius), float(radius)- patch_draw.text(reference, text, font=font, fill=fill, anchor=anchor)- draw_decorations(patch_draw, reference)- rotated = patch.rotate(-rotation, expand=False, resample=Image.Resampling.BICUBIC, center=reference)- target = round(position[0] - radius), round(position[1] - radius)- layer.alpha_composite(rotated, target)- return width, height---def _render_text_command(- command: DrawTextCommand,- matrix: Matrix,- size: tuple[int, int],- budget: FlattenBudget,-) -> Image.Image:- """把单条文字命令绘制到独立透明 RGBA layer。"""- layer = Image.new("RGBA", size, (0, 0, 0, 0))- scale_y = max(abs(matrix.d), 1e-9)- font_size = max(1, round(command.font_height * scale_y))- font = load_font(command.font.face_name, font_size, command.font.weight, command.font.italic, command.font.charset)- anchor = _text_anchor(command.text_align)- positions = (- [matrix.transform_point(position) for position in command.positions]- if command.positions- else [matrix.transform_point(command.origin)]- )- positions, positioned_run = _aligned_text_positions(command, matrix, positions)- if positioned_run:- anchor = "l" + anchor[1]- texts = tuple(command.text) if command.positions else (command.text,)- if command.opaque:- draw = ImageDraw.Draw(layer)- if command.bounds is not None:- rect = _mapped_rect(command.bounds, matrix).normalized()- background_bounds = rect.left, rect.top, rect.right, rect.bottom- else:- text_bounds = [draw.textbbox(position, text, font=font, anchor=anchor) for position, text in zip(positions, texts)]- background_bounds = (- min(bounds[0] for bounds in text_bounds),- min(bounds[1] for bounds in text_bounds),- max(bounds[2] for bounds in text_bounds),- max(bounds[3] for bounds in text_bounds),- )- draw.rectangle(background_bounds, fill=command.background_color.rgba())- if command.positions:- for position, character in zip(positions, command.text):- _draw_rotated_text(- layer,- position,- character,- font=font,- fill=command.color.rgba(),- anchor=anchor,- rotation=command.rotation,- underline=command.font.underline,- strikeout=command.font.strikeout,- )- else:- position = positions[0]- _draw_rotated_text(- layer,- position,- command.text,- font=font,- fill=command.color.rgba(),- anchor=anchor,- rotation=command.rotation,- underline=command.font.underline,- strikeout=command.font.strikeout,- )- _apply_clip(layer, command.clip, matrix, budget)- return layer---def _crop_source(image: Image.Image, source: Rect | None) -> tuple[Image.Image | None, Rect]:- """裁剪 GDI source rect,并返回交集在请求矩形中的归一化位置。"""- if source is None:- return image, Rect(0.0, 0.0, 1.0, 1.0)- if abs(source.width) <= 1e-9 or abs(source.height) <= 1e-9:- return None, Rect(0.0, 0.0, 0.0, 0.0)- flip_x = source.width < 0- flip_y = source.height < 0- normalized = source.normalized()- left = max(0, floor(normalized.left))- top = max(0, floor(normalized.top))- right = min(image.width, ceil(normalized.right))- bottom = min(image.height, ceil(normalized.bottom))- if right <= left or bottom <= top:- return None, Rect(0.0, 0.0, 0.0, 0.0)- horizontal = sorted(((left - source.left) / source.width, (right - source.left) / source.width))- vertical = sorted(((top - source.top) / source.height, (bottom - source.top) / source.height))- fraction = Rect(- max(0.0, horizontal[0]),- max(0.0, vertical[0]),- min(1.0, horizontal[1]),- min(1.0, vertical[1]),- )- cropped = image.crop((left, top, right, bottom))- if flip_x:- cropped = cropped.transpose(Image.Transpose.FLIP_LEFT_RIGHT)- if flip_y:- cropped = cropped.transpose(Image.Transpose.FLIP_TOP_BOTTOM)- return cropped, fraction---def _crop_destination(- destination: tuple[Point, Point, Point, Point],- fraction: Rect,-) -> tuple[Point, Point, Point, Point]:- """把 source 可见交集的归一化位置映射到目标平行四边形。"""- first, second, _third, fourth = destination- axis_x = second[0] - first[0], second[1] - first[1]- axis_y = fourth[0] - first[0], fourth[1] - first[1]-- def mapped(u: float, v: float) -> Point:- """把 source 归一化坐标映射到 destination。"""- return first[0] + axis_x[0] * u + axis_y[0] * v, first[1] + axis_x[1] * u + axis_y[1] * v-- return (- mapped(fraction.left, fraction.top),- mapped(fraction.right, fraction.top),- mapped(fraction.right, fraction.bottom),- mapped(fraction.left, fraction.bottom),- )---def _affine_image_layer(- image: Image.Image,- destination: tuple[Point, Point, Point, Point],- matrix: Matrix,- size: tuple[int, int],- stretch_mode: int,-) -> Image.Image:- """把源图片仿射映射到目标平行四边形。"""- first, second, _third, fourth = (matrix.transform_point(point) for point in destination)- axis_x = second[0] - first[0], second[1] - first[1]- axis_y = fourth[0] - first[0], fourth[1] - first[1]- determinant = axis_x[0] * axis_y[1] - axis_x[1] * axis_y[0]- if abs(determinant) < 1e-9:- return Image.new("RGBA", size, (0, 0, 0, 0))- inverse_00 = axis_y[1] / determinant- inverse_01 = -axis_y[0] / determinant- inverse_10 = -axis_x[1] / determinant- inverse_11 = axis_x[0] / determinant- scale_x = image.width- scale_y = image.height- a = inverse_00 * scale_x- b = inverse_01 * scale_x- c = -(inverse_00 * first[0] + inverse_01 * first[1]) * scale_x- d = inverse_10 * scale_y- e = inverse_11 * scale_y- f = -(inverse_10 * first[0] + inverse_11 * first[1]) * scale_y- resample = Image.Resampling.BICUBIC if stretch_mode == 4 else Image.Resampling.NEAREST- return image.transform(- size,- Image.Transform.AFFINE,- (a, b, c, d, e, f),- resample=resample,- fillcolor=(0, 0, 0, 0),- )---def _render_image_command(- command: DrawImageCommand,- matrix: Matrix,- size: tuple[int, int],- budget: FlattenBudget,-) -> Image.Image:- """解码、裁剪并仿射放置单条位图命令。"""- image, source_fraction = _crop_source(_decode_dib(command), command.source)- if image is None:- return Image.new("RGBA", size, (0, 0, 0, 0))- if command.constant_alpha < 255:- alpha = image.getchannel("A").point(lambda value: value * command.constant_alpha // 255)- image.putalpha(alpha)- destination = _crop_destination(command.destination, source_fraction)- layer = _affine_image_layer(image, destination, matrix, size, command.stretch_mode)- _apply_clip(layer, command.clip, matrix, budget)- return layer---def _bitwise_channel_bytes(destination: bytes, source: bytes, operation: str) -> bytes:- """对等长 RGB 字节串执行精确 AND、OR、XOR 或反相。"""- if operation == "xor":- return bytes(left ^ right for left, right in zip(destination, source))- if operation == "and":- return bytes(left & right for left, right in zip(destination, source))- if operation == "or":- return bytes(left | right for left, right in zip(destination, source))- if operation == "not_or":- return bytes((~(left | right)) & 0xFF for left, right in zip(destination, source))- if operation == "and_not_source":- return bytes(left & (~right & 0xFF) for left, right in zip(destination, source))- if operation == "not_source":- return bytes(255 - value for value in source)- if operation == "source_and_not_destination":- return bytes(right & (~left & 0xFF) for left, right in zip(destination, source))- if operation == "not_and":- return bytes((~(left & right)) & 0xFF for left, right in zip(destination, source))- if operation == "not_xor":- return bytes((~(left ^ right)) & 0xFF for left, right in zip(destination, source))- if operation == "destination_or_not_source":- return bytes(left | (~right & 0xFF) for left, right in zip(destination, source))- if operation == "source_or_not_destination":- return bytes(right | (~left & 0xFF) for left, right in zip(destination, source))- if operation == "invert":- return bytes(255 - value for value in destination)- fill = 0 if operation == "black" else 255- return bytes([fill]) * len(destination)---def _paste_bitwise(canvas: Image.Image, layer: Image.Image, operation: str) -> None:- """只在 layer 覆盖框内应用精确逐通道 GDI 逻辑合成。"""- mask = layer.getchannel("A")- bbox = mask.getbbox()- if bbox is None:- return- destination = canvas.crop(bbox).convert("RGB")- source = layer.crop(bbox).convert("RGB")- result = Image.frombytes(- "RGB",- destination.size,- _bitwise_channel_bytes(destination.tobytes(), source.tobytes(), operation),- ).convert("RGBA")- local_mask = mask.crop(bbox)- result.putalpha(ImageChops.lighter(canvas.getchannel("A").crop(bbox), local_mask))- canvas.paste(result, bbox[:2], local_mask)---def _composite_path(canvas: Image.Image, layer: Image.Image, rop2: int) -> None:- """按常见 ROP2 或默认 source-over 合成路径层。"""- operations = {- 1: "black",- 2: "not_or",- 3: "and_not_source",- 4: "not_source",- 5: "source_and_not_destination",- 6: "invert",- 7: "xor",- 8: "not_and",- 9: "and",- 10: "not_xor",- 12: "destination_or_not_source",- 14: "source_or_not_destination",- 15: "or",- 16: "white",- }- if rop2 == 13:- canvas.alpha_composite(layer)- elif rop2 != 11:- _paste_bitwise(canvas, layer, operations.get(rop2, "xor"))---def _composite_image(canvas: Image.Image, layer: Image.Image, rop: int) -> None:- """按常见 ROP3 或 AlphaBlend 结果合成位图层。"""- if rop in {_SRCCOPY, 0}:- canvas.alpha_composite(layer)- elif rop == _SRCAND:- _paste_bitwise(canvas, layer, "and")- elif rop == _SRCPAINT:- _paste_bitwise(canvas, layer, "or")- elif rop == _SRCINVERT:- _paste_bitwise(canvas, layer, "xor")- elif rop == _DSTINVERT:- _paste_bitwise(canvas, layer, "invert")- elif rop == _BLACKNESS:- _paste_bitwise(canvas, layer, "black")- elif rop == _WHITENESS:- _paste_bitwise(canvas, layer, "white")- else:- canvas.alpha_composite(layer)---def _supersample_factor(document: MetafileDocument) -> int:- """在画布、工作量预算内为纯矢量文档选择 1×、2× 或 4×。"""- if any(isinstance(command, DrawImageCommand) for command in document.commands):- return 1- work_units = _render_work_units(document)- for factor in (4, 2):- width = document.width * factor- height = document.height * factor- if (- width <= 8192- and height <= 8192- and width * height <= MAX_CANVAS_PIXELS- and width * height * work_units <= MAX_RENDER_WORK_PIXELS- ):- return factor- return 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_scale- height = document.height * raster_scale- 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)- size = width, height- canvas = Image.new("RGBA", size, (255, 255, 255, 0))- budget = FlattenBudget()- for command in document.commands:- if isinstance(command, DrawPathCommand):- _composite_path(canvas, _render_path_command(command, matrix, size, raster_scale, budget), command.rop2)- elif isinstance(command, DrawTextCommand):- canvas.alpha_composite(_render_text_command(command, matrix, size, budget))- else:- _composite_image(canvas, _render_image_command(command, matrix, size, budget), command.rop)- return canvas---def render_pillow(document: MetafileDocument) -> Image.Image:- """把统一图元文档以自适应超采样渲染为最终尺寸 RGBA 图片。"""- raster_scale = _supersample_factor(document)- canvas = _render_pillow_once(document, raster_scale)- if raster_scale == 1:- return canvas- resized = canvas.resize((document.width, document.height), Image.Resampling.LANCZOS)- return resized.filter(ImageFilter.UnsharpMask(radius=0.6, percent=100, threshold=2))---def _svg_number(value: float) -> str:- """以稳定且紧凑的形式序列化 SVG 浮点数。"""- rounded = round(value, 4)- if rounded == int(rounded):- return str(int(rounded))- return f"{rounded:.4f}".rstrip("0").rstrip(".")---def _svg_path_data(path: GraphicsPath, matrix: Matrix) -> str:- """把统一路径转换为安全 SVG path data。"""- parts: list[str] = []- for segment in transform_path(path, matrix).segments:- if segment.verb == "Z":- parts.append("Z")- continue- coordinates = " ".join(f"{_svg_number(point[0])} {_svg_number(point[1])}" for point in segment.points)- parts.append(f"{segment.verb} {coordinates}")- return " ".join(parts)---def _svg_opacity(color: Color) -> str:- """返回仅在颜色半透明时需要的 SVG opacity 属性。"""- return "" if color.alpha == 255 else f' opacity="{_svg_number(color.alpha / 255.0)}"'---def _svg_pen_attributes(pen: Pen, matrix: Matrix, miter_limit: float) -> str:- """把内部 Pen 转换为 SVG stroke 属性。"""- if pen.null:- return 'stroke="none"'- scale = (abs(matrix.a) + abs(matrix.d)) / 2.0- width = pen.width if pen.cosmetic else pen.width * max(scale, 1e-9)- attributes = [- f'stroke="{pen.color.svg()}"',- f'stroke-width="{_svg_number(max(width, 1.0))}"',- f'stroke-linecap="{pen.cap}"',- f'stroke-linejoin="{pen.join}"',- f'stroke-miterlimit="{_svg_number(max(miter_limit, 1.0))}"',- ]- if pen.color.alpha != 255:- attributes.append(f'stroke-opacity="{_svg_number(pen.color.alpha / 255.0)}"')- if pen.dashes:- dash_scale = 1.0 if pen.cosmetic else scale- attributes.append(f'stroke-dasharray="{" ".join(_svg_number(value * dash_scale) for value in pen.dashes)}"')- return " ".join(attributes)---def _svg_brush_attributes(brush: Brush) -> str:- """把内部 Brush 转换为基础 SVG fill 属性。"""- if brush.kind == "null":- return 'fill="none"'- attributes = [f'fill="{brush.color.svg()}"']- if brush.color.alpha != 255:- attributes.append(f'fill-opacity="{_svg_number(brush.color.alpha / 255.0)}"')- return " ".join(attributes)---def _svg_clip_definitions(document: MetafileDocument, matrix: Matrix) -> tuple[list[str], dict[ClipOperation, str]]:- """为只含 copy/and 的裁剪路径生成确定性 clipPath 定义。"""- definitions: list[str] = []- identifiers: dict[ClipOperation, str] = {}- ordinal = 0- for command in document.commands:- for operation in command.clip:- if operation in identifiers:- continue- ordinal += 1- identifier = f"mineru-clip-{ordinal}"- identifiers[operation] = identifier- definitions.append(- f'<clipPath id="{identifier}"><path d="{_svg_path_data(operation.path, matrix)}" '- f'fill-rule="{operation.fill_rule}"/></clipPath>'- )- return definitions, identifiers---def _wrap_svg_clip(element: str, clip: ClipStack, identifiers: dict[ClipOperation, str]) -> str:- """按裁剪顺序用嵌套 SVG group 包裹单个图元。"""- wrapped = element- active: list[ClipOperation] = []- for operation in clip:- if operation.mode == "copy":- active = [operation]- elif operation.mode == "and":- active.append(operation)- for operation in reversed(active):- wrapped = f'<g clip-path="url(#{identifiers[operation]})">{wrapped}</g>'- return wrapped---def _svg_text_anchor(text_align: int) -> tuple[str, str]:- """把 GDI 文字对齐转换为 SVG anchor 和 baseline。"""- horizontal = "middle" if text_align & _TA_CENTER == _TA_CENTER else "end" if text_align & _TA_RIGHT else "start"- vertical = (- "alphabetic"- if text_align & _TA_BASELINE == _TA_BASELINE- else "text-after-edge"- if text_align & _TA_BOTTOM- else "hanging"- )- return horizontal, vertical---def _svg_text_elements(command: DrawTextCommand, matrix: Matrix) -> str:- """把统一文字命令转换为一个或多个安全 SVG text 元素。"""- anchor, baseline = _svg_text_anchor(command.text_align)- scale_y = max(abs(matrix.d), 1e-9)- font_size = max(1.0, command.font_height * scale_y)- decorations = []- if command.font.underline:- decorations.append("underline")- if command.font.strikeout:- decorations.append("line-through")- decoration_attr = f' text-decoration="{" ".join(decorations)}"' if decorations else ""- elements: list[str] = []- positions = command.positions or (command.origin,)- texts = tuple(command.text) if command.positions else (command.text,)- mapped_positions_list = [matrix.transform_point(position) for position in positions]- mapped_positions_list, positioned_run = _aligned_text_positions(command, matrix, mapped_positions_list)- if positioned_run:- anchor = "start"- common = (- f'fill="{command.color.svg()}"{_svg_opacity(command.color)} '- f'font-family="{escape(command.font.face_name, quote=True)}" font-size="{_svg_number(font_size)}" '- f'font-weight="{command.font.weight}" font-style="{"italic" if command.font.italic else "normal"}" '- f'text-anchor="{anchor}" dominant-baseline="{baseline}"{decoration_attr}'- )- mapped_positions = tuple(mapped_positions_list)- for mapped, text in zip(mapped_positions, texts):- transform = ""- if abs(command.rotation) > 1e-6:- transform = (- f' transform="rotate({_svg_number(command.rotation)} {_svg_number(mapped[0])} {_svg_number(mapped[1])})"'- )- elements.append(- f'<text x="{_svg_number(mapped[0])}" y="{_svg_number(mapped[1])}" {common}{transform}>{escape(text)}</text>'- )- background = ""- if command.opaque:- if command.bounds is not None:- rect = _mapped_rect(command.bounds, matrix).normalized()- else:- approximate_widths = tuple(max(font_size * 0.6 * len(text), font_size * 0.25) for text in texts)- left = min(position[0] for position in mapped_positions)- right = max(position[0] + width for position, width in zip(mapped_positions, approximate_widths))- top = min(position[1] - font_size for position in mapped_positions)- bottom = max(position[1] + font_size * 0.25 for position in mapped_positions)- rect = Rect(left, top, right, bottom)- background = (- f'<rect x="{_svg_number(rect.left)}" y="{_svg_number(rect.top)}" width="{_svg_number(rect.width)}" '- f'height="{_svg_number(rect.height)}" fill="{command.background_color.svg()}"'- f"{_svg_opacity(command.background_color)}/>"- )- return background + "".join(elements)---def _svg_image_element(command: DrawImageCommand, matrix: Matrix) -> str:- """把 DIB 转成内嵌 PNG 并以 SVG affine matrix 放置。"""- image, source_fraction = _crop_source(_decode_dib(command), command.source)- if image is None:- return ""- if command.constant_alpha < 255:- image.putalpha(image.getchannel("A").point(lambda value: value * command.constant_alpha // 255))- output = BytesIO()- image.save(output, format="PNG")- encoded = base64.b64encode(output.getvalue()).decode("ascii")- destination = _crop_destination(command.destination, source_fraction)- first, second, _third, fourth = (matrix.transform_point(point) for point in destination)- a = (second[0] - first[0]) / max(image.width, 1)- b = (second[1] - first[1]) / max(image.width, 1)- c = (fourth[0] - first[0]) / max(image.height, 1)- d = (fourth[1] - first[1]) / max(image.height, 1)- transform = " ".join(_svg_number(value) for value in (a, b, c, d, first[0], first[1]))- return (- f'<image width="{image.width}" height="{image.height}" transform="matrix({transform})" '- f'href="data:image/png;base64,{encoded}"/>'- )---def _svg_requires_raster(document: MetafileDocument) -> bool:- """判断 SVG 是否需要用整图 PNG 包装保留复杂合成语义。"""- for command in document.commands:- if any(operation.mode not in {"copy", "and"} for operation in command.clip):- return True- if isinstance(command, DrawPathCommand) and command.rop2 != 13:- return True- if isinstance(command, DrawImageCommand) and command.rop not in {_SRCCOPY, 0}:- return True- return False---def _svg_fallback_scale(document: MetafileDocument) -> int:- """为纯矢量 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 (2,):- width = document.width * factor- height = document.height * factor- if (- width <= 8192- and height <= 8192- and width * height <= MAX_CANVAS_PIXELS- and width * height * command_count <= MAX_RENDER_WORK_PIXELS- ):- return factor- return 1---def _png_fallback_bytes(document: MetafileDocument, *, pixel_scale: int = 1) -> bytes:- """生成指定像素密度、带对应 DPI metadata 的 PNG fallback。"""- image = render_pillow(document) if pixel_scale == 1 else _render_pillow_once(document, pixel_scale)- output = BytesIO()- image.save(output, format="PNG", dpi=(96 * pixel_scale, 96 * pixel_scale))- return output.getvalue()---def _svg_fallback_metadata(encoded_png: str) -> str:- """生成带固定标识的不可见 PNG fallback metadata。"""- 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">'- f"{_svg_fallback_metadata(encoded)}"- f'<image width="{document.width}" height="{document.height}" href="data:image/png;base64,{encoded}"/>'- "</svg>"- )- return _encode_svg_markup(markup)---def render_svg(document: MetafileDocument) -> bytes:- """把统一图元文档渲染为安全、自包含 SVG 字节。"""- if _svg_requires_raster(document):- return _raster_wrapped_svg(document)- matrix = _document_matrix(document)- 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):- stroke = _svg_pen_attributes(command.pen, matrix, command.miter_limit) if command.stroke else 'stroke="none"'- fill = _svg_brush_attributes(command.brush) if command.fill else 'fill="none"'- element = f'<path d="{_svg_path_data(command.path, matrix)}" {stroke} {fill} fill-rule="{command.fill_rule}"/>'- elif isinstance(command, DrawTextCommand):- element = _svg_text_elements(command, matrix)- 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"{fallback_metadata}{defs}{''.join(elements)}</svg>"- )- return _encode_svg_markup(markup)---def encode_document(document: MetafileDocument, output_format: MetafileOutputFormat) -> tuple[bytes, str]:- """按目标格式编码统一图元文档并返回 MIME。"""- if output_format == "svg":- return render_svg(document), "image/svg+xml"- if output_format == "png":- return _png_fallback_bytes(document), "image/png"- image = render_pillow(document)- output = BytesIO()- background = Image.new("RGB", image.size, (255, 255, 255))- background.paste(image.convert("RGB"), (0, 0), image.getchannel("A"))- background.save(output, format="JPEG", quality=90)- return output.getvalue(), "image/jpeg"---__all__ = ["encode_document", "render_pillow", "render_svg"]diff --git a/mineru/render/_internal/docx/assets.py b/mineru/render/_internal/docx/assets.pyindex a7fb8734..05575024 100644--- a/mineru/render/_internal/docx/assets.py+++ b/mineru/render/_internal/docx/assets.py@@ -14,7 +14,7 @@ from PIL import Image, UnidentifiedImageErrorfrom ...contracts import AssetResolverfrom ....types import ImagePayloadBlockfrom ....utils.image_payload import (- extract_mineru_generated_svg_fallback,+ extract_generated_svg_fallback,parse_image_data_uri_strict,validate_image_sidecar_path,)@@ -95,7 +95,7 @@ def prepare_image_bytes(expected_extension = _normalize_extension(declared_extension)if expected_extension == "svg" or _looks_like_svg(data):try:- fallback, logical_width, logical_height = extract_mineru_generated_svg_fallback(data)+ fallback, logical_width, logical_height = extract_generated_svg_fallback(data)except ValueError as exc:raise DocxAssetError("SVG images are not supported unless they are safely generated by MinerU") from excprepared = prepare_image_bytes(fallback, declared_extension="png")diff --git a/mineru/render/_internal/epub/assets.py b/mineru/render/_internal/epub/assets.pyindex 102cd98b..ba310109 100644--- a/mineru/render/_internal/epub/assets.py+++ b/mineru/render/_internal/epub/assets.py@@ -17,7 +17,7 @@ from ....types import ImagePayloadBlockfrom ....utils.image_payload import (MAX_IMAGE_DATA_URI_BYTES,MAX_IMAGE_PAYLOAD_BYTES,- extract_mineru_generated_svg_fallback,+ extract_generated_svg_fallback,normalize_image_extension,parse_image_data_uri_strict,validate_decoded_raster_size,@@ -148,7 +148,7 @@ def _prepare_epub_image(data: bytes, *, declared_extension: str | None) -> tupleif expected == "svg" or _SVG_START_RE.match(data[:4096]) is not None:if expected not in {None, "svg"}:raise ValueError("Image bytes do not match the declared format")- fallback, _, _ = extract_mineru_generated_svg_fallback(data)+ fallback, _, _ = extract_generated_svg_fallback(data)return _prepare_epub_image(fallback, declared_extension="png")try:diff --git a/mineru/render/_internal/html/sanitizer.py b/mineru/render/_internal/html/sanitizer.pyindex 38c8aee4..e987a100 100644--- a/mineru/render/_internal/html/sanitizer.py+++ b/mineru/render/_internal/html/sanitizer.py@@ -10,7 +10,7 @@ from urllib.parse import quote, unquote, urlsplitimport nh3from bs4 import BeautifulSoup, NavigableString, Tag-from ....utils.image_payload import extract_mineru_generated_svg_fallback, parse_image_data_uri_strict+from ....utils.image_payload import extract_generated_svg_fallback, parse_image_data_uri_strict_ALLOWED_TAGS = {@@ -255,7 +255,7 @@ def _sanitize_raster_data_uri(source: str) -> str | None:return Noneif extension == "svg":try:- extract_mineru_generated_svg_fallback(payload)+ extract_generated_svg_fallback(payload)except ValueError:return Nonereturn sourcediff --git a/mineru/render/_internal/pdf/assets.py b/mineru/render/_internal/pdf/assets.pyindex 28c56d78..208a624d 100644--- a/mineru/render/_internal/pdf/assets.py+++ b/mineru/render/_internal/pdf/assets.py@@ -15,7 +15,7 @@ from ...contracts import AssetResolverfrom ....types import ImagePayloadBlockfrom ....utils.image_payload import (MAX_IMAGE_PAYLOAD_BYTES,- extract_mineru_generated_svg_fallback,+ extract_generated_svg_fallback,parse_image_data_uri_strict,validate_decoded_raster_size,validate_image_sidecar_path,@@ -94,7 +94,7 @@ def prepare_image_bytes(data: bytes, *, declared_extension: str | None = None) -expected_extension = _normalize_extension(declared_extension)if expected_extension == "svg" or _looks_like_svg(data):try:- fallback, logical_width, logical_height = extract_mineru_generated_svg_fallback(data)+ fallback, logical_width, logical_height = extract_generated_svg_fallback(data)except ValueError as exc:raise PdfAssetError("SVG images require a validated MinerU PNG fallback") from excprepared = prepare_image_bytes(fallback, declared_extension="png")diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.pyindex a0b14013..bc0f9da9 100644--- a/mineru/utils/image_payload.py+++ b/mineru/utils/image_payload.py@@ -11,8 +11,8 @@ from urllib.parse import urlsplitINLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;\"']+);base64,([^\"']+)", re.DOTALL)_SVG_NAMESPACE = "http://www.w3.org/2000/svg"-_MINERU_SVG_MARKER = "wmf-emf"-_MINERU_SVG_FALLBACK_ID = "mineru-raster-fallback"+_METAFILE_SVG_MARKER = "wmf-emf"+_METAFILE_SVG_FALLBACK_ID = "metafile-render-raster-fallback"MAX_IMAGE_PAYLOAD_BYTES: Final = 64 * 1024 * 1024MAX_GENERATED_SVG_BYTES: Final = MAX_IMAGE_PAYLOAD_BYTESMAX_RASTER_IMAGE_BYTES: Final = MAX_IMAGE_PAYLOAD_BYTES@@ -21,7 +21,7 @@ MAX_DECODED_RASTER_DIMENSION: Final = 8_192MAX_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"},+ "svg": {"width", "height", "viewBox", "data-metafile-render"},"metadata": {"id", "data-mime"},"defs": set(),"clipPath": {"id"},@@ -176,21 +176,21 @@ def _validate_generated_svg_attribute(tag: str, name: str, value: str) -> None:raise ValueError(f"Generated SVG contains an unsafe attribute value: {tag}.{name}")if name == "href":_decode_png_data_uri(value)- elif name == "clip-path" and re.fullmatch(r"url\(#mineru-clip-\d+\)", value) is None:- raise ValueError("Generated SVG clip-path must reference a local MinerU clip")+ elif name == "clip-path" and re.fullmatch(r"url\(#metafile-render-clip-\d+\)", value) is None:+ raise ValueError("Generated SVG clip-path must reference a local metafile-render clip")elif name == "transform" and re.fullmatch(r"(?:matrix|rotate)\([0-9eE+.,\- ]+\)", value) is None:raise ValueError("Generated SVG transform is outside the supported subset")elif name == "d" and re.fullmatch(r"[MmLlCcZz0-9eE+.,\- ]*", value) is None:raise ValueError("Generated SVG path data is outside the supported subset")-def extract_mineru_generated_svg_fallback(payload: bytes) -> tuple[bytes, int, int]:- """验证 MinerU 生成 SVG,并返回 PNG fallback 与逻辑像素尺寸。"""+def extract_generated_svg_fallback(payload: bytes) -> tuple[bytes, int, int]:+ """验证 metafile-render 生成 SVG,并返回 PNG fallback 与逻辑像素尺寸。"""if not isinstance(payload, bytes) or not payload:raise ValueError("Generated SVG payload is empty or exceeds its byte limit")root = _parse_svg_root_strict(payload)- if root.tag != f"{{{_SVG_NAMESPACE}}}svg" or root.get("data-mineru-generated") != _MINERU_SVG_MARKER:- raise ValueError("SVG is not marked as a MinerU generated metafile")+ if root.tag != f"{{{_SVG_NAMESPACE}}}svg" or root.get("data-metafile-render") != _METAFILE_SVG_MARKER:+ raise ValueError("SVG is not marked as a metafile-render generated image")try:width = int(root.get("width", ""))height = int(root.get("height", ""))@@ -217,7 +217,11 @@ def extract_mineru_generated_svg_fallback(payload: bytes) -> tuple[bytes, int, iif element.tail and element.tail.strip():raise ValueError("Generated SVG contains unexpected tail text")if tag == "metadata":- if element.get("id") != _MINERU_SVG_FALLBACK_ID or element.get("data-mime") != "image/png" or fallback is not None:+ if (+ element.get("id") != _METAFILE_SVG_FALLBACK_ID+ or element.get("data-mime") != "image/png"+ or fallback is not None+ ):raise ValueError("Generated SVG fallback metadata is invalid or duplicated")encoded = (element.text or "").strip()fallback = _decode_png_data_uri(f"data:image/png;base64,{encoded}")diff --git a/pyproject.toml b/pyproject.tomlindex 8638a18b..15144a1a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,6 +39,7 @@ classifiers = []dependencies = ["mineru-vl-utils>=1.2.1,<2",+ "metafile-render>=0.1.0,<0.2.0","mineru-llama-cpp>=0.1.0,<1","click>=8.1.7","loguru>=0.7.2",diff --git a/tests/unittest/test_docx_assets.py b/tests/unittest/test_docx_assets.pyindex 64b9684b..57031bc4 100644--- a/tests/unittest/test_docx_assets.py+++ b/tests/unittest/test_docx_assets.py@@ -40,8 +40,8 @@ def _generated_svg(*, logical_size: tuple[int, int] = (7, 5), fallback_size: tupwidth, height = logical_sizereturn (f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '- f'viewBox="0 0 {width} {height}" data-mineru-generated="wmf-emf">'- f'<metadata id="mineru-raster-fallback" data-mime="image/png">{fallback}</metadata>'+ f'viewBox="0 0 {width} {height}" data-metafile-render="wmf-emf">'+ f'<metadata id="metafile-render-raster-fallback" data-mime="image/png">{fallback}</metadata>'f'<path d="M 0 0 L {width} 0 L {width} {height} Z" fill="#000000"/>'"</svg>").encode()diff --git a/tests/unittest/test_docx_render.py b/tests/unittest/test_docx_render.pyindex 8868a9ff..0bbdb577 100644--- a/tests/unittest/test_docx_render.py+++ b/tests/unittest/test_docx_render.py@@ -72,8 +72,8 @@ def _generated_svg_uri(*, logical_size: tuple[int, int] = (12, 8), fallback_sizefallback = base64.b64encode(_png_bytes(size=fallback_size)).decode("ascii")svg = (f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '- f'viewBox="0 0 {width} {height}" data-mineru-generated="wmf-emf">'- f'<metadata id="mineru-raster-fallback" data-mime="image/png">{fallback}</metadata>'+ f'viewBox="0 0 {width} {height}" data-metafile-render="wmf-emf">'+ f'<metadata id="metafile-render-raster-fallback" data-mime="image/png">{fallback}</metadata>'f'<path d="M 0 0 L {width} 0 L {width} {height} Z" fill="#000000"/>'"</svg>").encode()diff --git a/tests/unittest/test_flash_office_metafile.py b/tests/unittest/test_flash_office_metafile.pyindex bc37b349..9977728c 100644--- a/tests/unittest/test_flash_office_metafile.py+++ b/tests/unittest/test_flash_office_metafile.py@@ -1,19 +1,36 @@-"""验证 Office WMF/EMF 跨平台渲染能力。"""+"""验证独立 WMF/EMF 渲染包的 Office 集成。"""from __future__ import annotationsimport base64-from io import BytesIO-from pathlib import Pathimport struct-from unittest.mock import Mockimport zlib+from io import BytesIO+from unittest.mock import Mockfrom zipfile import ZIP_DEFLATED, ZipFile-from PIL import Image, ImageFont-import pyclipperimport pytest-import pptx+from _legacy_ppt_test_utils import build_equation_ppt+from _legacy_xls_test_utils import build_equation_xls+from _metafile_test_utils import (+ basic_wmf,+ build_emf,+ emf_create_brush,+ emf_create_pen,+ emf_font,+ emf_rectangle,+ emf_select_object,+ emf_stretch_dib,+ emf_text,+)+from _mtef_test_utils import build_equation_doc+from _odf_test_utils import build_odp_fixture, build_ods_fixture, build_odt_fixture+from _office_image_mtef_test_utils import build_image_docx, build_image_pptx, build_image_xlsx+from metafile_render import (+ MetafileResourceLimitError,+ render_metafile,+)+from PIL import Imagefrom mineru.model.flash import (DocModel,@@ -28,73 +45,10 @@ from mineru.model.flash import (XlsxModel,)from mineru.model.flash.office import image as office_image-from mineru.model.flash.office.metafile import (- MetafileMalformedError,- MetafileError,- MetafileUnsupportedError,- MetafileResourceLimitError,- render_metafile,-)-from mineru.model.flash.office.metafile import parser as metafile_parser-from mineru.model.flash.office.metafile import render as metafile_render-from mineru.model.flash.office.metafile.geometry import FlattenBudget, PathBuilder, flatten_path, path_bounds-from mineru.model.flash.office.metafile.models import (- ClipOperation,- DrawImageCommand,- DrawPathCommand,- DrawTextCommand,- GraphicsPath,- Matrix,- Pen,- Rect,-)from mineru.model.flash.office.legacy.officeart import OfficeArtRecord, decode_blipfrom mineru.model.flash.office.pptx.pptx_converter import PptxConverterfrom mineru.model.flash.office.xlsx.xlsx_converter import XlsxConverter-from mineru.utils.image_payload import extract_mineru_generated_svg_fallback--from _metafile_test_utils import (- basic_wmf,- build_emf,- build_placeable_wmf,- emf_angle_arc,- emf_arc_to,- emf_begin_path,- emf_close_figure,- emf_create_brush,- emf_create_pen,- emf_end_path,- emf_font,- emf_intersect_clip_rect,- emf_line_to,- emf_move_to,- emf_polybezier,- emf_polyline_to,- emf_record,- emf_rectangle,- emf_restoredc,- emf_savedc,- emf_select_object,- emf_set_miter_limit,- emf_set_text_align,- emf_set_world_transform,- emf_stroke_and_fill_path,- emf_stroke_path,- emf_stretch_dib,- emf_text,- emfplus_comment,- wmf_move_to,- wmf_rectangle,- wmf_record,- wmf_set_map_mode,- wmf_set_text_align,- wmf_textout,-)-from _legacy_ppt_test_utils import build_equation_ppt-from _legacy_xls_test_utils import build_equation_xls-from _mtef_test_utils import build_equation_doc-from _office_image_mtef_test_utils import build_image_docx, build_image_pptx, build_image_xlsx-from _odf_test_utils import build_odp_fixture, build_ods_fixture, build_odt_fixture+from mineru.utils.image_payload import extract_generated_svg_fallbackdef _open_result(payload: bytes) -> Image.Image:@@ -108,7 +62,7 @@ def _svg_data_uri_fallback(data_uri: str) -> tuple[Image.Image, tuple[int, int],"""解析 MinerU SVG data URI,并返回 fallback 图片、逻辑尺寸和 SVG。"""assert data_uri.startswith("data:image/svg+xml;base64,")svg = base64.b64decode(data_uri.split(",", 1)[1])- fallback, logical_width, logical_height = extract_mineru_generated_svg_fallback(svg)+ fallback, logical_width, logical_height = extract_generated_svg_fallback(svg)return _open_result(fallback), (logical_width, logical_height), svg@@ -151,33 +105,6 @@ def _replace_zip_member(package: bytes, member_name: str, payload: bytes) -> bytreturn output.getvalue()-def _compound_square_path(*, inner_reversed: bool, include_island: bool = False) -> GraphicsPath:- """构造用于验证 winding 与 even-odd 的嵌套方形复合路径。"""- builder = PathBuilder()- for point in ((10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)):- if builder.current is None:- builder.move_to(point)- else:- builder.line_to(point)- builder.close()- inner = (- ((25.0, 25.0), (25.0, 75.0), (75.0, 75.0), (75.0, 25.0))- if inner_reversed- else ((25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0))- )- builder.move_to(inner[0])- for point in inner[1:]:- builder.line_to(point)- builder.close()- if include_island:- builder.move_to((40.0, 40.0))- builder.line_to((60.0, 40.0))- builder.line_to((60.0, 60.0))- builder.line_to((40.0, 60.0))- builder.close()- return builder.build()--def _build_doc_with_wmf_preview(payload: bytes) -> bytes:"""构造 Native 失败后使用 WMF PICF 预览的 DOC。"""return build_equation_doc(@@ -197,647 +124,17 @@ def _build_xls_with_wmf_preview(payload: bytes) -> bytes:return build_equation_xls([(1, b"invalid")], preview_payload=payload)-def test_emf_renders_png_jpeg_and_safe_svg() -> None:- """验证同一 EMF 可输出三种格式且 SVG 不含活动或外部内容。"""- data = build_emf(_basic_emf_records())-- png = render_metafile(data, output_format="png")- jpeg = render_metafile(data, output_format="jpeg")- svg = render_metafile(data, output_format="svg")-- assert png.media_type == "image/png"- assert png.data.startswith(b"\x89PNG\r\n\x1a\n")- assert jpeg.media_type == "image/jpeg"- assert jpeg.data.startswith(b"\xff\xd8\xff")- assert svg.media_type == "image/svg+xml"- assert svg.data.startswith(b'<svg xmlns="http://www.w3.org/2000/svg"')- assert b"<script" not in svg.data- assert b"http://" not in svg.data.replace(b"http://www.w3.org/2000/svg", b"")- assert b"https://" not in svg.data- assert (png.width, png.height) == (144, 144)- assert not png.partial-- image = _open_result(png.data)- assert image.getbbox() is not None- assert image.getpixel((30, 30))[:3] == (255, 0, 0)- assert image.getpixel((100, 30))[:3] == (0, 255, 0)- assert image.getpixel((30, 110))[:3] == (0, 0, 255)- assert image.getpixel((100, 110))[:3] == (255, 255, 255)- assert image.getpixel((30, 90))[:3] == (255, 255, 255)---def test_alpha_dib_unpremultiplies_channels_before_compositing() -> None:- """验证 AC_SRC_ALPHA 的 premultiplied BGRA 在 Pillow 合成前恢复为 straight RGBA。"""- header = bytearray(40)- struct.pack_into("<IiiHHIIiiII", header, 0, 40, 2, -1, 1, 32, 0, 8, 0, 0, 0, 0)- command = DrawImageCommand(- dib_header=bytes(header),- bits=bytes((0, 0, 128, 128, 0, 64, 0, 64)),- destination=((0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)),- source=None,- rop=0,- use_source_alpha=True,- )-- decoded = metafile_render._decode_raw_alpha_dib(command)-- assert decoded is not None- assert decoded.getpixel((0, 0)) == (255, 0, 0, 128)- assert decoded.getpixel((1, 0)) == (0, 255, 0, 64)- background = Image.new("RGBA", decoded.size, "white")- background.alpha_composite(decoded)- assert background.getpixel((0, 0)) == (255, 127, 127, 255)- assert background.getpixel((1, 0)) == (191, 255, 191, 255)---def test_emf_save_restore_preserves_selected_objects_and_transform() -> None:- """验证 SaveDC/RestoreDC 同时恢复 transform 与选中画刷。"""- records = [- emf_create_brush(1, 0x000000FF),- emf_create_brush(2, 0x00FF0000),- emf_select_object(1),- emf_rectangle(0, 0, 20, 20),- emf_savedc(),- emf_set_world_transform((1, 0, 0, 1, 50, 0)),- emf_select_object(2),- emf_rectangle(0, 0, 20, 20),- emf_restoredc(),- emf_rectangle(25, 0, 45, 20),- ]- image = _open_result(render_metafile(build_emf(records)).data)-- assert image.getpixel((14, 14))[0] > 200- assert image.getpixel((50, 14))[0] > 200- assert image.getpixel((86, 14))[2] > 200---def test_emf_to_records_append_to_one_path_figure_and_update_current_position() -> None:- """验证 Path bracket 内 To records 连续追加且 CloseFigure 后新建 figure。"""- data = build_emf(- [- emf_begin_path(),- emf_move_to(10, 50),- emf_polyline_to([(20, 50), (30, 50)]),- emf_polybezier([(40, 50), (50, 50), (60, 50)], to=True),- emf_close_figure(),- emf_line_to(70, 70),- emf_end_path(),- emf_stroke_path(),- emf_line_to(90, 90),- ]- )-- document = metafile_parser.parse_metafile(data)- commands = [command for command in document.commands if isinstance(command, DrawPathCommand)]-- assert [segment.verb for segment in commands[0].path.segments] == ["M", "L", "L", "C", "Z", "M", "L"]- assert commands[0].path.segments[5].points == ((60.0, 50.0),)- assert commands[1].path.segments[0].points == ((70.0, 70.0),)---def test_emf_non_to_polybezier_does_not_change_gdi_current_position() -> None:- """验证 PolyBezier 不像 PolyBezierTo 那样更新 DC current position。"""- data = build_emf(- [- emf_move_to(5, 5),- emf_begin_path(),- emf_polybezier([(20, 20), (30, 0), (50, 0), (60, 20)], to=False),- emf_end_path(),- emf_stroke_path(),- emf_line_to(10, 5),- ]- )-- document = metafile_parser.parse_metafile(data)- commands = [command for command in document.commands if isinstance(command, DrawPathCommand)]-- assert commands[1].path.segments[0].points == ((5.0, 5.0),)--- "data",- [- build_emf(- [- emf_set_text_align(1),- emf_move_to(10, 50),- emf_text("first", 900, 900, dx=None),- emf_text("second", 800, 800, dx=None),- ]- ),- build_placeable_wmf(- [- wmf_set_text_align(1),- wmf_move_to(10, 50),- wmf_textout("first", 900, 900),- wmf_textout("second", 800, 800),- ]- ),- ],- ids=["emf", "wmf"],-)-def test_updatecp_text_without_explicit_spacing_advances_current_position(data: bytes) -> None:- """验证 EMF/WMF 无显式 spacing 的 TA_UPDATECP 文本不会相互覆盖。"""- commands = [command for command in metafile_parser.parse_metafile(data).commands if isinstance(command, DrawTextCommand)]-- assert len(commands) == 2- assert commands[0].origin == (10.0, 50.0)- assert commands[1].origin[0] > commands[0].origin[0]- assert commands[1].origin[1] == pytest.approx(commands[0].origin[1])- assert not commands[0].positions- assert not commands[1].positions--[email protected](("text_align", "expected_x"), [(6, (40.0, 50.0)), (2, (30.0, 40.0))])-def test_explicit_spacing_applies_center_or_right_alignment_once(- text_align: int,- expected_x: tuple[float, float],-) -> None:- """验证显式 DX 字符先按整串 alignment 平移,再从左侧 cell origin 绘制。"""- document = metafile_parser.parse_metafile(build_emf([emf_set_text_align(text_align), emf_text("AB", 50, 50, dx=10)]))- command = next(command for command in document.commands if isinstance(command, DrawTextCommand))- positions, positioned_run = metafile_render._aligned_text_positions(command, Matrix(), list(command.positions))- svg = metafile_render._svg_text_elements(command, Matrix())-- assert command.advance_end == (70.0, 50.0)- assert positioned_run- assert tuple(position[0] for position in positions) == expected_x- assert all(position[1] == 50.0 for position in positions)- assert 'text-anchor="start"' in svg---def test_rotated_text_preserves_left_and_right_anchor_without_clipping() -> None:- """验证旋转文字围绕 GDI reference 定位,左右 anchor 均保留完整字形。"""- font = ImageFont.load_default(size=20)- left = Image.new("RGBA", (180, 140), (0, 0, 0, 0))- right = Image.new("RGBA", (180, 140), (0, 0, 0, 0))-- for layer, anchor in ((left, "la"), (right, "ra")):- metafile_render._draw_rotated_text(- layer,- (90.0, 70.0),- "Anchor",- font=font,- fill=(0, 0, 0, 255),- anchor=anchor,- rotation=35.0,- underline=True,- strikeout=True,- )-- left_pixels = sum(value > 0 for value in left.getchannel("A").getdata())- right_pixels = sum(value > 0 for value in right.getchannel("A").getdata())-- assert left.getbbox() is not None and right.getbbox() is not None- assert right_pixels == pytest.approx(left_pixels, rel=0.05)- assert left.getbbox()[2] > 90- assert right.getbbox()[0] < 90--[email protected](("sweep_angle", "expected_end_y"), [(90.0, -10.0), (-90.0, 10.0)])-def test_emf_anglearc_uses_sweep_direction_and_updates_current_position(- sweep_angle: float,- expected_end_y: float,-) -> None:- """验证 AngleArc 绘制起始连线、使用正确 sweep 方向并更新 current position。"""- data = build_emf(- [emf_angle_arc(0, 0, 10, 0.0, sweep_angle), emf_line_to(20, 20)],- bounds=(-20, -20, 30, 30),- )- commands = [command for command in metafile_parser.parse_metafile(data).commands if isinstance(command, DrawPathCommand)]-- assert len(commands[0].path.segments) == 14- assert commands[0].path.segments[0].points == ((0.0, 0.0),)- assert commands[0].path.segments[1].points == ((10.0, 0.0),)- assert commands[0].path.segments[-1].points[0] == pytest.approx((0.0, expected_end_y))- assert commands[1].path.segments[0].points[0] == pytest.approx((0.0, expected_end_y))---def test_emf_arcto_connects_current_position_to_projected_arc_endpoints() -> None:- """验证 ArcTo 连接 current 与椭圆投影起点,并将 current 更新到投影终点。"""- data = build_emf(- [- emf_move_to(10, 10),- emf_arc_to((0, 0, 100, 100), (150, 50), (50, -100)),- emf_line_to(80, 80),- ]- )- commands = [command for command in metafile_parser.parse_metafile(data).commands if isinstance(command, DrawPathCommand)]-- assert commands[0].path.segments[0].points == ((10.0, 10.0),)- assert commands[0].path.segments[1].points[0] == pytest.approx((100.0, 50.0))- assert commands[0].path.segments[-1].points[0] == pytest.approx((50.0, 0.0))- assert commands[1].path.segments[0].points[0] == pytest.approx((50.0, 0.0))---def test_emf_stroke_and_fill_closes_every_open_figure() -> None:- """验证 StrokeAndFillPath 在描边前显式闭合全部开放 figure。"""- data = build_emf(- [- emf_begin_path(),- emf_move_to(10, 10),- emf_polyline_to([(40, 10), (40, 40)]),- emf_move_to(60, 60),- emf_polyline_to([(90, 60), (90, 90)]),- emf_end_path(),- emf_stroke_and_fill_path(),- ]- )-- command = next(command for command in metafile_parser.parse_metafile(data).commands if isinstance(command, DrawPathCommand))-- assert [segment.verb for segment in command.path.segments] == ["M", "L", "L", "Z", "M", "L", "L", "Z"]---def test_compound_path_masks_preserve_nonzero_and_evenodd_topology() -> None:- """验证 winding、alternate、孔洞和孔洞内岛屿的 mask 拓扑。"""- opposite = _compound_square_path(inner_reversed=True)- same = _compound_square_path(inner_reversed=False)- island = _compound_square_path(inner_reversed=True, include_island=True)- self_intersecting_builder = PathBuilder()- self_intersecting_builder.move_to((10.0, 10.0))- self_intersecting_builder.line_to((90.0, 90.0))- self_intersecting_builder.line_to((10.0, 90.0))- self_intersecting_builder.line_to((90.0, 10.0))- self_intersecting_builder.close()-- winding_hole = metafile_render._path_mask(opposite, Matrix(), (100, 100), "nonzero")- winding_filled = metafile_render._path_mask(same, Matrix(), (100, 100), "nonzero")- evenodd_hole = metafile_render._path_mask(same, Matrix(), (100, 100), "evenodd")- nested_island = metafile_render._path_mask(island, Matrix(), (100, 100), "nonzero")- self_intersecting = metafile_render._path_mask(self_intersecting_builder.build(), Matrix(), (100, 100), "evenodd")-- assert winding_hole.getpixel((20, 20)) == 255- assert winding_hole.getpixel((30, 30)) == 0- assert winding_filled.getpixel((50, 50)) == 255- assert evenodd_hole.getpixel((50, 50)) == 0- assert nested_island.getpixel((30, 30)) == 0- assert nested_island.getpixel((50, 50)) == 255- assert self_intersecting.getbbox() is not 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)- inner_builder = PathBuilder()- inner_builder.move_to((35.0, 35.0))- inner_builder.line_to((65.0, 35.0))- inner_builder.line_to((65.0, 65.0))- inner_builder.line_to((35.0, 65.0))- inner_builder.close()- inner = inner_builder.build()- copy_outer = ClipOperation(outer, "copy", "nonzero")- copy_inner = ClipOperation(inner, "copy", "nonzero")-- intersection = metafile_render._clip_mask((copy_outer, ClipOperation(inner, "and", "nonzero")), Matrix(), (100, 100))- union = metafile_render._clip_mask((copy_inner, ClipOperation(outer, "or", "nonzero")), Matrix(), (100, 100))- xor = metafile_render._clip_mask((copy_inner, ClipOperation(outer, "xor", "nonzero")), Matrix(), (100, 100))- difference = metafile_render._clip_mask((copy_outer, ClipOperation(inner, "diff", "nonzero")), Matrix(), (100, 100))-- assert intersection is not None and intersection.getpixel((50, 50)) == 255 and intersection.getpixel((20, 20)) == 0- assert union is not None and union.getpixel((50, 50)) == 255 and union.getpixel((20, 20)) == 255- assert xor is not None and xor.getpixel((50, 50)) == 0 and xor.getpixel((20, 20)) == 255- assert difference is not None and difference.getpixel((50, 50)) == 0 and difference.getpixel((20, 20)) == 255---def test_adaptive_cubic_flattening_respects_error_and_point_budget() -> None:- """验证更严格 flatness 产生更多点且离散点预算可以稳定终止。"""- builder = PathBuilder()- builder.move_to((0.0, 0.0))- builder.cubic_to((0.0, 100.0), (100.0, 100.0), (100.0, 0.0))- path = builder.build()-- coarse = flatten_path(path, flatness=10.0)[0][0]- fine = flatten_path(path, flatness=0.1)[0][0]-- assert fine[-1] == coarse[-1] == (100.0, 0.0)- assert len(fine) > len(coarse)- with pytest.raises(MetafileResourceLimitError, match="max_flattened_points=2"):- flatten_path(path, flatness=0.1, budget=FlattenBudget(limit=2))---def test_stroke_mask_honors_caps_and_svg_miter_limit() -> None:- """验证 flat/square/round 端帽差异以及 SVG 保留 DC miter limit。"""- subpaths = [([(20.0, 50.0), (80.0, 50.0)], False)]- flat = metafile_render._stroke_mask(- subpaths,- size=(100, 100),- width=10.0,- pen=Pen(cap="flat"),- dashes=(),- miter_limit=10.0,- budget=FlattenBudget(),- )- square = metafile_render._stroke_mask(- subpaths,- size=(100, 100),- width=10.0,- pen=Pen(cap="square"),- dashes=(),- miter_limit=10.0,- budget=FlattenBudget(),- )- round_cap = metafile_render._stroke_mask(- subpaths,- size=(100, 100),- width=10.0,- pen=Pen(cap="round"),- dashes=(),- miter_limit=10.0,- budget=FlattenBudget(),- )- dashed = metafile_render._stroke_mask(- subpaths,- size=(100, 100),- width=6.0,- pen=Pen(cap="flat"),- dashes=(10.0, 10.0),- miter_limit=10.0,- budget=FlattenBudget(),- )- corner = [([(20.0, 80.0), (50.0, 20.0), (80.0, 80.0)], False)]- miter = metafile_render._stroke_mask(- corner,- size=(100, 100),- width=12.0,- pen=Pen(cap="flat", join="miter"),- dashes=(),- miter_limit=10.0,- budget=FlattenBudget(),- )- bevel = metafile_render._stroke_mask(- corner,- size=(100, 100),- width=12.0,- pen=Pen(cap="flat", join="bevel"),- dashes=(),- miter_limit=10.0,- budget=FlattenBudget(),- )- svg = render_metafile(- build_emf(- [- emf_set_miter_limit(3.5),- emf_begin_path(),- emf_move_to(10, 10),- emf_line_to(90, 90),- emf_end_path(),- emf_stroke_path(),- ]- ),- output_format="svg",- ).data-- assert flat.getpixel((16, 50)) == 0- assert square.getpixel((16, 50)) == 255- assert round_cap.getpixel((16, 50)) == 255- assert dashed.getpixel((25, 50)) == 255- assert dashed.getpixel((35, 50)) == 0- assert miter.getbbox() is not None and bevel.getbbox() is not None- assert miter.getbbox()[1] < bevel.getbbox()[1]- assert b'stroke-miterlimit="3.5"' in svg---def test_bitmap_source_crop_preserves_empty_and_partial_destination_mapping() -> None:- """验证完全越界 source 不绘制,部分交集只映射到对应 destination 子区域。"""- image = Image.new("RGBA", (2, 2), "red")- destination = ((0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0))-- outside, outside_fraction = metafile_render._crop_source(image, Rect(10.0, 10.0, 12.0, 12.0))- partial, partial_fraction = metafile_render._crop_source(image, Rect(-1.0, 0.0, 1.0, 2.0))- mirrored, mirrored_fraction = metafile_render._crop_source(image, Rect(3.0, 0.0, -1.0, 2.0))-- assert outside is None- assert outside_fraction == Rect(0.0, 0.0, 0.0, 0.0)- assert partial is not None and partial.size == (1, 2)- assert partial_fraction == Rect(0.5, 0.0, 1.0, 1.0)- assert mirrored is not None and mirrored.size == (2, 2)- assert mirrored_fraction == Rect(0.25, 0.0, 0.75, 1.0)- assert metafile_render._crop_destination(destination, partial_fraction) == (- (50.0, 0.0),- (100.0, 0.0),- (100.0, 100.0),- (50.0, 100.0),- )---def test_placeable_wmf_renders_vector_content() -> None:- """验证 placeable WMF 的 checksum、对象表和逻辑尺寸进入 PNG。"""- result = render_metafile(basic_wmf())- image = _open_result(result.data)-- assert result.source_format == "wmf"- assert (result.width, result.height) == (144, 144)- assert not result.partial- assert image.getbbox() is not None- assert image.getpixel((72, 72))[1] > 150---def test_wmf_roundrect_uses_record_parameter_order() -> None:- """验证 META_ROUNDRECT 按 Height/Width/Bottom/Right/Top/Left 解码。"""- payload = struct.pack("<hhhhhh", 100, 300, 900, 800, 200, 100)- document = metafile_parser.parse_metafile(build_placeable_wmf([wmf_record(0x061C, payload)]))- command = next(command for command in document.commands if isinstance(command, DrawPathCommand))-- assert path_bounds(command.path) == Rect(100.0, 200.0, 800.0, 900.0)- 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())- 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) == 2- assert (logical_width, logical_height) == (144, 144)- with Image.open(BytesIO(fallback)) as image:- 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。"""+ """通过公开 API 的资源错误验证 Office 消费者可靠回退到 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)+ png = render_metafile(data, output_format="png")+ render = Mock(side_effect=[MetafileResourceLimitError("generated SVG exceeds budget"), png])+ monkeypatch.setattr(office_image, "render_metafile", render)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")-+ data_uri = office_image.serialize_office_image(data, part_name="image.emf", content_type="image/emf")assert data_uri is not Noneassert data_uri.startswith("data:image/png;base64,")- image_element.assert_not_called()---def test_emfplus_dual_uses_emf_fallback_and_only_is_rejected() -> None:- """验证 EMF+ Dual 播放 EMF fallback,Only 返回稳定不支持错误。"""- records = [emfplus_comment(dual=True), emf_create_brush(1, 0x0000FF00), emf_select_object(1), emf_rectangle(5, 5, 95, 95)]- dual = render_metafile(build_emf(records))-- assert dual.emfplus_mode == "dual"- assert _open_result(dual.data).getbbox() is not None-- only_data = build_emf([emfplus_comment(dual=False), emf_rectangle(5, 5, 95, 95)])- with pytest.raises(MetafileUnsupportedError, match=r"EMF\+ Only"):- render_metafile(only_data)---def test_unknown_drawing_record_keeps_partial_result() -> None:- """验证未知绘图 record 被跳过但其他内容继续输出。"""- data = build_emf([emf_record(118, b"\x00" * 16), emf_rectangle(5, 5, 95, 95)])- result = render_metafile(data)-- assert result.partial- assert any(diagnostic.code == "unsupported_emf_record" for diagnostic in result.diagnostics)- assert _open_result(result.data).getbbox() is not None---def test_malformed_record_and_emf_signature_fail_closed() -> None:- """验证截断 record 与伪造签名均返回稳定 malformed 错误。"""- valid = bytearray(build_emf([emf_rectangle(5, 5, 95, 95)]))- valid[92:96] = (0x7FFFFFFC).to_bytes(4, "little")- with pytest.raises(MetafileMalformedError):- render_metafile(bytes(valid))- with pytest.raises(MetafileMalformedError):- render_metafile(b"not-a-metafile")---def test_canvas_is_downscaled_to_fixed_pixel_budget() -> None:- """验证巨大物理 frame 只会触发等比缩放而不会分配无界画布。"""- data = build_emf([emf_rectangle(0, 0, 100, 100)], frame=(0, 0, 254000, 254000))- result = render_metafile(data)-- assert result.width * result.height <= 16_000_000- assert max(result.width, result.height) <= 8192- assert any(diagnostic.code == "canvas_downscaled" for diagnostic in result.diagnostics)---def test_fixed_record_point_and_state_limits_are_enforced(monkeypatch: pytest.MonkeyPatch) -> None:- """验证点数和 SaveDC 深度使用 metafile 专属固定安全预算。"""- polygon_payload = (- b"\x00" * 16- + (3).to_bytes(4, "little")- + b"".join(value.to_bytes(4, "little", signed=True) for value in (0, 0, 50, 0, 25, 50))- )- monkeypatch.setattr(metafile_parser, "MAX_POINTS_PER_RECORD", 2)- with pytest.raises(MetafileResourceLimitError, match="max_points_per_record"):- render_metafile(build_emf([emf_record(3, polygon_payload)]))-- monkeypatch.setattr(metafile_parser, "MAX_POINTS_PER_RECORD", 1_000_000)- monkeypatch.setattr(metafile_parser, "MAX_STATE_DEPTH", 1)- with pytest.raises(MetafileResourceLimitError, match="max_state_depth"):- render_metafile(build_emf([emf_savedc(), emf_savedc(), emf_rectangle(1, 1, 10, 10)]))-- oversized_dib = bytearray(emf_stretch_dib())- oversized_dib[84:88] = (100_000).to_bytes(4, "little", signed=True)- oversized_dib[88:92] = (100_000).to_bytes(4, "little", signed=True)- with pytest.raises(MetafileResourceLimitError, match="DIB dimensions"):- render_metafile(build_emf([bytes(oversized_dib)]))-- monkeypatch.setattr(metafile_render, "MAX_RENDER_WORK_PIXELS", 1)- with pytest.raises(MetafileResourceLimitError, match="max_render_work_pixels"):- render_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)])- svg = render_metafile(data, output_format="svg").data-- assert b"<script>" not in svg- assert b"<" in svg- assert b">" in svg- assert b"&" in svg- assert svg.index(b"<rect") < svg.index(b"<text")---def test_raster_operations_use_exact_bitwise_channels() -> None:- """验证常见 ROP2/ROP3 不使用颜色明暗近似替代位运算。"""- destination = bytes((0x0F, 0x55, 0xAA))- source = bytes((0x33, 0x0F, 0xF0))-- assert metafile_render._bitwise_channel_bytes(destination, source, "xor") == bytes((0x3C, 0x5A, 0x5A))- assert metafile_render._bitwise_channel_bytes(destination, source, "and") == bytes((0x03, 0x05, 0xA0))- assert metafile_render._bitwise_channel_bytes(destination, source, "or") == bytes((0x3F, 0x5F, 0xFA))- assert metafile_render._bitwise_channel_bytes(destination, source, "not_source") == bytes((0xCC, 0xF0, 0x0F))- assert metafile_render._bitwise_channel_bytes(destination, source, "not_xor") == bytes((0xC3, 0xA5, 0xA5))+ assert [call.kwargs["output_format"] for call in render.call_args_list] == ["svg", "png"]def test_non_windows_office_serializer_returns_generated_svg(monkeypatch: pytest.MonkeyPatch) -> None:@@ -1032,26 +329,3 @@ def test_odf_models_emit_rendered_emf_svg(assert imagesassert all(image.startswith("data:image/svg+xml;base64,") for image in images)--[email protected]("data", [build_emf([emf_rectangle(5, 5, 95, 95)]), basic_wmf()])-def test_every_truncated_prefix_fails_without_unexpected_exception(data: bytes) -> None:- """验证每个截断位置都只产生稳定格式错误,不泄漏 struct/Pillow 异常。"""- for size in range(len(data)):- with pytest.raises(MetafileError):- render_metafile(data[:size])--[email protected]("name", ["docx-icon.emf", "generic-icon.emf", "pptx-icon.emf", "xlsx-icon.emf"])-def test_real_python_pptx_emf_icons_render_without_partial_result(name: str) -> None:- """验证依赖包内真实 Office EMF 图标的文字、alpha 和裁剪组合。"""- template = Path(pptx.__file__).resolve().parent / "templates" / name- result = render_metafile(template.read_bytes())- image = _open_result(result.data)-- assert not result.partial- assert result.diagnostics == ()- assert image.width >= 100- assert image.height >= 90- assert image.getbbox() is not None- assert image.getchannel("A").getextrema()[1] == 255diff --git a/tests/unittest/test_html_security.py b/tests/unittest/test_html_security.pyindex ecd16b02..dcec1305 100644--- a/tests/unittest/test_html_security.py+++ b/tests/unittest/test_html_security.py@@ -21,14 +21,36 @@ def _generated_svg_data_uri(extra_markup: str = "") -> str:"""构造带 PNG fallback 的最小 MinerU 安全 SVG data URI。"""svg = ('<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1" viewBox="0 0 1 1" '- 'data-mineru-generated="wmf-emf">'- f'<metadata id="mineru-raster-fallback" data-mime="image/png">{_SAFE_PNG_BASE64}</metadata>'+ 'data-metafile-render="wmf-emf">'+ f'<metadata id="metafile-render-raster-fallback" data-mime="image/png">{_SAFE_PNG_BASE64}</metadata>''<path d="M 0 0 L 1 0 L 1 1 Z" fill="#000000"/>'f"{extra_markup}</svg>").encode()return f"data:image/svg+xml;base64,{base64.b64encode(svg).decode('ascii')}"+ ("current", "obsolete"),+ [+ (b"data-metafile-render", b"data-mineru-generated"),+ (b"metafile-render-raster-fallback", b"mineru-raster-fallback"),+ (b"metafile-render-clip-1", b"mineru-clip-1"),+ ],+)+def test_generated_svg_accepts_new_contract_and_rejects_obsolete_markers(current: bytes, obsolete: bytes) -> None:+ """消费端只接受独立包的新 SVG 标识,不保留旧根属性、元数据或裁剪引用。"""+ data_uri = _generated_svg_data_uri(+ '<defs><clipPath id="metafile-render-clip-1"><path d="M 0 0 L 1 0 L 1 1 Z"/></clipPath></defs>'+ '<g clip-path="url(#metafile-render-clip-1)"><path d="M 0 0 L 1 1"/></g>'+ )+ payload = base64.b64decode(data_uri.split(",", 1)[1])+ fallback, width, height = image_payload.extract_generated_svg_fallback(payload)+ assert fallback.startswith(b"\x89PNG")+ assert (width, height) == (1, 1)+ with pytest.raises(ValueError):+ image_payload.extract_generated_svg_fallback(payload.replace(current, obsolete))++@pytest.mark.parametrize("content",[