Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(svg-to-pptx): enforce closed image aspect-ratio contracts

hugohe3a42cde45daa1
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.md
index 6cca885d..1f6bbe3e 100644
--- a/docs/powerpoint-svg-mapping.md
+++ b/docs/powerpoint-svg-mapping.md
@@ -126,9 +126,9 @@ Preset-shape selection and its exact atomic fragment contract are documented in
| PowerPoint feature | Project representation | PPTX result | Import and fidelity | Validation boundary |
|---|---|---|---|---|
| Picture | `<image>` with a project asset or data URI | `p:pic`, media part, and relationship | Reconstructed as `<image>` | Source must resolve, and dimensions must be valid |
-| Stretch picture to frame | `preserveAspectRatio="none"` | Stretched native picture frame | `Native-stable` | Use intentionally; it changes the source aspect ratio |
-| Crop picture to fill | Supported aligned `slice` form | Native `a:srcRect` crop | `Native-stable` when source dimensions are readable | Crop alignment and source metadata must be deterministic |
-| Fit picture inside frame | Supported aligned `meet` form | Native fitted picture frame | `Native-normalized` | Letterboxing/unused frame area follows the alignment contract |
+| Stretch picture to frame | `preserveAspectRatio="none"` | Stretched native picture frame | `Native-stable` | `none` must stand alone; it intentionally changes the source aspect ratio |
+| Crop picture to fill | One registered alignment plus explicit `slice` | Native `a:srcRect` crop | `Native-stable` when source dimensions are readable | Alignment is case-sensitive; unknown modes and extra tokens are errors |
+| Fit picture inside frame | Omitted default, or one registered alignment plus explicit `meet` | Native fitted picture frame | `Native-normalized` | Alignment-only shorthand is compatible input that receives a normalization recommendation |
| Picture transparency | Atomic image `opacity` | Native `a:alphaModFix` | `Native-stable` | Value must be finite and within the accepted opacity grammar |
| Picture clipped to a shape | Image-only registered `clip-path` | Picture preset or custom geometry | `Native-normalized` | Arbitrary masks are not accepted |
| Imported cropped picture | Nested crop SVG representation produced by import | Native `a:srcRect` on re-export | `Native-stable` within the crop contract | Do not manually generalize nested SVG into an unrestricted feature |
diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.md
index ec30cb64..d3c34742 100644
--- a/docs/zh/powerpoint-svg-mapping.md
+++ b/docs/zh/powerpoint-svg-mapping.md
@@ -126,9 +126,9 @@ preset 形状选择与精确原子片段合同见 [`native-shape-authoring.md`](
| PowerPoint 功能 | 项目表达 | PPTX 结果 | 回导与保真度 | 校验边界 |
|---|---|---|---|---|
| 图片 | 引用项目资产或 data URI 的 `<image>` | `p:pic`、media part 与 relationship | 重建为 `<image>` | 源必须可解析,尺寸必须合法 |
-| 图片拉伸填满框 | `preserveAspectRatio="none"` | 原生拉伸 picture frame | `Native-stable` | 应有意使用;它会改变源宽高比 |
-| 图片裁剪填充 | 受支持的对齐 `slice` 形式 | 原生 `a:srcRect` 裁剪 | 源尺寸可读时为 `Native-stable` | 裁剪对齐与源 metadata 必须确定 |
-| 图片适应框 | 受支持的对齐 `meet` 形式 | 原生 fitted picture frame | `Native-normalized` | 留白/未使用框区域遵循对齐合同 |
+| 图片拉伸填满框 | `preserveAspectRatio="none"` | 原生拉伸 picture frame | `Native-stable` | `none` 必须单独出现;它会有意改变源宽高比 |
+| 图片裁剪填充 | 一个已登记对齐值加显式 `slice` | 原生 `a:srcRect` 裁剪 | 源尺寸可读时为 `Native-stable` | 对齐值区分大小写;未知模式与额外 token 为 error |
+| 图片适应框 | 省略时使用默认值,或一个已登记对齐值加显式 `meet` | 原生 fitted picture frame | `Native-normalized` | 仅写对齐值是兼容输入,Checker 会给出规范化建议 |
| 图片透明度 | 原子 image `opacity` | 原生 `a:alphaModFix` | `Native-stable` | 值必须有限,并在可接受 opacity 语法内 |
| 图片裁成形状 | 仅作用于 image 的已登记 `clip-path` | picture preset 或 custom geometry | `Native-normalized` | 不接受任意 mask |
| 导入的裁剪图片 | 导入器产生的嵌套 crop SVG 表达 | 重新导出为原生 `a:srcRect` | crop 合同内为 `Native-stable` | 不得手工将嵌套 SVG 泛化为不受限功能 |
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index 5f3d8e95..07e69dc3 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -758,6 +758,17 @@ alpha `0.03–0.05`, increasing offset/radius, and optional same-family tint nea
| Uniform fade | `<image opacity="...">` | Native picture alpha |
| Shaped picture | §1.2 image-only `clip-path` | Preset/custom picture geometry |
+**Hard rule — closed image aspect-ratio grammar**: on `<image>`, omit
+`preserveAspectRatio` for the default `xMidYMid meet`, use `none` alone for
+stretch, or use one of the nine case-sensitive alignments (`xMinYMin`,
+`xMidYMin`, `xMaxYMin`, `xMinYMid`, `xMidYMid`, `xMaxYMid`, `xMinYMax`,
+`xMidYMax`, `xMaxYMax`) followed by explicit `meet` or `slice`. Generated SVG
+always includes the mode on an aligned value. An alignment without a mode and
+values needing whitespace normalization are compatible input and receive a
+Checker recommendation. Empty values, `defer`, unknown/wrong-case alignments or
+modes, `none` with a mode, and extra tokens are errors; the converter never
+guesses a fallback.
+
**Hard rule — fit/clip interaction**: a non-trivial clip disables `meet`
frame-fit. Match the image box to the source ratio or use `slice`. Do not apply
filters directly to `<image>`.
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 34671510..b2f58db7 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -58,9 +58,11 @@ try:
DRAWINGML_TEXT_FONT_SIZE_MIN as _DRAWINGML_TEXT_FONT_SIZE_MIN,
IDENTITY_MATRIX as _IDENTITY_MATRIX,
format_project_geometry_length as _format_project_geometry_length,
+ format_project_image_aspect_ratio as _format_project_image_aspect_ratio,
font_px_to_hpt as _font_px_to_hpt,
is_canonical_project_geometry_length as _is_canonical_project_geometry_length,
iter_project_geometry_lengths as _iter_project_geometry_lengths,
+ iter_project_image_aspect_ratios as _iter_project_image_aspect_ratios,
iter_project_stroke_styles as _iter_project_stroke_styles,
iter_project_transforms as _iter_project_transforms,
matrix_multiply as _matrix_multiply,
@@ -70,10 +72,12 @@ try:
parse_font_family as _parse_export_font_family,
parse_inline_style as _parse_inline_style,
parse_project_geometry_length as _parse_project_geometry_length,
+ parse_project_image_aspect_ratio as _parse_project_image_aspect_ratio,
parse_project_stroke_dasharray as _parse_project_stroke_dasharray,
parse_project_stroke_enum as _parse_project_stroke_enum,
parse_svg_color as _parse_export_color,
parse_svg_length as _parse_export_length,
+ project_image_aspect_ratio_errors as _project_image_aspect_ratio_errors,
project_stroke_style_errors as _project_stroke_style_errors,
project_transform_errors as _project_transform_errors,
rect_to_dml_xfrm as _rect_to_dml_xfrm,
@@ -84,9 +88,11 @@ except ImportError:
_DRAWINGML_TEXT_FONT_SIZE_MIN = None
_IDENTITY_MATRIX = None
_format_project_geometry_length = None
+ _format_project_image_aspect_ratio = None
_font_px_to_hpt = None
_is_canonical_project_geometry_length = None
_iter_project_geometry_lengths = None
+ _iter_project_image_aspect_ratios = None
_iter_project_stroke_styles = None
_iter_project_transforms = None
_matrix_multiply = None
@@ -96,10 +102,12 @@ except ImportError:
_parse_export_font_family = None
_parse_inline_style = None
_parse_project_geometry_length = None
+ _parse_project_image_aspect_ratio = None
_parse_project_stroke_dasharray = None
_parse_project_stroke_enum = None
_parse_export_color = None
_parse_export_length = None
+ _project_image_aspect_ratio_errors = None
_project_stroke_style_errors = None
_project_transform_errors = None
_rect_to_dml_xfrm = None
@@ -1097,13 +1105,16 @@ class SVGQualityChecker:
# 2b. Validate line-presentation grammar and mappings.
self._check_stroke_style_values(root, result)
- # 2c. Validate complete path-data and point-list grammar.
+ # 2c. Validate image fit/crop grammar and mappings.
+ self._check_image_aspect_ratio_values(root, result)
+
+ # 2d. Validate complete path-data and point-list grammar.
self._check_freeform_geometry_values(root, result)
- # 2d. Validate complete transform grammar and native mappings.
+ # 2e. Validate complete transform grammar and native mappings.
self._check_transform_values(root, result)
- # 2e. Validate the closed authoring-property surface and
+ # 2f. Validate the closed authoring-property surface and
# conditional definition interfaces before export.
self._check_authoring_property_contract(root, result)
self._check_paint_compatibility(root, result)
@@ -1112,10 +1123,10 @@ class SVGQualityChecker:
self._check_marker_contract(root, result)
self._check_clip_path_contract(root, result)
- # 2f. Validate the supported shadow/glow filter interface.
+ # 2g. Validate the supported shadow/glow filter interface.
self._check_filter_effects(root, result)
- # 2g. Validate gradient definitions, stops, and coordinates.
+ # 2h. Validate gradient definitions, stops, and coordinates.
self._check_gradient_interfaces(root, result)
# 3. Check font-size values
@@ -2290,6 +2301,53 @@ class SVGQualityChecker:
"required for export."
)
+ def _check_image_aspect_ratio_values(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Reject ambiguous image fit/crop values and advise canonical forms."""
+ helpers = (
+ _format_project_image_aspect_ratio,
+ _iter_project_image_aspect_ratios,
+ _parse_project_image_aspect_ratio,
+ _project_image_aspect_ratio_errors,
+ )
+ if any(helper is None for helper in helpers):
+ result['warnings'].append(
+ "Unable to import svg_to_pptx image aspect-ratio validators; "
+ "native export will still validate image fit/crop syntax."
+ )
+ return
+
+ result['errors'].extend(_project_image_aspect_ratio_errors(root))
+ recommendations: Counter[tuple[str, str]] = Counter()
+ examples: Dict[tuple[str, str], List[str]] = defaultdict(list)
+
+ for elem, raw in _iter_project_image_aspect_ratios(root):
+ try:
+ align, mode = _parse_project_image_aspect_ratio(raw)
+ except ValueError:
+ continue
+ normalized = _format_project_image_aspect_ratio(align, mode)
+ if raw == normalized:
+ continue
+ key = (raw, normalized)
+ recommendations[key] += 1
+ label = _element_label(elem)
+ if label not in examples[key] and len(examples[key]) < 3:
+ examples[key].append(label)
+
+ for (raw, normalized), count in sorted(recommendations.items()):
+ shown_examples = ', '.join(examples[(raw, normalized)])
+ result['warnings'].append(
+ f"Recommendation: image preserveAspectRatio={raw!r} is "
+ f"converter-compatible in {count} location(s) "
+ f"({shown_examples}); generated SVG should prefer "
+ f'preserveAspectRatio="{normalized}". No change is required '
+ "for export."
+ )
+
def _check_freeform_geometry_values(
self,
root: ET.Element,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
index a7809dda..98c6a2c8 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -39,6 +39,7 @@ from .utils import (
parse_transform_operations,
parse_transform_matrix,
project_geometry_length_errors,
+ project_image_aspect_ratio_errors,
project_stroke_style_errors,
project_transform_errors,
resolve_url_id,
@@ -116,6 +117,22 @@ def _require_project_stroke_styles(
)
+def _require_project_image_aspect_ratios(
+ root: ET.Element,
+ svg_path: Path | str,
+) -> None:
+ """Reject ambiguous image fit/crop values before native conversion."""
+ errors = project_image_aspect_ratio_errors(root)
+ if not errors:
+ return
+ preview = '; '.join(errors[:8])
+ suffix = '' if len(errors) <= 8 else f'; +{len(errors) - 8} more'
+ raise SvgNativeConversionError(
+ f'{Path(svg_path).name}: invalid project image aspect ratio(s): '
+ f'{preview}{suffix}'
+ )
+
+
# ---------------------------------------------------------------------------
# Transform & layout helpers
# ---------------------------------------------------------------------------
@@ -1161,6 +1178,7 @@ def convert_svg_to_slide_shapes(
_require_project_freeform_geometry(root, svg_path)
_require_project_stroke_styles(root, svg_path)
+ _require_project_image_aspect_ratios(root, svg_path)
_require_project_transforms(root, svg_path)
viewport_width, viewport_height = _root_viewport_size(root)
@@ -1221,6 +1239,7 @@ def convert_svg_to_slide_shapes(
# Recheck compiler-injected icon/use wrappers and cloned definition trees.
_require_project_stroke_styles(root, svg_path)
+ _require_project_image_aspect_ratios(root, svg_path)
_require_project_transforms(root, svg_path)
# Flatten positional <tspan> (those with x/y/non-zero dy) into independent
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
index c9e57d5e..74453aef 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -30,6 +30,7 @@ from .theme_colors import color_node_xml
from .theme_fonts import theme_font_tokens
from .utils import (
SVG_NS, XLINK_NS, ANGLE_UNIT, FONT_PX_TO_HUNDREDTHS_PT,
+ PROJECT_IMAGE_ASPECT_RATIO_ANCHORS,
px_to_emu, _f, _get_attr, parse_svg_length,
svg_length_x, svg_length_y, svg_length_size,
ctx_x, ctx_y, ctx_w, ctx_h,
@@ -39,6 +40,7 @@ from .utils import (
parse_inline_style, parse_font_family, is_cjk_char, estimate_text_width,
detect_text_lang, font_px_to_hpt, resolve_text_run_fonts,
is_thick_circle_shorthand, parse_project_geometry_length,
+ parse_project_image_aspect_ratio,
parse_project_stroke_dasharray,
matrix_multiply, parse_transform_matrix, parse_transform_operations,
transform_point, _xml_escape,
@@ -2760,14 +2762,6 @@ def _read_image_size(data: bytes) -> tuple[int | None, int | None]:
return (None, None)
-def _parse_preserve_aspect_ratio(par: str | None) -> tuple[str, str]:
- """Parse SVG preserveAspectRatio into ``(align, mode)``."""
- parts = (par or 'xMidYMid meet').strip().split()
- align = parts[0] if parts else 'xMidYMid'
- mode = parts[1] if len(parts) > 1 else 'meet'
- return align, mode
-
-
def _image_has_alpha(img: Any) -> bool:
"""Return whether a PIL image carries useful transparency."""
if img.mode in ('RGBA', 'LA'):
@@ -2918,7 +2912,9 @@ def _optimize_image_for_pptx(
if getattr(img, 'is_animated', False):
return img_data, img_format
- align, mode = _parse_preserve_aspect_ratio(elem.get('preserveAspectRatio'))
+ align, mode = parse_project_image_aspect_ratio(
+ elem.get('preserveAspectRatio')
+ )
target_w, target_h = _fit_full_image_target(
img.size[0],
img.size[1],
@@ -2976,8 +2972,7 @@ def _compute_slice_src_rect(
crop_w_total = max(0.0, img_w - visible_w)
crop_h_total = max(0.0, img_h - visible_h)
- x_anchor = {'xMin': 0.0, 'xMid': 0.5, 'xMax': 1.0}.get(align[:4], 0.5)
- y_anchor = {'YMin': 0.0, 'YMid': 0.5, 'YMax': 1.0}.get(align[4:], 0.5)
+ x_anchor, y_anchor = PROJECT_IMAGE_ASPECT_RATIO_ANCHORS[align]
crop_l = crop_w_total * x_anchor
crop_r = crop_w_total - crop_l
@@ -3007,7 +3002,9 @@ def _resolve_image_src_rect(
shrinks the picture frame to match image aspect ratio); none mode keeps
the legacy stretch behaviour intentionally.
"""
- align, mode = _parse_preserve_aspect_ratio(elem.get('preserveAspectRatio'))
+ align, mode = parse_project_image_aspect_ratio(
+ elem.get('preserveAspectRatio')
+ )
if align == 'none' or mode != 'slice':
return '' # meet handled by frame fit; none → stretch is correct per SVG spec
@@ -3045,7 +3042,9 @@ def _resolve_image_meet_fit(
- intrinsic image dimensions cannot be read
- frame already matches image ratio (no-op)
"""
- align, mode = _parse_preserve_aspect_ratio(elem.get('preserveAspectRatio'))
+ align, mode = parse_project_image_aspect_ratio(
+ elem.get('preserveAspectRatio')
+ )
if align == 'none' or mode == 'slice':
return None
@@ -3063,8 +3062,7 @@ def _resolve_image_meet_fit(
if abs(fit_w - box_w) < 0.5 and abs(fit_h - box_h) < 0.5:
return None # already matches — no adjustment
- x_anchor = {'xMin': 0.0, 'xMid': 0.5, 'xMax': 1.0}.get(align[:4], 0.5)
- y_anchor = {'YMin': 0.0, 'YMid': 0.5, 'YMax': 1.0}.get(align[4:], 0.5)
+ x_anchor, y_anchor = PROJECT_IMAGE_ASPECT_RATIO_ANCHORS[align]
dx = (box_w - fit_w) * x_anchor
dy = (box_h - fit_h) * y_anchor
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
index 882e2358..6424e08b 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
@@ -1,7 +1,7 @@
"""Coordinate, transform, color, and font helpers for DrawingML conversion.
-See references/shared-standards.md §2.1, §6.6, and §6.8 for project geometry,
-line-presentation, and transform authoring contracts.
+See references/shared-standards.md §2.1, §6.5, §6.6, and §6.8 for project
+geometry, image-fit, line-presentation, and transform authoring contracts.
"""
from __future__ import annotations
@@ -149,6 +149,18 @@ PROJECT_STROKE_ENUM_VALUES = {
'stroke-linejoin': frozenset({'bevel', 'miter', 'round'}),
'vector-effect': frozenset({'none', 'non-scaling-stroke'}),
}
+PROJECT_IMAGE_ASPECT_RATIO_ANCHORS = {
+ 'xMinYMin': (0.0, 0.0),
+ 'xMidYMin': (0.5, 0.0),
+ 'xMaxYMin': (1.0, 0.0),
+ 'xMinYMid': (0.0, 0.5),
+ 'xMidYMid': (0.5, 0.5),
+ 'xMaxYMid': (1.0, 0.5),
+ 'xMinYMax': (0.0, 1.0),
+ 'xMidYMax': (0.5, 1.0),
+ 'xMaxYMax': (1.0, 1.0),
+}
+PROJECT_IMAGE_ASPECT_RATIO_MODES = frozenset({'meet', 'slice'})
THICK_CIRCLE_COVERAGE_TOLERANCE = 1.0
@@ -315,6 +327,44 @@ def format_project_geometry_length(value: float) -> str:
return '0' if text in {'', '-0'} else text
+def parse_project_image_aspect_ratio(raw: str | None) -> tuple[str, str]:
+ """Parse the closed project ``<image>`` aspect-ratio grammar."""
+ if raw is None:
+ return 'xMidYMid', 'meet'
+
+ text = raw.strip()
+ if not text:
+ raise ValueError('must not be empty; omit the attribute for the default')
+
+ parts = text.split()
+ align = parts[0]
+ if align == 'none':
+ if len(parts) != 1:
+ raise ValueError('value "none" must appear alone')
+ return align, 'meet'
+
+ if align not in PROJECT_IMAGE_ASPECT_RATIO_ANCHORS:
+ choices = ', '.join(PROJECT_IMAGE_ASPECT_RATIO_ANCHORS)
+ raise ValueError(
+ f'alignment must be "none" or one of: {choices}'
+ )
+ if len(parts) > 2:
+ raise ValueError('accepts at most one alignment and one mode token')
+
+ mode = parts[1] if len(parts) == 2 else 'meet'
+ if mode not in PROJECT_IMAGE_ASPECT_RATIO_MODES:
+ choices = ', '.join(sorted(PROJECT_IMAGE_ASPECT_RATIO_MODES))
+ raise ValueError(f'mode must be one of: {choices}')
+ return align, mode
+
+
+def format_project_image_aspect_ratio(align: str, mode: str) -> str:
+ """Format one parsed image aspect ratio for generated project SVG."""
+ if align == 'none':
+ return 'none'
+ return f'{align} {mode}'
+
+
def _parse_project_stroke_dasharray(
raw: str,
*,
@@ -1246,6 +1296,31 @@ def project_geometry_length_errors(root: ET.Element) -> list[str]:
return errors
+def iter_project_image_aspect_ratios(
+ root: ET.Element,
+) -> Iterator[tuple[ET.Element, str]]:
+ """Yield explicit ``preserveAspectRatio`` values from image elements."""
+ for elem in root.iter():
+ if _svg_element_tag(elem) != 'image':
+ continue
+ raw = elem.get('preserveAspectRatio')
+ if raw is not None:
+ yield elem, raw
+
+
+def project_image_aspect_ratio_errors(root: ET.Element) -> list[str]:
+ """Return blocking project image aspect-ratio errors for preflight."""
+ errors: list[str] = []
+ for elem, raw in iter_project_image_aspect_ratios(root):
+ elem_id = elem.get('id')
+ label = f'<image id={elem_id!r}>' if elem_id else '<image>'
+ try:
+ parse_project_image_aspect_ratio(raw)
+ except ValueError as exc:
+ errors.append(f'{label} preserveAspectRatio={raw!r}: {exc}')
+ return errors
+
+
def _finite_float(raw: str) -> float:
"""Parse a finite floating-point number."""
value = float(raw)