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

feat(svg-to-pptx): compile inline numeric geometry

hugohe38b891acd0fb5
diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.py
index ea9ec232..a95469c1 100644
--- a/skills/ppt-master/scripts/finalize_svg.py
+++ b/skills/ppt-master/scripts/finalize_svg.py
@@ -52,6 +52,10 @@ from svg_finalize.align_embed_images import (
count_office_vector_refs_in_svg,
)
from svg_finalize.embed_icons import process_svg_file as embed_icons_in_file
+from svg_to_pptx.geometry_properties import (
+ GeometryStyleError,
+ materialize_inline_geometry_in_file,
+)
from svg_to_pptx.use_expander import (
UseExpansionError,
expand_local_use_references_in_file,
@@ -172,6 +176,16 @@ def finalize_project(
if not quiet:
print()
+ # Core normalization: downstream image/rect processors read XML geometry.
+ geometry_count = 0
+ for svg_file in svg_final.glob('*.svg'):
+ try:
+ geometry_count += materialize_inline_geometry_in_file(svg_file)
+ except (OSError, ET.ParseError, GeometryStyleError) as exc:
+ safe_print(
+ f"[ERROR] {svg_file.name}: inline geometry materialization failed: {exc}"
+ )
+ return False
# Step 2: Expand project icons, then standard same-document use references.
if options.get('embed_icons'):
if not quiet:
@@ -186,6 +200,15 @@ def finalize_project(
fallback_dir=icons_fallback_dir,
)
icons_count += count
+ for svg_file in svg_final.glob('*.svg'):
+ try:
+ geometry_count += materialize_inline_geometry_in_file(svg_file)
+ except (OSError, ET.ParseError, GeometryStyleError) as exc:
+ safe_print(
+ f"[ERROR] {svg_file.name}: expanded icon geometry "
+ f"materialization failed: {exc}"
+ )
+ return False
local_use_count = 0
for svg_file in svg_final.glob('*.svg'):
try:
@@ -205,6 +228,11 @@ def finalize_project(
else:
safe_print(" No local use references")
+ if not quiet and geometry_count:
+ safe_print(
+ f"[PREP] {geometry_count} inline geometry declaration(s) materialized"
+ )
+
# Step 3: Align (slice/meet) and Base64-embed all <image> in one pass.
# Replaces the former crop-images / fix-aspect / embed-images trio: the
# spatial transform (slice → crop, meet → fit-box) and the asset embed
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 a16d9f95..d9bfc007 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -666,10 +666,32 @@ def convert_svg_to_slide_shapes(
"""
tree = ET.parse(str(svg_path))
root = tree.getroot()
- viewport_width, viewport_height = _root_viewport_size(root)
trace_events: list[dict[str, Any]] | None = [] if trace_out is not None else None
trace_steps: list[dict[str, Any]] = []
+ from ..geometry_properties import (
+ GeometryStyleError,
+ materialize_inline_geometry_properties,
+ )
+
+ try:
+ geometry_count = materialize_inline_geometry_properties(root)
+ except GeometryStyleError as exc:
+ raise SvgNativeConversionError(
+ f'{svg_path.name}: inline geometry materialization failed: {exc}'
+ ) from exc
+ geometry_trace = None
+ if geometry_count:
+ geometry_trace = {
+ 'action': 'materialize-inline-geometry',
+ 'count': geometry_count,
+ }
+ trace_steps.append(geometry_trace)
+ if verbose:
+ print(f' Materialized {geometry_count} inline geometry declaration(s)')
+
+ viewport_width, viewport_height = _root_viewport_size(root)
+
# Expand project icon placeholders and static same-document <use>
# references before unsupported-element preflight.
from ..use_expander import (
@@ -686,6 +708,28 @@ def convert_svg_to_slide_shapes(
if verbose and expanded:
print(f' Expanded {expanded} <use data-icon="..."/> placeholder(s)')
+ try:
+ injected_geometry_count = materialize_inline_geometry_properties(root)
+ except GeometryStyleError as exc:
+ raise SvgNativeConversionError(
+ f'{svg_path.name}: expanded icon geometry materialization failed: {exc}'
+ ) from exc
+ if injected_geometry_count:
+ geometry_count += injected_geometry_count
+ if geometry_trace is None:
+ geometry_trace = {
+ 'action': 'materialize-inline-geometry',
+ 'count': geometry_count,
+ }
+ trace_steps.append(geometry_trace)
+ else:
+ geometry_trace['count'] = geometry_count
+ if verbose:
+ print(
+ f' Materialized {injected_geometry_count} inline geometry '
+ 'declaration(s) from expanded icons'
+ )
+
try:
expanded_local = expand_local_use_references(root)
except UseExpansionError as exc:
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 f7f53565..54a8cb4f 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -2600,8 +2600,14 @@ def convert_ellipse(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None
"""Convert SVG <ellipse> to DrawingML ellipse shape."""
raw_cx = svg_length_x(elem.get('cx'), ctx)
raw_cy = svg_length_y(elem.get('cy'), ctx)
- raw_rx = svg_length_x(elem.get('rx'), ctx)
- raw_ry = svg_length_y(elem.get('ry'), ctx)
+ rx_attr = elem.get('rx')
+ ry_attr = elem.get('ry')
+ raw_rx = svg_length_x(rx_attr, ctx) if rx_attr is not None else 0.0
+ raw_ry = svg_length_y(ry_attr, ctx) if ry_attr is not None else 0.0
+ if rx_attr is not None and ry_attr is None:
+ raw_ry = raw_rx
+ elif ry_attr is not None and rx_attr is None:
+ raw_rx = raw_ry
cx_ = ctx_x(raw_cx, ctx)
cy_ = ctx_y(raw_cy, ctx)
rx = raw_rx * ctx.scale_x
diff --git a/skills/ppt-master/scripts/svg_to_pptx/geometry_properties.py b/skills/ppt-master/scripts/svg_to_pptx/geometry_properties.py
new file mode 100644
index 00000000..b1e26a7b
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/geometry_properties.py
@@ -0,0 +1,140 @@
+"""Materialize the supported inline SVG geometry-property subset.
+
+SVG 2 lets selected geometry values participate in CSS. PPT Master does not
+run a CSS engine, but it can safely compile literal per-element ``style``
+declarations into the equivalent XML geometry attributes before any existing
+SVG post-processing or DrawingML conversion runs.
+"""
+
+from __future__ import annotations
+
+import copy
+import math
+import re
+from pathlib import Path
+from xml.etree import ElementTree as ET
+
+
+SVG_NS = 'http://www.w3.org/2000/svg'
+XLINK_NS = 'http://www.w3.org/1999/xlink'
+
+INLINE_GEOMETRY_PROPERTIES = {
+ 'rect': frozenset({'x', 'y', 'width', 'height', 'rx', 'ry'}),
+ 'circle': frozenset({'cx', 'cy', 'r'}),
+ 'ellipse': frozenset({'cx', 'cy', 'rx', 'ry'}),
+ 'image': frozenset({'x', 'y', 'width', 'height'}),
+ 'svg': frozenset({'x', 'y', 'width', 'height'}),
+ 'use': frozenset({'x', 'y', 'width', 'height'}),
+}
+
+_GEOMETRY_LIKE_PROPERTIES = frozenset({
+ 'x', 'y', 'width', 'height', 'rx', 'ry', 'cx', 'cy', 'r',
+ 'x1', 'y1', 'x2', 'y2', 'dx', 'dy', 'points', 'd',
+})
+_NON_NEGATIVE_PROPERTIES = frozenset({'width', 'height', 'rx', 'ry', 'r'})
+_PX_LENGTH_RE = re.compile(
+ r'^\s*([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)\s*(px)?\s*$',
+ re.IGNORECASE,
+)
+
+
+class GeometryStyleError(ValueError):
+ """Reject inline geometry that cannot be compiled deterministically."""
+
+
+def _local_tag(elem: ET.Element) -> str:
+ tag = str(elem.tag)
+ return tag.rsplit('}', 1)[-1] if '}' in tag else tag
+
+
+def _format_number(value: float) -> str:
+ if abs(value) < 1e-12:
+ value = 0.0
+ return f'{value:.12g}'
+
+
+def _normalize_px_length(raw: str, tag: str, prop: str) -> str:
+ """Return one finite CSS px literal as a unitless SVG user value."""
+ match = _PX_LENGTH_RE.fullmatch(raw)
+ if match is None:
+ raise GeometryStyleError(
+ f'<{tag}> inline geometry {prop} requires a finite px literal; '
+ f'got {raw!r}'
+ )
+ value = float(match.group(1))
+ if not math.isfinite(value):
+ raise GeometryStyleError(
+ f'<{tag}> inline geometry {prop} must be finite; got {raw!r}'
+ )
+ if match.group(2) is None and value != 0:
+ raise GeometryStyleError(
+ f'<{tag}> inline geometry {prop} requires px for non-zero values; '
+ f'got {raw!r}'
+ )
+ if prop in _NON_NEGATIVE_PROPERTIES and value < 0:
+ raise GeometryStyleError(
+ f'<{tag}> inline geometry {prop} cannot be negative; got {raw!r}'
+ )
+ return _format_number(value)
+
+
+def materialize_inline_geometry_properties(root: ET.Element) -> int:
+ """Compile supported inline geometry declarations into XML attributes."""
+ materialized = 0
+ for elem in root.iter():
+ style = elem.get('style')
+ if not style:
+ continue
+ tag = _local_tag(elem)
+ supported = INLINE_GEOMETRY_PROPERTIES.get(tag, frozenset())
+ retained: list[str] = []
+ element_materialized = 0
+ for raw_declaration in style.split(';'):
+ declaration = raw_declaration.strip()
+ if not declaration:
+ continue
+ if ':' not in declaration:
+ retained.append(declaration)
+ continue
+ raw_name, raw_value = declaration.split(':', 1)
+ name = raw_name.strip().lower()
+ value = raw_value.strip()
+ if name not in _GEOMETRY_LIKE_PROPERTIES:
+ retained.append(declaration)
+ continue
+ if name not in supported:
+ raise GeometryStyleError(
+ f'<{tag}> does not support inline geometry property {name!r}; '
+ 'use the element\'s XML geometry attribute instead'
+ )
+ elem.set(name, _normalize_px_length(value, tag, name))
+ materialized += 1
+ element_materialized += 1
+
+ if element_materialized == 0:
+ continue
+ if retained:
+ elem.set('style', '; '.join(retained))
+ else:
+ elem.attrib.pop('style', None)
+ return materialized
+
+
+def validate_inline_geometry_properties(root: ET.Element) -> list[str]:
+ """Return inline geometry errors without mutating the caller's SVG tree."""
+ try:
+ materialize_inline_geometry_properties(copy.deepcopy(root))
+ except GeometryStyleError as exc:
+ return [str(exc)]
+ return []
+
+
+def materialize_inline_geometry_in_file(svg_path: Path) -> int:
+ """Materialize inline geometry in one SVG file in place."""
+ tree = ET.parse(str(svg_path))
+ count = materialize_inline_geometry_properties(tree.getroot())
+ if count:
+ ET.register_namespace('', SVG_NS)
+ ET.register_namespace('xlink', XLINK_NS)
+ tree.write(str(svg_path), encoding='unicode', xml_declaration=False)
+ return count
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py
index 4d8fdeac..fb69e84a 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py
@@ -26,6 +26,11 @@ from pathlib import Path
from typing import Any
from xml.etree import ElementTree as ET
+from ..geometry_properties import (
+ GeometryStyleError,
+ materialize_inline_geometry_properties,
+)
+
_NON_VISUAL_TAGS = frozenset({"defs", "title", "desc", "metadata", "style"})
_STRUCTURE_ATTRS = frozenset({
@@ -705,6 +710,13 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
f"{svg_path.name}: unable to parse SVG structure metadata: {exc}"
) from exc
+ try:
+ materialize_inline_geometry_properties(root)
+ except GeometryStyleError as exc:
+ raise TemplateStructureError(
+ f"{svg_path.name}: invalid inline geometry: {exc}"
+ ) from exc
+
if _local_tag(root) != "svg":
raise TemplateStructureError(f"{svg_path.name}: root element must be <svg>")