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 geometry length contracts

hugohe3f802abffb4c7
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index dc109694..4ceeb003 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -8,7 +8,7 @@ Other files link here instead of restating its contracts.
| Section | Owns | Strength |
|---|---|---|
| §1 Required Foundation, Forbidden Features, and Conditional Interfaces | XML validity, the closed generated-authoring surface, structural blacklist, native line ends, image clipping, static local reuse, and imported/authored native-shape semantics | Required / Forbidden / Conditional |
-| §2 Conditional Compatibility Mappings | Literal inline geometry and the approximate group-opacity compatibility boundary | Conditional / Default |
+| §2 Conditional Compatibility Mappings | Direct geometry-length grammar, literal inline geometry, and the approximate group-opacity compatibility boundary | Required / Conditional / Default |
| §3 Canvas Format Quick Reference | Pointer to the complete canvas catalog | Reference |
| §4 Required Page Contract and Conditional Packaging | Complete-page authority, semantic markers, editable text/grouping, and package promotion | Required / Conditional |
| §5 Workflow Authority | Pointer to the serial post-processing/export procedure | Workflow pointer |
@@ -209,8 +209,8 @@ the original `<use>` / `<symbol>` structure.
|---|---|
| Reference syntax | Author new SVG with the SVG 2 form `href="#id"`. Legacy `xlink:href="#id"` remains read-compatible and Live Preview normalizes it to `href`; if both attributes exist, their values MUST match. |
| Referenced target | One of `<symbol>`, `<g>`, `<use>`, `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<path>`, `<polygon>`, `<polyline>`, `<text>`, or `<image>`. Nested local `<use>` is recursively expanded. |
-| Instance position | `<use x>` / `<use y>` are finite unitless or `px` values; omitted values default to `0`. |
-| Symbol viewport | A referenced `<symbol>` MUST have a finite four-number `viewBox` with positive width/height. Its `<use>` MUST have positive finite unitless or `px` `width` and `height`. |
+| Instance position | Generated `<use x>` / `<use y>` use finite unitless values; an explicit `px` suffix is read-compatible. Omitted values default to `0`. |
+| Symbol viewport | A referenced `<symbol>` MUST have a finite four-number `viewBox` with positive width/height. Its `<use>` MUST have positive finite unitless `width` and `height`; an explicit `px` suffix is read-compatible. |
| Aspect ratio | Default/aligned `meet` values and plain `preserveAspectRatio="none"` are supported. `slice`, `refX`, and `refY` are forbidden. |
| Viewport boundary | Symbol artwork MUST stay inside its `viewBox`; expansion does not reproduce symbol overflow clipping. |
| Internal references | Author exact `href="#id"` and `url(#id)` fragments. The expander also reads legacy `xlink:href="#id"` and rewrites all instance-local cloned IDs. |
@@ -388,7 +388,30 @@ hyperlinks.
## 2. Conditional Compatibility Mappings
-### 2.1 Literal Inline Geometry
+### 2.1 Literal Geometry Lengths and Inline Geometry
+
+**Hard rule — direct geometry length grammar**: New generated SVG writes the
+following XML geometry values and `stroke-width` as finite unitless ordinary
+decimals in the page `viewBox` coordinate space, for example `x="120"` and
+`stroke-width="2"`. The explicit `px` suffix is read-compatible and receives a
+recommendation warning. No other unit is registered for this surface.
+
+| Element / surface | Direct length attributes |
+|---|---|
+| `<svg>`, `<rect>`, `<image>`, `<use>` | `x`, `y`, `width`, `height`; `<rect>` also `rx`, `ry` |
+| `<circle>` | `cx`, `cy`, `r` |
+| `<ellipse>` | `cx`, `cy`, `rx`, `ry` |
+| `<line>` | `x1`, `y1`, `x2`, `y2` |
+| `<text>` / positional `<tspan>` | `x`, `y`; `<tspan>` also `dx`, `dy` |
+| Any supported painted element | `stroke-width` |
+
+`width`, `height`, `r`, `rx`, `ry`, and `stroke-width` must be non-negative;
+the stricter positive `<use>` symbol-viewport rule remains in §1.3. `pt`,
+`pc` / `pica`, `in`, `cm`, `mm`, `q`, `em`, `rem`, percentages, unknown units,
+non-finite values, expressions, scientific notation, leading plus signs, and
+trailing decimal points are invalid here even when generic SVG/CSS defines
+them. A missing attribute may use its documented SVG/project default; an
+explicitly supplied invalid value never falls back to that default.
The following geometry properties may appear in the same element's
`style="..."`. The pipeline materializes them as
diff --git a/skills/ppt-master/scripts/svg_finalize/embed_icons.py b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
index 46603f37..f747840b 100644
--- a/skills/ppt-master/scripts/svg_finalize/embed_icons.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
@@ -56,6 +56,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from svg_to_pptx.drawingml.utils import parse_project_geometry_length # noqa: E402
configure_utf8_stdio()
@@ -312,7 +313,7 @@ def parse_use_element(use_match: str) -> dict[str, str | float]:
for attr in ['x', 'y', 'width', 'height']:
value = _attr_value(use_match, attr)
if value is not None:
- attrs[attr] = float(value)
+ attrs[attr] = parse_project_geometry_length(value, attr)
# Extract fill color
fill_value = _attr_value(use_match, 'fill')
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 2666e702..8646b6d9 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -57,11 +57,15 @@ try:
DRAWINGML_TEXT_FONT_SIZE_MAX as _DRAWINGML_TEXT_FONT_SIZE_MAX,
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,
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,
matrix_multiply as _matrix_multiply,
parse_transform_matrix as _parse_transform_matrix,
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_svg_color as _parse_export_color,
parse_svg_length as _parse_export_length,
rect_to_dml_xfrm as _rect_to_dml_xfrm,
@@ -71,11 +75,15 @@ except ImportError:
_DRAWINGML_TEXT_FONT_SIZE_MAX = None
_DRAWINGML_TEXT_FONT_SIZE_MIN = None
_IDENTITY_MATRIX = None
+ _format_project_geometry_length = None
_font_px_to_hpt = None
+ _is_canonical_project_geometry_length = None
+ _iter_project_geometry_lengths = None
_matrix_multiply = None
_parse_transform_matrix = None
_parse_export_font_family = None
_parse_inline_style = None
+ _parse_project_geometry_length = None
_parse_export_color = None
_parse_export_length = None
_rect_to_dml_xfrm = None
@@ -1056,6 +1064,9 @@ class SVGQualityChecker:
# 2. Check forbidden elements
self._check_forbidden_elements(content, root, result)
+ # 2a. Validate direct geometry lengths and stroke widths.
+ self._check_geometry_length_values(root, result)
+
# 2b. Validate the closed authoring-property surface and
# conditional definition interfaces before export.
self._check_authoring_property_contract(root, result)
@@ -2094,6 +2105,53 @@ class SVGQualityChecker:
result['errors'].extend(sorted(issues))
+ def _check_geometry_length_values(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Reject invalid project geometry and advise the unitless spelling."""
+ if (
+ _format_project_geometry_length is None
+ or _is_canonical_project_geometry_length is None
+ or _iter_project_geometry_lengths is None
+ or _parse_project_geometry_length is None
+ ):
+ result['warnings'].append(
+ "Unable to import svg_to_pptx geometry length validators; "
+ "native export will still validate project geometry."
+ )
+ return
+
+ errors: set[str] = set()
+ recommendations: Counter[tuple[str, str, str]] = Counter()
+ examples: Dict[tuple[str, str, str], List[str]] = defaultdict(list)
+
+ for elem, attribute, raw, source in _iter_project_geometry_lengths(root):
+ label = f'{_element_label(elem)} {source}'
+ try:
+ value = _parse_project_geometry_length(raw, attribute)
+ except ValueError as exc:
+ errors.add(f"{label} {attribute}={raw!r}: {exc}")
+ continue
+ if _is_canonical_project_geometry_length(raw):
+ continue
+ normalized = _format_project_geometry_length(value)
+ key = (attribute, raw, normalized)
+ recommendations[key] += 1
+ if label not in examples[key] and len(examples[key]) < 3:
+ examples[key].append(label)
+
+ result['errors'].extend(sorted(errors))
+ for (attribute, raw, normalized), count in sorted(recommendations.items()):
+ shown_examples = ', '.join(examples[(attribute, raw, normalized)])
+ result['warnings'].append(
+ f"Recommendation: project geometry {attribute}={raw!r} is "
+ f"converter-compatible in {count} location(s) ({shown_examples}); "
+ f"generated SVG should prefer the unitless px spelling "
+ f'{attribute}="{normalized}". No change is required for export.'
+ )
+
def _check_font_size_values(self, content: str, result: Dict):
"""Keep supported font-size units compatible and recommend unitless px."""
canonical_re = re.compile(r'^(?:\d+(?:\.\d+)?|\.\d+)$')
@@ -2115,7 +2173,11 @@ class SVGQualityChecker:
drawingml_out_of_range = set()
compatible_noncanonical = set()
for raw in values:
- parsed_px = _parse_export_length(raw, math.nan, font_size=16)
+ try:
+ parsed_px = _parse_export_length(raw, math.nan, font_size=16)
+ except (TypeError, ValueError):
+ unsupported.add(raw)
+ continue
if not math.isfinite(parsed_px) or parsed_px < 0:
unsupported.add(raw)
continue
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 f34c2393..22891748 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -30,9 +30,14 @@ from .context import ConvertContext, ShapeResult
from .theme_colors import ThemeColorSpec
from .theme_fonts import ThemeFontSpec
from .utils import (
- SVG_NS, EMU_PER_PX,
- _extract_inheritable_styles, _f, _get_attr, parse_transform_matrix, resolve_url_id,
+ EMU_PER_PX,
+ SVG_NS,
+ _extract_inheritable_styles,
+ _get_attr,
parse_svg_length,
+ parse_transform_matrix,
+ project_geometry_length_errors,
+ resolve_url_id,
)
from .styles import (
build_effect_xml, build_fill_xml,
@@ -633,7 +638,12 @@ def _parse_svg_canvas(root: ET.Element) -> tuple[float, float, float, float]:
return x, y, w, h
except ValueError:
pass
- return 0.0, 0.0, _f(root.get('width')), _f(root.get('height'))
+ return (
+ 0.0,
+ 0.0,
+ parse_svg_length(root.get('width'), 0.0),
+ parse_svg_length(root.get('height'), 0.0),
+ )
def _is_full_canvas_rect(
@@ -654,7 +664,10 @@ def _is_full_canvas_rect(
)
):
return False
- if _f(elem.get('rx')) > 0 or _f(elem.get('ry')) > 0:
+ if (
+ parse_svg_length(elem.get('rx'), 0.0) > 0
+ or parse_svg_length(elem.get('ry'), 0.0) > 0
+ ):
return False
canvas_x, canvas_y, canvas_w, canvas_h = canvas
@@ -662,13 +675,13 @@ def _is_full_canvas_rect(
return False
tolerance = 0.5
- if abs(_f(elem.get('x')) - canvas_x) > tolerance:
+ if abs(parse_svg_length(elem.get('x'), 0.0) - canvas_x) > tolerance:
return False
- if abs(_f(elem.get('y')) - canvas_y) > tolerance:
+ if abs(parse_svg_length(elem.get('y'), 0.0) - canvas_y) > tolerance:
return False
- if abs(_f(elem.get('width')) - canvas_w) > tolerance:
+ if abs(parse_svg_length(elem.get('width'), 0.0) - canvas_w) > tolerance:
return False
- if abs(_f(elem.get('height')) - canvas_h) > tolerance:
+ if abs(parse_svg_length(elem.get('height'), 0.0) - canvas_h) > tolerance:
return False
fill = _get_attr(elem, 'fill', ctx)
@@ -676,7 +689,7 @@ def _is_full_canvas_rect(
return False
stroke = _get_attr(elem, 'stroke', ctx)
- stroke_width = _f(_get_attr(elem, 'stroke-width', ctx), 1.0)
+ stroke_width = parse_svg_length(_get_attr(elem, 'stroke-width', ctx), 1.0)
stroke_opacity = get_stroke_opacity(elem, ctx)
if stroke and stroke != 'none' and stroke_width > 0 and stroke_opacity != 0:
return False
@@ -1113,6 +1126,18 @@ def convert_svg_to_slide_shapes(
if verbose:
print(f' Materialized {geometry_count} inline geometry declaration(s)')
+ geometry_length_errors = project_geometry_length_errors(root)
+ if geometry_length_errors:
+ preview = '; '.join(geometry_length_errors[:8])
+ suffix = (
+ '' if len(geometry_length_errors) <= 8
+ else f'; +{len(geometry_length_errors) - 8} more'
+ )
+ raise SvgNativeConversionError(
+ f'{Path(svg_path).name}: invalid project geometry length(s): '
+ f'{preview}{suffix}'
+ )
+
viewport_width, viewport_height = _root_viewport_size(root)
# Expand project icon placeholders and static same-document <use>
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 bba58a7a..82d4fd44 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -2635,8 +2635,10 @@ def _resolve_clip_geometry(
# --- Rect with rx/ry → preset roundRect ---
if shape_tag == 'rect':
- rx = _f(shape.get('rx'))
- ry = _f(shape.get('ry'), rx)
+ rx_attr = shape.get('rx')
+ ry_attr = shape.get('ry')
+ rx = svg_length_x(rx_attr, ctx) if rx_attr is not None else 0.0
+ ry = svg_length_y(ry_attr, ctx) if ry_attr is not None else rx
if rx <= 0 and ry <= 0:
return DEFAULT # plain rect clip is a no-op
r = max(rx, ry)
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 ddd2fcfd..cab0e2a7 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import colorsys
import math
import re
+from collections.abc import Iterator
from xml.etree import ElementTree as ET
from pptx_shapes import validate_ooxml_xfrm
@@ -182,6 +183,34 @@ def _f(val: str | None, default: float = 0.0) -> float:
_LENGTH_RE = re.compile(r'^\s*([-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?)\s*([A-Za-z%]*)\s*$')
+_CANONICAL_PROJECT_GEOMETRY_LENGTH_RE = re.compile(
+ r'^-?(?:\d+(?:\.\d+)?|\.\d+)$'
+)
+PROJECT_GEOMETRY_LENGTH_ATTRIBUTES = {
+ 'svg': frozenset({'x', 'y', 'width', 'height'}),
+ 'rect': frozenset({'x', 'y', 'width', 'height', 'rx', 'ry'}),
+ 'circle': frozenset({'cx', 'cy', 'r'}),
+ 'ellipse': frozenset({'cx', 'cy', 'rx', 'ry'}),
+ 'line': frozenset({'x1', 'y1', 'x2', 'y2'}),
+ 'text': frozenset({'x', 'y'}),
+ 'tspan': frozenset({'x', 'y', 'dx', 'dy'}),
+ 'image': frozenset({'x', 'y', 'width', 'height'}),
+ 'use': frozenset({'x', 'y', 'width', 'height'}),
+}
+PROJECT_NON_NEGATIVE_LENGTH_ATTRIBUTES = frozenset({
+ 'width', 'height', 'r', 'rx', 'ry', 'stroke-width',
+})
+
+
+def _parse_svg_length_parts(val: str) -> tuple[float, str]:
+ """Parse one finite SVG length into its numeric part and lowercase unit."""
+ match = _LENGTH_RE.match(str(val))
+ if not match:
+ raise ValueError(f'SVG length must be one finite literal, got {val!r}')
+ number = float(match.group(1))
+ if not math.isfinite(number):
+ raise ValueError(f'SVG length must be finite, got {val!r}')
+ return number, match.group(2).lower()
def parse_svg_length(
@@ -196,18 +225,18 @@ def parse_svg_length(
Unitless and ``px`` values are already SVG px. Percentages need a caller
supplied reference length because SVG uses different bases for x, y,
width, height, and radii.
+
+ A default applies only when the attribute is absent. Present but malformed,
+ non-finite, unsupported, or context-free percentage values fail closed.
"""
if val is None:
return default
- match = _LENGTH_RE.match(str(val))
- if not match:
- return default
-
- number = float(match.group(1))
- unit = match.group(2).lower() or 'px'
+ number, unit = _parse_svg_length_parts(str(val))
if unit == '%':
if percent_base is None:
- return default
+ raise ValueError(
+ f'SVG percentage length requires a reference length, got {val!r}'
+ )
return percent_base * number / 100.0
if unit in ('', 'px'):
return number
@@ -224,8 +253,46 @@ def parse_svg_length(
if unit == 'q':
return number * 96.0 / 101.6
if unit in ('em', 'rem'):
+ if not math.isfinite(font_size):
+ raise ValueError(
+ f'SVG relative length requires a finite font size, got {val!r}'
+ )
return number * font_size
- return default
+ raise ValueError(f'Unsupported SVG length unit {unit!r} in {val!r}')
+
+
+def parse_project_geometry_length(raw: str, attribute: str) -> float:
+ """Parse one project geometry value without widening the authoring surface."""
+ number, unit = _parse_svg_length_parts(raw)
+ if unit not in {'', 'px'}:
+ raise ValueError(
+ f'uses unsupported unit {unit!r}; project geometry accepts only '
+ 'unitless values or the compatible px suffix'
+ )
+ numeric_literal = raw.strip()
+ if unit == 'px':
+ numeric_literal = numeric_literal[:-2].strip()
+ if not _CANONICAL_PROJECT_GEOMETRY_LENGTH_RE.fullmatch(numeric_literal):
+ raise ValueError(
+ 'uses an unsupported numeric spelling; use an ordinary decimal '
+ 'without a leading plus sign, exponent, or trailing decimal point'
+ )
+ if attribute in PROJECT_NON_NEGATIVE_LENGTH_ATTRIBUTES and number < 0:
+ raise ValueError('must be non-negative')
+ return number
+
+
+def is_canonical_project_geometry_length(raw: str) -> bool:
+ """Return whether a project geometry value uses the generated-SVG spelling."""
+ return bool(_CANONICAL_PROJECT_GEOMETRY_LENGTH_RE.fullmatch(raw.strip()))
+
+
+def format_project_geometry_length(value: float) -> str:
+ """Format a parsed project geometry value as a plain unitless decimal."""
+ if abs(value) < 1e-15:
+ return '0'
+ text = f'{value:.15f}'.rstrip('0').rstrip('.')
+ return '0' if text in {'', '-0'} else text
def svg_length_x(val: str | None, ctx: ConvertContext, default: float = 0.0) -> float:
@@ -538,6 +605,44 @@ def parse_inline_style(style_str: str | None) -> dict[str, str]:
return styles
+def iter_project_geometry_lengths(
+ root: ET.Element,
+) -> Iterator[tuple[ET.Element, str, str, str]]:
+ """Yield project geometry values as element, attribute, raw value, source."""
+ for elem in root.iter():
+ tag = elem.tag.rsplit('}', 1)[-1] if '}' in str(elem.tag) else str(elem.tag)
+ for attribute in sorted(
+ PROJECT_GEOMETRY_LENGTH_ATTRIBUTES.get(tag, frozenset())
+ ):
+ raw = elem.get(attribute)
+ if raw is not None:
+ yield elem, attribute, raw, 'attribute'
+
+ direct_stroke_width = elem.get('stroke-width')
+ if direct_stroke_width is not None:
+ yield elem, 'stroke-width', direct_stroke_width, 'attribute'
+
+ style_stroke_width = parse_inline_style(elem.get('style')).get('stroke-width')
+ if style_stroke_width is not None:
+ yield elem, 'stroke-width', style_stroke_width, 'inline style'
+
+
+def project_geometry_length_errors(root: ET.Element) -> list[str]:
+ """Return blocking project geometry errors for converter preflight."""
+ errors: list[str] = []
+ for elem, attribute, raw, source in iter_project_geometry_lengths(root):
+ tag = elem.tag.rsplit('}', 1)[-1] if '}' in str(elem.tag) else str(elem.tag)
+ elem_id = elem.get('id')
+ label = f'<{tag} id={elem_id!r}>' if elem_id else f'<{tag}>'
+ try:
+ parse_project_geometry_length(raw, attribute)
+ except ValueError as exc:
+ errors.append(
+ f'{label} {source} {attribute}={raw!r}: {exc}'
+ )
+ return errors
+
+
def _finite_float(raw: str) -> float:
"""Parse a finite floating-point number."""
value = float(raw)