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(checker): align SVG validation with export semantics

hugohe37b5e1de03eef
diff --git a/skills/ppt-master/references/svg-image-embedding.md b/skills/ppt-master/references/svg-image-embedding.md
index fe5b5917..f21a3314 100644
--- a/skills/ppt-master/references/svg-image-embedding.md
+++ b/skills/ppt-master/references/svg-image-embedding.md
@@ -135,16 +135,19 @@ python3 scripts/finalize_svg.py <project_path>
python3 scripts/svg_to_pptx.py <project_path>
```
-### Standalone: embed_images.py (advanced)
+### Standalone: align_embed_images.py (advanced)
For processing specific SVGs without the full pipeline:
```bash
-python3 scripts/svg_finalize/embed_images.py <svg_file> # Single file
-python3 scripts/svg_finalize/embed_images.py <project_path>/svg_output/*.svg # Batch
-python3 scripts/svg_finalize/embed_images.py --dry-run <project_path>/svg_output/*.svg # Preview
+python3 scripts/svg_finalize/align_embed_images.py <svg_file>
+python3 scripts/svg_finalize/align_embed_images.py --dry-run <svg_file>
```
+Use `finalize_svg.py --only align-images` for project-level batches. The old
+`crop-images`, `fix-aspect`, and `embed-images` step names are compatibility
+aliases only when invoked through `finalize_svg.py --only`.
+
---
## Best Practices
diff --git a/skills/ppt-master/references/template-designer.md b/skills/ppt-master/references/template-designer.md
index 248fd7f7..5175b899 100644
--- a/skills/ppt-master/references/template-designer.md
+++ b/skills/ppt-master/references/template-designer.md
@@ -194,7 +194,7 @@ When rewriting an existing template that contains the omitted sections, delete t
### 2. Inherit Design Specification
Templates must strictly follow the finalized template brief and the generated `design_spec.md`:
-- **Canvas dimensions**: `canvas_format` is not enough; root SVG `viewBox` matches `canvas_viewbox` in the design spec (`width` / `height`, if written, equal it)
+- **Canvas dimensions**: `canvas_format` is not enough; root SVG `viewBox` matches `canvas_viewbox` in the design spec. Root `width` / `height` are optional compatibility attributes and are not PPT Master canvas authority.
- **Source canvas**: when a PPTX/SVG reference is used, record `source_canvas_width`, `source_canvas_height`, and `source_viewbox`. If the output canvas differs from the source, normalize all geometry, typography, line heights, strokes, and image crop coordinates explicitly instead of relying on the shared aspect ratio.
- **Color scheme**: Uses primary, secondary, and accent colors from the spec
- **Font plan**: Uses the per-role font families declared in the spec
diff --git a/skills/ppt-master/scripts/batch_validate.py b/skills/ppt-master/scripts/batch_validate.py
index 2f83c8cb..9686ed1d 100644
--- a/skills/ppt-master/scripts/batch_validate.py
+++ b/skills/ppt-master/scripts/batch_validate.py
@@ -203,8 +203,8 @@ class BatchValidator:
f" Reference: examples/google_annual_report_ppt169_20251116/README.md")
if self.summary['svg_issues'] > 0:
- print(f" 2. Check and fix SVG viewBox settings")
- print(f" Ensure consistency with canvas format")
+ print(f" 2. Check SVG root viewBox settings")
+ print(f" The SVG root viewBox is the export canvas authority")
if self.summary['missing_spec'] > 0:
print(f" 3. Add design specification files")
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index fb167e18..6722df32 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -20,9 +20,7 @@ Unified post-processing entry point. This is the preferred way to run SVG cleanu
It aggregates:
- `embed_icons.py`
-- `crop_images.py`
-- `fix_image_aspect.py`
-- `embed_images.py`
+- `align_embed_images.py` (`crop-images` / `fix-aspect` / `embed-images` aliases route here)
- `flatten_tspan.py`
- `svg_rect_to_path.py`
@@ -179,15 +177,18 @@ python3 scripts/svg_finalize/svg_rect_to_path.py path/to/file.svg
Use when rounded corners must survive PowerPoint shape conversion.
-### `fix_image_aspect.py`
+### `align_embed_images.py`
```bash
-python3 scripts/svg_finalize/fix_image_aspect.py path/to/slide.svg
-python3 scripts/svg_finalize/fix_image_aspect.py 01_cover.svg 02_toc.svg
-python3 scripts/svg_finalize/fix_image_aspect.py --dry-run path/to/slide.svg
+python3 scripts/svg_finalize/align_embed_images.py path/to/slide.svg
+python3 scripts/svg_finalize/align_embed_images.py --dry-run path/to/slide.svg
```
-Use when embedded images stretch after PowerPoint shape conversion.
+Use for rare single-file diagnostics when image `slice` / `meet` alignment and
+Base64 embedding must be inspected outside `finalize_svg.py`. In normal project
+runs, use `python3 scripts/finalize_svg.py <project_path>`; the old
+`crop-images`, `fix-aspect`, and `embed-images` names remain accepted only as
+`finalize_svg.py --only` aliases for the merged `align-images` step.
### `embed_icons.py`
@@ -209,7 +210,7 @@ Use PowerPoint-safe transparency syntax:
| `<g opacity=\"...\">` | Set opacity on each child |
| `<image opacity=\"...\">` | Overlay with a mask layer |
-PowerPoint also has trouble with:
-- marker-based arrows
-- unsupported filters
-- direct SVG features not mapped to DrawingML
+PowerPoint also has trouble with unsupported filters and direct SVG features
+not mapped to DrawingML. Connector arrows may use qualified
+`marker-start` / `marker-end`; chunky or exotic arrows should be standalone
+`<path>` / `<polygon>` shapes.
diff --git a/skills/ppt-master/scripts/error_helper.py b/skills/ppt-master/scripts/error_helper.py
index 18462aa1..13eb6f73 100644
--- a/skills/ppt-master/scripts/error_helper.py
+++ b/skills/ppt-master/scripts/error_helper.py
@@ -75,10 +75,11 @@ class ErrorHelper:
'severity': 'warning'
},
'viewbox_mismatch': {
- 'message': 'SVG viewBox does not match canvas format',
+ 'message': 'SVG viewBox differs from the recorded canvas format',
'solutions': [
'Check the viewBox attribute of SVG files',
- 'Ensure it matches the project canvas format',
+ 'Treat the root viewBox as the actual canvas size',
+ 'If the project metadata is stale, export will use the SVG viewBox',
'PPT 16:9 should be: viewBox="0 0 1280 720"',
'PPT 4:3 should be: viewBox="0 0 1024 768"',
'Reference: references/canvas-formats.md'
@@ -100,8 +101,8 @@ class ErrorHelper:
'solutions': [
'Add the viewBox attribute to the SVG root element',
'Format: <svg viewBox="0 0 1280 720" ...>',
- 'Ensure width, height are consistent with viewBox',
- 'This is a mandatory requirement for SVG generation'
+ 'Root width/height are optional compatibility attributes',
+ 'The root viewBox is mandatory for SVG generation'
],
'severity': 'error'
},
diff --git a/skills/ppt-master/scripts/project_utils.py b/skills/ppt-master/scripts/project_utils.py
index d8bba432..98cfcc21 100644
--- a/skills/ppt-master/scripts/project_utils.py
+++ b/skills/ppt-master/scripts/project_utils.py
@@ -11,6 +11,7 @@ import re
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Tuple
+from xml.etree import ElementTree as ET
from console_encoding import configure_utf8_stdio
@@ -323,7 +324,6 @@ def validate_svg_viewbox(svg_files: List[Path], expected_format: Optional[str] =
List of warnings
"""
warnings = []
- viewbox_pattern = re.compile(r'viewBox\s*=\s*["\']([^"\']+)["\']')
viewboxes = set()
# Determine expected viewBox
@@ -333,27 +333,28 @@ def validate_svg_viewbox(svg_files: List[Path], expected_format: Optional[str] =
for svg_file in svg_files[:10]: # Check first 10 files
try:
- with open(svg_file, 'r', encoding='utf-8') as f:
- content = f.read(2000) # Only read first 2000 characters
- match = viewbox_pattern.search(content)
- if match:
- viewbox = match.group(1)
- viewboxes.add(viewbox)
-
- # If expected format is specified, check for match
- if expected_viewbox and viewbox != expected_viewbox:
- warnings.append(
- f"{svg_file.name}: viewBox '{viewbox}' does not match expected format "
- f"'{expected_format}' (expected: '{expected_viewbox}')"
- )
- else:
- warnings.append(f"{svg_file.name}: viewBox attribute not found")
+ viewbox = ET.parse(svg_file).getroot().get('viewBox')
+ if viewbox:
+ viewboxes.add(viewbox)
+
+ # If expected format is specified, check for match
+ if expected_viewbox and viewbox != expected_viewbox:
+ warnings.append(
+ f"{svg_file.name}: root viewBox '{viewbox}' differs from recorded "
+ f"project format '{expected_format}' ({expected_viewbox}); export uses "
+ f"the SVG viewBox as the canvas size"
+ )
+ else:
+ warnings.append(f"{svg_file.name}: root viewBox attribute not found")
except Exception as e:
warnings.append(f"{svg_file.name}: Failed to read - {e}")
# Check for multiple different viewBoxes
if len(viewboxes) > 1:
- warnings.append(f"Multiple different viewBox settings detected: {viewboxes}")
+ warnings.append(
+ f"Multiple different root viewBox settings detected: {viewboxes}; "
+ "confirm this mixed-canvas project is intentional"
+ )
return warnings
diff --git a/skills/ppt-master/scripts/svg_finalize/embed_icons.py b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
index b97238db..7f10e303 100644
--- a/skills/ppt-master/scripts/svg_finalize/embed_icons.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
@@ -230,6 +230,16 @@ def extract_paths_from_icon(icon_path: Path, target_color: str = '#000000') -> t
return elements, style, base_size
+def _attr_value(tag_text: str, attr: str) -> str | None:
+ """Return an attribute value from a raw tag, accepting either quote style."""
+ match = re.search(
+ rf'\b{re.escape(attr)}\s*=\s*(["\'])(.*?)\1',
+ tag_text,
+ re.DOTALL,
+ )
+ return match.group(2) if match else None
+
+
def parse_use_element(use_match: str) -> dict[str, str | float]:
"""
Parse attributes of a use element.
@@ -241,42 +251,42 @@ def parse_use_element(use_match: str) -> dict[str, str | float]:
Attribute dictionary
"""
attrs: dict[str, str | float] = {}
-
+
# Extract data-icon
- icon_match = re.search(r'data-icon="([^"]+)"', use_match)
- if icon_match:
- attrs['icon'] = icon_match.group(1)
-
+ icon_value = _attr_value(use_match, 'data-icon')
+ if icon_value:
+ attrs['icon'] = icon_value
+
# Extract numeric attributes
for attr in ['x', 'y', 'width', 'height']:
- match = re.search(rf'{attr}="([^"]+)"', use_match)
- if match:
- attrs[attr] = float(match.group(1))
-
+ value = _attr_value(use_match, attr)
+ if value is not None:
+ attrs[attr] = float(value)
+
# Extract fill color
- fill_match = re.search(r'fill="([^"]+)"', use_match)
- if fill_match:
- attrs['fill'] = fill_match.group(1)
+ fill_value = _attr_value(use_match, 'fill')
+ if fill_value is not None:
+ attrs['fill'] = fill_value
# Stroke-style icons may be authored with natural SVG semantics:
# fill="none" stroke="#HEX". Keep accepting fill as the canonical color
# carrier, but preserve stroke so outline icons do not collapse to none.
- stroke_match = re.search(r'stroke="([^"]+)"', use_match)
- if stroke_match:
- attrs['stroke'] = stroke_match.group(1)
+ stroke_value = _attr_value(use_match, 'stroke')
+ if stroke_value is not None:
+ attrs['stroke'] = stroke_value
# Live preview direct edits may write an absolute transform matrix back to
# the placeholder. Preserve it so the expanded icon matches the edited
# browser geometry instead of falling back to the original x/y placement.
- transform_match = re.search(r'transform="([^"]+)"', use_match)
- if transform_match:
- attrs['transform'] = transform_match.group(1)
+ transform_value = _attr_value(use_match, 'transform')
+ if transform_value is not None:
+ attrs['transform'] = transform_value
# Extract optional stroke-width override (stroke-style icons only).
# Tabler-outline ships at stroke-width=2; passing 1.5 reads thin, 3 reads bold.
- stroke_width_match = re.search(r'stroke-width="([^"]+)"', use_match)
- if stroke_width_match:
- attrs['stroke-width'] = stroke_width_match.group(1)
+ stroke_width_value = _attr_value(use_match, 'stroke-width')
+ if stroke_width_value is not None:
+ attrs['stroke-width'] = stroke_width_value
return attrs
@@ -386,9 +396,10 @@ def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, ver
content = svg_path.read_text(encoding='utf-8')
- # Match <use data-icon="xxx" ... /> elements
- use_pattern = r'<use\s+[^>]*data-icon="[^"]*"[^>]*/>'
- matches = list(re.finditer(use_pattern, content))
+ # Match self-closing <use data-icon="..."/> placeholders. Attribute
+ # parsing below accepts both single and double quotes.
+ use_pattern = r'<use\b(?=[^>]*\bdata-icon\s*=)[^>]*/>'
+ matches = list(re.finditer(use_pattern, content, re.IGNORECASE | re.DOTALL))
if not matches:
if verbose:
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index bbfa5bad..c45b2c73 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -17,6 +17,7 @@ import html
from pathlib import Path
from typing import List, Dict, Tuple
from collections import Counter, defaultdict
+from urllib.parse import unquote, urlsplit
from xml.etree import ElementTree as ET
from console_encoding import configure_utf8_stdio
@@ -73,9 +74,17 @@ try:
except ImportError:
_native_object_marker_warnings = None
+try:
+ from svg_finalize.embed_icons import (
+ resolve_icon_path as _resolve_icon_path,
+ )
+except ImportError:
+ _resolve_icon_path = None
+
HEX_VALUE_RE = re.compile(r"#[0-9A-Fa-f]{3,8}")
SVG_NS = "http://www.w3.org/2000/svg"
+XLINK_NS = "http://www.w3.org/1999/xlink"
# Fonts that survive direct PPTX typeface assignment on a typical Windows /
# macOS viewer without requiring a custom install. Keep this aligned with
@@ -136,6 +145,28 @@ def _design_spec_is_brand(spec_path: Path) -> bool:
return False
+def _local_name(elem: ET.Element) -> str:
+ """Return an XML element's namespace-free local tag name."""
+ tag = elem.tag
+ if not isinstance(tag, str):
+ return ''
+ return tag.rsplit('}', 1)[-1] if '}' in tag else tag
+
+
+def _parse_viewbox_values(viewbox: str) -> Tuple[float, float, float, float] | None:
+ """Parse a root viewBox into four numeric values."""
+ parts = re.split(r'[\s,]+', viewbox.strip())
+ if len(parts) != 4:
+ return None
+ try:
+ values = tuple(float(part) for part in parts)
+ except ValueError:
+ return None
+ if values[2] <= 0 or values[3] <= 0:
+ return None
+ return values
+
+
def _parse_placeholders_fallback(block: str) -> Dict[str, Tuple[str, ...]]:
"""Tiny YAML-free reader for the documented ``placeholders:`` shape.
@@ -325,22 +356,25 @@ class SVGQualityChecker:
# 6. Check image references (file existence and resolution)
self._check_image_references(content, svg_path, result)
- # 7. Check object-level animation anchor quality.
+ # 7. Check icon placeholders resolve before post-processing.
+ self._check_icon_placeholders(content, svg_path, result)
+
+ # 8. Check object-level animation anchor quality.
self._check_animation_group_ids(content, result)
- # 7b. Check <pattern> elements declare a PPTX preset.
+ # 8b. Check <pattern> elements declare a PPTX preset.
self._check_pattern_fills(content, result)
- # 7c. Check opt-in native table/chart markers before export.
+ # 8c. Check opt-in native table/chart markers before export.
self._check_native_object_markers(content, result)
- # 8. Check spec_lock drift (colors / font-family / font-size).
+ # 9. Check spec_lock drift (colors / font-family / font-size).
# Templates do not ship a spec_lock.md, so skip in template
# mode to avoid noise.
if not self.template_mode:
self._check_spec_lock_drift(content, svg_path, result)
- # 9. Check web-sourced image attribution. Templates don't carry
+ # 10. Check web-sourced image attribution. Templates don't carry
# image_sources.json; skip in template mode.
if not self.template_mode:
self._check_sourced_image_attribution(content, svg_path, result)
@@ -395,13 +429,16 @@ class SVGQualityChecker:
def _check_viewbox(self, content: str, result: Dict, expected_format: str = None):
"""Check viewBox attribute"""
- viewbox_match = re.search(r'viewBox\s*=\s*["\']([^"\']+)["\']', content)
+ try:
+ root = ET.fromstring(content)
+ except ET.ParseError:
+ return
- if not viewbox_match:
+ viewbox = root.get('viewBox')
+ if not viewbox:
result['errors'].append("Missing viewBox attribute")
return
- viewbox = viewbox_match.group(1)
result['info']['viewbox'] = viewbox
parts = re.split(r'[\s,]+', viewbox.strip())
@@ -410,15 +447,13 @@ class SVGQualityChecker:
f"viewBox must contain exactly four numeric values; got: {viewbox}"
)
return
-
try:
- values = [float(part) for part in parts]
+ values = tuple(float(part) for part in parts)
except ValueError:
result['errors'].append(
f"viewBox must contain exactly four numeric values; got: {viewbox}"
)
return
-
if values[2] <= 0 or values[3] <= 0:
result['errors'].append(
f"viewBox width/height must be positive; got: {viewbox}"
@@ -431,7 +466,8 @@ class SVGQualityChecker:
# Check if it matches expected format
if expected_format and expected_format in CANVAS_FORMATS:
expected_viewbox = CANVAS_FORMATS[expected_format]['viewbox']
- if viewbox != expected_viewbox:
+ expected_values = _parse_viewbox_values(expected_viewbox)
+ if expected_values and values != expected_values:
result['errors'].append(
f"viewBox mismatch: expected '{expected_viewbox}', got '{viewbox}'"
)
@@ -439,6 +475,13 @@ class SVGQualityChecker:
def _check_forbidden_elements(self, content: str, result: Dict):
"""Check forbidden elements (blocklist)"""
content_lower = content.lower()
+ try:
+ root = ET.fromstring(content)
+ elems = list(root.iter())
+ except ET.ParseError:
+ root = None
+ elems = []
+ local_names = {_local_name(elem).lower() for elem in elems}
# ============================================================
# Forbidden elements blocklist - PPT incompatible
@@ -448,37 +491,36 @@ class SVGQualityChecker:
# clipPath is allowed on <image> elements and on pptx_to_svg-generated
# nested crop <svg data-pptx-crop="1"> wrappers. Both map back to
# DrawingML picture geometry in the native converter.
- if '<clippath' in content_lower:
- # clip-path on non-image elements → error
- clip_on_non_image = re.search(
- r'<(?!image\b)(?!svg\b[^>]*\bdata-pptx-crop\s*=\s*["\']1["\'])\w+[^>]*\bclip-path\s*=',
- content,
- re.IGNORECASE,
- )
- if clip_on_non_image:
- result['errors'].append(
- "clip-path is only allowed on <image> elements or "
- "pptx_to_svg crop wrappers — for shapes, draw the target "
- "shape directly instead of clipping")
- # Check that every clip-path reference has a matching <clipPath> def
- clip_refs = re.findall(r'clip-path\s*=\s*["\']url\(#([^)]+)\)', content)
- for ref_id in clip_refs:
- if f'id="{ref_id}"' not in content and f"id='{ref_id}'" not in content:
+ if 'clippath' in local_names:
+ ids = {elem.get('id') for elem in elems if elem.get('id')}
+ for elem in elems:
+ clip_ref = elem.get('clip-path')
+ if not clip_ref:
+ continue
+ tag = _local_name(elem).lower()
+ is_crop_svg = tag == 'svg' and elem.get('data-pptx-crop') == '1'
+ if tag != 'image' and not is_crop_svg:
result['errors'].append(
- f"clip-path references #{ref_id} but no matching "
- f"<clipPath id=\"{ref_id}\"> definition found")
- if '<mask' in content_lower:
+ "clip-path is only allowed on <image> elements or "
+ "pptx_to_svg crop wrappers — for shapes, draw the target "
+ "shape directly instead of clipping")
+ match = re.search(r'url\(#([^)]+)\)', clip_ref)
+ if match and match.group(1) not in ids:
+ result['errors'].append(
+ f"clip-path references #{match.group(1)} but no matching "
+ f"<clipPath id=\"{match.group(1)}\"> definition found")
+ if 'mask' in local_names:
result['errors'].append("Detected forbidden <mask> element (PPT does not support SVG masks)")
# Style system
- if '<style' in content_lower:
+ if 'style' in local_names:
result['errors'].append("Detected forbidden <style> element (use inline attributes instead)")
if re.search(r'\bclass\s*=', content):
result['errors'].append("Detected forbidden class attribute (use inline styles instead)")
# id attribute: only report error when <style> also exists (id is harmful only with CSS selectors)
# id inside <defs> for linearGradient/filter etc. is required, Inkscape also auto-adds id to elements,
# standalone id attributes have no impact on PPT export
- if '<style' in content_lower and re.search(r'\bid\s*=', content):
+ if 'style' in local_names and re.search(r'\bid\s*=', content):
result['errors'].append(
"Detected id attribute used with <style> (CSS selectors forbidden, use inline styles instead)"
)
@@ -490,47 +532,51 @@ class SVGQualityChecker:
result['errors'].append("Detected forbidden @import (external CSS references forbidden)")
# Structure / nesting
- if '<foreignobject' in content_lower:
+ if 'foreignobject' in local_names:
result['errors'].append(
"Detected forbidden <foreignObject> element (use <tspan> for manual line breaks)")
- has_symbol = '<symbol' in content_lower
- has_use = re.search(r'<use\b', content_lower) is not None
+ has_symbol = 'symbol' in local_names
+ has_use = 'use' in local_names
if has_symbol and has_use:
result['errors'].append("Detected forbidden <symbol> + <use> complex usage (use basic shapes or simple <use> instead)")
# marker-start / marker-end are conditionally allowed (see shared-standards.md §1.1).
# The converter maps qualifying <marker> defs to native DrawingML <a:headEnd>/<a:tailEnd>.
# We only warn when a marker is used without an obvious <defs> definition in the same file.
if re.search(r'\bmarker-(?:start|end)\s*=\s*["\']url\(#([^)]+)\)', content_lower):
- if '<marker' not in content_lower:
+ if 'marker' not in local_names:
result['errors'].append(
"Detected marker-start/marker-end referencing a marker id, "
"but no <marker> element found in the file")
# Text / fonts
- if '<textpath' in content_lower:
+ if 'textpath' in local_names:
result['errors'].append("Detected forbidden <textPath> element (path text is incompatible with PPT)")
if '@font-face' in content_lower:
result['errors'].append("Detected forbidden @font-face (use system font stack)")
# Animation / interaction
- if re.search(r'<animate', content_lower):
+ if any(name.startswith('animate') for name in local_names):
result['errors'].append("Detected forbidden SMIL animation element <animate*> (SVG animations are not exported)")
- if re.search(r'<set\b', content_lower):
+ if 'set' in local_names:
result['errors'].append("Detected forbidden SMIL animation element <set> (SVG animations are not exported)")
- if '<script' in content_lower:
+ if 'script' in local_names:
result['errors'].append("Detected forbidden <script> element (scripts and event handlers forbidden)")
if re.search(r'\bon\w+\s*=', content): # onclick, onload etc.
result['errors'].append("Detected forbidden event attributes (e.g., onclick, onload)")
# Other discouraged elements
- if '<iframe' in content_lower:
+ if 'iframe' in local_names:
result['errors'].append("Detected <iframe> element (should not appear in SVG)")
- if re.search(r'rgba\s*\(', content_lower):
- result['errors'].append("Detected forbidden rgba() color (use fill-opacity/stroke-opacity instead)")
- if re.search(r'<g[^>]*\sopacity\s*=', content_lower):
+ for attr in ('fill', 'stroke', 'stop-color'):
+ if any('rgba' in value.lower() for value in self._svg_property_values(content, attr)):
+ result['errors'].append("Detected forbidden rgba() color (use fill-opacity/stroke-opacity instead)")
+ break
+ if any(_local_name(elem).lower() == 'g' and elem.get('opacity') for elem in elems):
result['errors'].append("Detected forbidden <g opacity> (set opacity on each child element individually)")
- if re.search(r'<image[^>]*\sopacity\s*=', content_lower):
+ if any(_local_name(elem).lower() == 'image' and elem.get('opacity') for elem in elems):
result['errors'].append("Detected forbidden <image opacity> (use overlay mask approach)")
+ if root is None and re.search(r'rgba\s*\(', content_lower):
+ result['errors'].append("Detected forbidden rgba() color (use fill-opacity/stroke-opacity instead)")
def _check_font_size_values(self, content: str, result: Dict):
"""Require font-size values to be unitless numeric SVG px values."""
@@ -694,41 +740,33 @@ class SVGQualityChecker:
def _check_image_references(self, content: str, svg_path: Path, result: Dict):
"""Check image file existence and resolution vs display size."""
- # Find all <image ...> elements (capture the full tag)
- img_tag_pattern = re.compile(r'<image\b([^>]*)/?>', re.IGNORECASE)
-
+ try:
+ root = ET.fromstring(content)
+ except ET.ParseError:
+ return
svg_dir = svg_path.parent
checked = set()
- for tag_match in img_tag_pattern.finditer(content):
- attrs = tag_match.group(1)
-
- # Extract href (prefer href over xlink:href)
- href_match = (
- re.search(r'\bhref="(?!data:)([^"]+)"', attrs) or
- re.search(r'\bxlink:href="(?!data:)([^"]+)"', attrs)
- )
- if not href_match:
+ for image in root.iter():
+ if _local_name(image).lower() != 'image':
continue
- href = href_match.group(1)
+ href = image.get('href') or image.get(f'{{{XLINK_NS}}}href')
+ if not href or href.startswith('data:'):
+ continue
if href in checked:
continue
checked.add(href)
- # Resolve path relative to SVG file directory
- img_path = (svg_dir / href).resolve()
-
+ img_path = self._resolve_image_reference(svg_dir, href)
if not img_path.exists():
result['errors'].append(
f"Image file not found: {href} (resolved to {img_path})")
continue
# Check resolution vs display size
- w_match = re.search(r'\bwidth="([^"]+)"', attrs)
- h_match = re.search(r'\bheight="([^"]+)"', attrs)
- display_w_str = w_match.group(1) if w_match else None
- display_h_str = h_match.group(1) if h_match else None
+ display_w_str = image.get('width')
+ display_h_str = image.get('height')
if not display_w_str or not display_h_str:
continue
@@ -757,6 +795,77 @@ class SVGQualityChecker:
except Exception:
pass # Image unreadable, skip resolution check
+ @staticmethod
+ def _resolve_image_reference(svg_dir: Path, href: str) -> Path:
+ """Resolve an external image reference using the exporter search order."""
+ parsed = urlsplit(href)
+ if parsed.scheme and parsed.scheme not in ('file',):
+ return (svg_dir / href).resolve()
+ decoded = unquote(
+ parsed.path if parsed.scheme else href.split('?', 1)[0].split('#', 1)[0]
+ )
+ for candidate in (
+ svg_dir / decoded,
+ svg_dir.parent / decoded,
+ svg_dir.parent / 'images' / decoded,
+ svg_dir.parent / 'templates' / decoded,
+ ):
+ if candidate.exists():
+ return candidate.resolve()
+ return (svg_dir / decoded).resolve()
+
+ def _check_icon_placeholders(self, content: str, svg_path: Path, result: Dict) -> None:
+ """Check that <use data-icon="..."> placeholders resolve."""
+ try:
+ root = ET.fromstring(content)
+ except ET.ParseError:
+ return
+
+ placeholders = [
+ elem for elem in root.iter()
+ if _local_name(elem).lower() == 'use' and elem.get('data-icon') is not None
+ ]
+ if not placeholders:
+ return
+
+ if _resolve_icon_path is None:
+ result['warnings'].append(
+ "Detected data-icon placeholders, but icon resolver could not be imported; "
+ "post-processing/export will still validate them."
+ )
+ return
+
+ icons_dir, fallback_dir = self._icon_search_dirs(svg_path)
+ seen = set()
+ for elem in placeholders:
+ icon_name = (elem.get('data-icon') or '').strip()
+ if not icon_name:
+ result['errors'].append("Icon placeholder has empty data-icon value")
+ continue
+ if icon_name in seen:
+ continue
+ seen.add(icon_name)
+
+ icon_path, _ = _resolve_icon_path(icon_name, icons_dir, fallback_dir)
+ if not icon_path.exists():
+ fallback_msg = f", then {fallback_dir}" if fallback_dir else ""
+ result['errors'].append(
+ f"Icon not found: {icon_name} (searched {icons_dir}"
+ f"{fallback_msg})"
+ )
+
+ @staticmethod
+ def _icon_search_dirs(svg_path: Path) -> Tuple[Path, Path | None]:
+ """Return project-first icon dirs matching finalize_svg.py."""
+ project_path = svg_path.parent.parent if svg_path.parent.name in {
+ 'svg_output', 'svg_final', 'svg-flat', 'svg_flat',
+ } else svg_path.parent
+ global_icons_dir = Path(__file__).resolve().parent.parent / 'templates' / 'icons'
+ project_icons_dir = project_path / 'icons'
+ if project_icons_dir.is_dir():
+ return project_icons_dir, global_icons_dir
+ return global_icons_dir, None
+
def _check_animation_group_ids(self, content: str, result: Dict):
"""Warn when visible top-level groups cannot be customized."""
try:
@@ -1589,21 +1698,18 @@ class SVGQualityChecker:
@staticmethod
def _parse_svg_viewbox(content: str) -> Tuple[float, float] | None:
- """Return viewBox width/height from SVG content."""
- match = re.search(r'viewBox\s*=\s*["\']([^"\']+)["\']', content)
- if not match:
- return None
- parts = re.split(r'[\s,]+', match.group(1).strip())
- if len(parts) != 4:
- return None
+ """Return root viewBox width/height from SVG content."""
try:
- width = float(parts[2])
- height = float(parts[3])
- except ValueError:
+ root = ET.fromstring(content)
+ except ET.ParseError:
+ return None
+ viewbox = root.get('viewBox')
+ if not viewbox:
return None
- if width <= 0 or height <= 0:
+ values = _parse_viewbox_values(viewbox)
+ if values is None:
return None
- return width, height
+ return values[2], values[3]
@classmethod
def _has_off_canvas_reference(cls, refs: List[Tuple[Path, str]]) -> bool:
@@ -1959,7 +2065,7 @@ class SVGQualityChecker:
if self.summary['errors'] > 0 or self.summary['warnings'] > 0:
print(f"\n[TIP] Common fixes:")
print(f" 1. XML well-formedness: write typography as raw Unicode (—, ©, →, NBSP); escape XML reserved chars as &amp; &lt; &gt; &quot; &apos; — never use HTML named entities like &nbsp; &mdash; &copy;")
- print(f" 2. viewBox issues: Ensure consistency with canvas format (see references/canvas-formats.md)")
+ print(f" 2. viewBox issues: root viewBox is the canvas authority (see references/canvas-formats.md)")
print(f" 3. foreignObject: Use <text> + <tspan> for manual line breaks")
print(f" 4. Font issues: use PPT-safe exported typefaces (e.g. Microsoft YaHei / Arial / Consolas)")
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 be91352c..1c083275 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml_converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml_converter.py
@@ -511,10 +511,16 @@ def convert_svg_to_slide_shapes(
# both ignore data-icon, so without expansion icons would silently drop.
# The on-disk finalize_svg pipeline does the same expansion for svg_final/;
# running this here makes the two pipelines behaviourally aligned.
- icons_dir = Path(__file__).resolve().parent.parent.parent / 'templates' / 'icons'
+ global_icons_dir = Path(__file__).resolve().parent.parent.parent / 'templates' / 'icons'
+ project_path = svg_path.parent.parent if svg_path.parent.name in {
+ 'svg_output', 'svg_final', 'svg-flat', 'svg_flat',
+ } else svg_path.parent
+ project_icons_dir = project_path / 'icons'
+ icons_dir = project_icons_dir if project_icons_dir.is_dir() else global_icons_dir
+ icons_fallback_dir = global_icons_dir if icons_dir != global_icons_dir else None
if icons_dir.exists():
from .use_expander import expand_use_data_icons
- expanded = expand_use_data_icons(root, icons_dir)
+ expanded = expand_use_data_icons(root, icons_dir, icons_fallback_dir)
if expanded:
trace_steps.append({'action': 'expand-use-data-icons', 'count': expanded})
if verbose and expanded:
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_dimensions.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_dimensions.py
index da8ee79e..cb82e040 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_dimensions.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_dimensions.py
@@ -93,6 +93,28 @@ def get_pixel_dimensions(
return 1280, 720
+def _root_viewbox(svg_path: Path) -> str | None:
+ """Return the root SVG viewBox, ignoring nested sprite/crop viewBoxes."""
+ try:
+ root = ET.parse(svg_path).getroot()
+ except (ET.ParseError, OSError):
+ return None
+ return root.get('viewBox')
+
+
+def _parse_viewbox_values(viewbox: str) -> tuple[float, float, float, float] | None:
+ parts = re.split(r'[\s,]+', viewbox.strip())
+ if len(parts) != 4:
+ return None
+ try:
+ values = tuple(float(part) for part in parts)
+ except ValueError:
+ return None
+ if values[2] <= 0 or values[3] <= 0:
+ return None
+ return values
+
+
def get_viewbox_dimensions(svg_path: Path) -> tuple[int, int] | None:
"""Extract pixel dimensions from SVG viewBox.
@@ -102,26 +124,13 @@ def get_viewbox_dimensions(svg_path: Path) -> tuple[int, int] | None:
Returns:
(width, height) as integers, or None if not found.
"""
- try:
- with open(svg_path, 'r', encoding='utf-8') as f:
- content = f.read(2000)
-
- match = re.search(r'viewBox\s*=\s*["\']([^"\']+)["\']', content)
- if not match:
- return None
-
- parts = re.split(r'[\s,]+', match.group(1).strip())
- if len(parts) != 4:
- return None
-
- width = float(parts[2])
- height = float(parts[3])
- if width <= 0 or height <= 0:
- return None
-
- return int(round(width)), int(round(height))
- except Exception:
+ viewbox = _root_viewbox(svg_path)
+ if not viewbox:
+ return None
+ values = _parse_viewbox_values(viewbox)
+ if values is None:
return None
+ return int(round(values[2])), int(round(values[3]))
def detect_format_from_svg(svg_path: Path) -> str | None:
@@ -133,16 +142,14 @@ def detect_format_from_svg(svg_path: Path) -> str | None:
Returns:
Canvas format key (e.g. 'ppt169'), or None if not detected.
"""
- try:
- with open(svg_path, 'r', encoding='utf-8') as f:
- content = f.read(2000)
-
- match = re.search(r'viewBox\s*=\s*["\']([^"\']+)["\']', content)
- if match:
- viewbox = match.group(1)
- for fmt_key, fmt_info in CANVAS_FORMATS.items():
- if fmt_info['viewbox'] == viewbox:
- return fmt_key
- except Exception:
- pass
+ viewbox = _root_viewbox(svg_path)
+ if not viewbox:
+ return None
+ values = _parse_viewbox_values(viewbox)
+ if values is None:
+ return None
+ for fmt_key, fmt_info in CANVAS_FORMATS.items():
+ expected = _parse_viewbox_values(fmt_info['viewbox'])
+ if expected and values == expected:
+ return fmt_key
return None
diff --git a/skills/ppt-master/scripts/svg_to_pptx/use_expander.py b/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
index 72289b0d..16089bb7 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
@@ -8,7 +8,7 @@ expansion in memory so ``svg_to_pptx`` can consume ``svg_output/`` directly
without first running the on-disk finalize step.
Public API:
- expand_use_data_icons(root, icons_dir) -> int
+ expand_use_data_icons(root, icons_dir, fallback_dir=None) -> int
Walk the SVG element tree, replace every ``<use data-icon="...">``
with its expanded ``<g>`` group of primitive shapes, and return
the number of replacements made.
@@ -40,6 +40,7 @@ def _import_embed_icons():
def _build_replacement_g(
use_elem: ET.Element,
icons_dir: Path,
+ fallback_dir: Path | None,
embed_icons_mod,
) -> ET.Element | None:
"""Resolve a single ``<use data-icon="...">`` into an expanded ``<g>``.
@@ -55,7 +56,7 @@ def _build_replacement_g(
return None
icon_path, _base_size = embed_icons_mod.resolve_icon_path(
- attrs['icon'], icons_dir,
+ attrs['icon'], icons_dir, fallback_dir,
)
if not icon_path.exists():
return None
@@ -84,12 +85,17 @@ def _build_replacement_g(
return None
-def expand_use_data_icons(root: ET.Element, icons_dir: Path) -> int:
+def expand_use_data_icons(
+ root: ET.Element,
+ icons_dir: Path,
+ fallback_dir: Path | None = None,
+) -> int:
"""Replace every ``<use data-icon="...">`` in *root* with its expansion.
Walks the tree, finds use elements that carry a ``data-icon`` attribute,
- builds a new ``<g>`` subtree from the corresponding icon library, and
- swaps it into the parent element at the same position.
+ builds a new ``<g>`` subtree from the project icon library (falling back to
+ the global library when supplied), and swaps it into the parent element at
+ the same position.
Returns the number of placeholders successfully expanded. Unresolvable
placeholders are left in place so callers can decide whether to warn.
@@ -116,7 +122,7 @@ def expand_use_data_icons(root: ET.Element, icons_dir: Path) -> int:
parent = parent_of.get(use_elem)
if parent is None:
continue
- replacement = _build_replacement_g(use_elem, icons_dir, embed_icons_mod)
+ replacement = _build_replacement_g(use_elem, icons_dir, fallback_dir, embed_icons_mod)
if replacement is None:
continue
idx = list(parent).index(use_elem)