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

refactor(scripts): centralize SVG resource path resolution

hugohe36ac62b5c2413
diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.py
index 0846e6aa..a904b4ac 100644
--- a/skills/ppt-master/scripts/finalize_svg.py
+++ b/skills/ppt-master/scripts/finalize_svg.py
@@ -45,6 +45,7 @@ configure_utf8_stdio()
# Import finalize helpers from the internal package.
sys.path.insert(0, str(Path(__file__).parent))
+from resource_paths import icon_search_dirs_for_project # noqa: E402
from svg_finalize.align_embed_images import (
align_and_embed_images_in_svg,
count_office_vector_refs_in_svg,
@@ -136,12 +137,7 @@ def finalize_project(
"""
svg_output = project_dir / 'svg_output'
svg_final = project_dir / 'svg_final'
- # Project-first: embed from the deck's own icons/ (synced library icons +
- # any custom icons), falling back to the global library per-icon.
- global_icons_dir = Path(__file__).parent.parent / 'templates' / 'icons'
- project_icons_dir = project_dir / '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
+ icons_dir, icons_fallback_dir = icon_search_dirs_for_project(project_dir)
# Check if svg_output exists
if not svg_output.exists():
diff --git a/skills/ppt-master/scripts/resource_paths.py b/skills/ppt-master/scripts/resource_paths.py
new file mode 100644
index 00000000..3f671c0e
--- /dev/null
+++ b/skills/ppt-master/scripts/resource_paths.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Shared SVG Resource Path Helpers
+
+Centralizes project-relative SVG resource lookup used by the checker,
+finalizer, and SVG-to-PPTX exporter.
+
+Usage:
+ Imported by scripts; not intended as a standalone CLI.
+
+Examples:
+ from resource_paths import resolve_external_image_reference
+
+Dependencies:
+ None
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from urllib.parse import unquote, urlsplit
+
+
+SVG_WORK_DIR_NAMES = frozenset({'svg_output', 'svg_final', 'svg-flat', 'svg_flat'})
+
+
+def project_root_for_svg_path(svg_path: Path) -> Path:
+ """Infer the project root from an SVG file path or SVG directory path."""
+ path = Path(svg_path)
+ base = path if path.is_dir() else path.parent
+ if base.name in SVG_WORK_DIR_NAMES:
+ return base.parent
+ return base
+
+
+def global_icons_dir() -> Path:
+ """Return the skill-level icon library directory."""
+ return Path(__file__).resolve().parent.parent / 'templates' / 'icons'
+
+
+def icon_search_dirs_for_project(project_path: Path) -> tuple[Path, Path | None]:
+ """Return project-first icon dirs plus the global fallback when needed."""
+ global_dir = global_icons_dir()
+ project_icons_dir = Path(project_path) / 'icons'
+ if project_icons_dir.is_dir():
+ return project_icons_dir, global_dir
+ return global_dir, None
+
+
+def icon_search_dirs_for_svg(svg_path: Path) -> tuple[Path, Path | None]:
+ """Return icon dirs for an SVG file path or SVG directory path."""
+ return icon_search_dirs_for_project(project_root_for_svg_path(svg_path))
+
+
+def external_image_reference_candidates(svg_dir: Path, href: str) -> list[Path]:
+ """Return candidate paths for a non-data-URI SVG image href."""
+ parsed = urlsplit(href)
+ if parsed.scheme and parsed.scheme not in {'file'}:
+ return []
+ decoded = unquote(
+ parsed.path
+ if parsed.scheme
+ else href.split('?', 1)[0].split('#', 1)[0]
+ )
+ svg_dir = Path(svg_dir)
+ project_root = project_root_for_svg_path(svg_dir)
+ return [
+ svg_dir / decoded,
+ project_root / decoded,
+ project_root / 'images' / decoded,
+ project_root / 'templates' / decoded,
+ ]
+
+
+def resolve_external_image_reference(svg_dir: Path, href: str) -> Path | None:
+ """Resolve an SVG image href to an existing file, or return None."""
+ for candidate in external_image_reference_candidates(svg_dir, href):
+ if candidate.exists():
+ return candidate.resolve()
+ return None
+
+
+def unresolved_external_image_reference_path(svg_dir: Path, href: str) -> Path:
+ """Return the first candidate path for diagnostics when resolution fails."""
+ candidates = external_image_reference_candidates(svg_dir, href)
+ if candidates:
+ return candidates[0].resolve()
+ return (Path(svg_dir) / href).resolve()
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 3a277ad3..3cabe8e8 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -17,7 +17,6 @@ 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
@@ -81,6 +80,21 @@ try:
except ImportError:
_resolve_icon_path = None
+try:
+ from resource_paths import (
+ SVG_WORK_DIR_NAMES as _SVG_WORK_DIR_NAMES,
+ icon_search_dirs_for_svg as _icon_search_dirs_for_svg,
+ project_root_for_svg_path as _project_root_for_svg_path,
+ resolve_external_image_reference as _resolve_external_image_reference,
+ unresolved_external_image_reference_path as _unresolved_external_image_reference_path,
+ )
+except ImportError:
+ _SVG_WORK_DIR_NAMES = frozenset()
+ _icon_search_dirs_for_svg = None
+ _project_root_for_svg_path = None
+ _resolve_external_image_reference = None
+ _unresolved_external_image_reference_path = None
+
HEX_VALUE_RE = re.compile(r"#[0-9A-Fa-f]{3,8}")
SVG_NS = "http://www.w3.org/2000/svg"
@@ -771,14 +785,21 @@ class SVGQualityChecker:
href = image.get('href') or image.get(f'{{{XLINK_NS}}}href')
if not href or href.startswith('data:'):
continue
+ if _resolve_external_image_reference is None or _unresolved_external_image_reference_path is None:
+ result['warnings'].append(
+ "Detected image references, but shared image resolver could not be imported; "
+ "export will still validate them."
+ )
+ return
if href in checked:
continue
checked.add(href)
- img_path = self._resolve_image_reference(svg_dir, href)
- if not img_path.exists():
+ img_path = _resolve_external_image_reference(svg_dir, href)
+ if img_path is None:
+ resolved_path = _unresolved_external_image_reference_path(svg_dir, href)
result['errors'].append(
- f"Image file not found: {href} (resolved to {img_path})")
+ f"Image file not found: {href} (resolved to {resolved_path})")
continue
# Check resolution vs display size
@@ -812,25 +833,6 @@ 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:
@@ -851,8 +853,14 @@ class SVGQualityChecker:
"post-processing/export will still validate them."
)
return
+ if _icon_search_dirs_for_svg is None:
+ result['warnings'].append(
+ "Detected data-icon placeholders, but shared icon search helper could not be imported; "
+ "post-processing/export will still validate them."
+ )
+ return
- icons_dir, fallback_dir = self._icon_search_dirs(svg_path)
+ icons_dir, fallback_dir = _icon_search_dirs_for_svg(svg_path)
seen = set()
for elem in placeholders:
icon_name = (elem.get('data-icon') or '').strip()
@@ -871,18 +879,6 @@ class SVGQualityChecker:
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:
@@ -1500,8 +1496,8 @@ class SVGQualityChecker:
@staticmethod
def _resolve_project_path(dir_path: Path) -> Path:
"""Resolve a checker target directory to its project root."""
- if dir_path.name in {'svg_output', 'svg_final'}:
- return dir_path.parent
+ if _project_root_for_svg_path is not None and dir_path.name in _SVG_WORK_DIR_NAMES:
+ return _project_root_for_svg_path(dir_path)
if (dir_path / 'svg_output').exists() or (dir_path / 'design_spec.md').exists():
return dir_path
return dir_path.parent
@@ -1774,7 +1770,7 @@ class SVGQualityChecker:
"""Project-level animations.json reference checks."""
if _load_animation_config is None or _validate_animation_config is None:
return
- project_path = dir_path if (dir_path / 'svg_output').exists() else dir_path.parent
+ project_path = self._resolve_project_path(dir_path)
try:
config = _load_animation_config(project_path)
except Exception as exc:
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 1c083275..045cde9f 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml_converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml_converter.py
@@ -8,6 +8,8 @@ from pathlib import Path
from typing import Any
from xml.etree import ElementTree as ET
+from resource_paths import icon_search_dirs_for_svg
+
from .drawingml_context import ConvertContext, ShapeResult
from .drawingml_utils import (
SVG_NS, EMU_PER_PX,
@@ -511,13 +513,7 @@ 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.
- 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
+ icons_dir, icons_fallback_dir = icon_search_dirs_for_svg(svg_path)
if icons_dir.exists():
from .use_expander import expand_use_data_icons
expanded = expand_use_data_icons(root, icons_dir, icons_fallback_dir)
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 147db02a..ef9013d7 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml_elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml_elements.py
@@ -8,9 +8,11 @@ import re
import base64
from pathlib import Path
from typing import Any
-from urllib.parse import unquote, unquote_to_bytes, urlsplit
+from urllib.parse import unquote_to_bytes
from xml.etree import ElementTree as ET
+from resource_paths import resolve_external_image_reference
+
from .drawingml_context import ConvertContext, ShapeResult
from .drawingml_utils import (
SVG_NS, XLINK_NS, ANGLE_UNIT, FONT_PX_TO_HUNDREDTHS_PT, DASH_PRESETS,
@@ -43,19 +45,9 @@ def _resolve_external_image(svg_dir: Path, href: str) -> Path:
(legacy flat-copied template assets). Raises ``FileNotFoundError`` if none
of these exist.
"""
- parsed = urlsplit(href)
- if parsed.scheme and parsed.scheme not in ('file',):
- raise FileNotFoundError(f'External image not found: {href}')
- 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
+ candidate = resolve_external_image_reference(svg_dir, href)
+ if candidate is not None:
+ return candidate
raise FileNotFoundError(f'External image not found: {href}')