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(tooling): preserve PPTX state across import edge cases

hugohe33deb8e866b24
diff --git a/skills/ppt-master/scripts/native_enhance_pptx_core.py b/skills/ppt-master/scripts/native_enhance_pptx_core.py
index 19c88706..c23d5d39 100644
--- a/skills/ppt-master/scripts/native_enhance_pptx_core.py
+++ b/skills/ppt-master/scripts/native_enhance_pptx_core.py
@@ -27,6 +27,7 @@ from __future__ import annotations
import argparse
import json
+import posixpath
import re
import shutil
import subprocess
@@ -96,6 +97,9 @@ CONTENT_TYPE_NOTES_MASTER = (
"application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"
)
CONTENT_TYPE_THEME = "application/vnd.openxmlformats-officedocument.theme+xml"
+_NOTES_SLIDE_PART_RE = re.compile(
+ r"^ppt/notesSlides/notesSlide([1-9]\d*)\.xml$"
+)
@dataclass(frozen=True)
@@ -171,18 +175,6 @@ def _ensure_rels_file(path: Path) -> None:
)
-def _remove_relationships_by_type(rels_path: Path, rel_type: str) -> None:
- if not rels_path.exists():
- return
- content = rels_path.read_text(encoding="utf-8")
- content = re.sub(
- rf'\s*<Relationship\b[^>]*\bType="{re.escape(rel_type)}"[^>]*/>',
- "",
- content,
- )
- rels_path.write_text(content, encoding="utf-8")
-
-
def _target_to_part(target: str) -> str:
target = target.lstrip("/")
if target.startswith("ppt/"):
@@ -197,6 +189,118 @@ def _slide_number_from_part(part_name: str) -> int:
return int(match.group(1))
+def _resolve_relationship_part(source_part: str, target: str) -> str:
+ """Resolve an internal relationship target to a package part name."""
+ target_path = target.split("#", 1)[0]
+ if target_path.startswith("/"):
+ return posixpath.normpath(target_path.lstrip("/"))
+ return posixpath.normpath(
+ posixpath.join(posixpath.dirname(source_part), target_path)
+ )
+
+
+def _notes_slide_index(part_name: str) -> int | None:
+ match = _NOTES_SLIDE_PART_RE.fullmatch(part_name)
+ return int(match.group(1)) if match else None
+
+
+def _is_notes_slide_part(part_name: str) -> bool:
+ """Return whether a relationship target stays in the notesSlides folder."""
+ return (
+ posixpath.dirname(part_name) == "ppt/notesSlides"
+ and posixpath.basename(part_name).endswith(".xml")
+ and posixpath.basename(part_name) != ".xml"
+ )
+
+
+def _notes_slide_part_for_slide(
+ extract_dir: Path,
+ slide: SlidePart,
+) -> str | None:
+ """Return the notes part currently related to a slide, if present."""
+ slide_rels = _relationship_file_for_part(extract_dir, slide.part_name)
+ if not slide_rels.exists():
+ return None
+
+ related_parts: list[str] = []
+ for rel in ET.parse(slide_rels).getroot():
+ if rel.attrib.get("Type") != NOTES_REL_TYPE:
+ continue
+ if rel.attrib.get("TargetMode", "").lower() == "external":
+ raise RuntimeError(
+ f"Slide {slide.index} has an external notesSlide relationship"
+ )
+ target = rel.attrib.get("Target")
+ if not target:
+ raise RuntimeError(
+ f"Slide {slide.index} notesSlide relationship has no Target"
+ )
+ part_name = _resolve_relationship_part(slide.part_name, target)
+ if not _is_notes_slide_part(part_name):
+ raise RuntimeError(
+ f"Slide {slide.index} has an unsupported notesSlide target: {target}"
+ )
+ related_parts.append(part_name)
+
+ if len(related_parts) > 1:
+ raise RuntimeError(
+ f"Slide {slide.index} has multiple notesSlide relationships"
+ )
+ return related_parts[0] if related_parts else None
+
+
+def _used_notes_slide_indices(extract_dir: Path) -> set[int]:
+ """Collect every notesSlide number already reserved in the package."""
+ used: set[int] = set()
+ notes_dir = extract_dir / "ppt" / "notesSlides"
+ for path in notes_dir.glob("notesSlide*.xml"):
+ index = _notes_slide_index(f"ppt/notesSlides/{path.name}")
+ if index is not None:
+ used.add(index)
+ for path in (notes_dir / "_rels").glob("notesSlide*.xml.rels"):
+ index = _notes_slide_index(
+ f"ppt/notesSlides/{path.name.removesuffix('.rels')}"
+ )
+ if index is not None:
+ used.add(index)
+
+ content_types_path = extract_dir / "[Content_Types].xml"
+ if content_types_path.exists():
+ content_types = content_types_path.read_text(encoding="utf-8")
+ for match in re.finditer(
+ r'PartName="/(ppt/notesSlides/notesSlide[1-9]\d*\.xml)"',
+ content_types,
+ ):
+ index = _notes_slide_index(match.group(1))
+ if index is not None:
+ used.add(index)
+
+ slides_rels_dir = extract_dir / "ppt" / "slides" / "_rels"
+ for rels_path in slides_rels_dir.glob("slide*.xml.rels"):
+ source_part = f"ppt/slides/{rels_path.name.removesuffix('.rels')}"
+ for rel in ET.parse(rels_path).getroot():
+ if (
+ rel.attrib.get("Type") != NOTES_REL_TYPE
+ or rel.attrib.get("TargetMode", "").lower() == "external"
+ ):
+ continue
+ target = rel.attrib.get("Target")
+ if not target:
+ continue
+ index = _notes_slide_index(
+ _resolve_relationship_part(source_part, target)
+ )
+ if index is not None:
+ used.add(index)
+ return used
+
+
+def _allocate_notes_slide_part(extract_dir: Path) -> str:
+ used = _used_notes_slide_indices(extract_dir)
+ index = max(used, default=0) + 1
+ return f"ppt/notesSlides/notesSlide{index}.xml"
+
+
def read_slide_parts(extract_dir: Path) -> list[SlidePart]:
presentation_path = extract_dir / "ppt" / "presentation.xml"
rels_path = extract_dir / "ppt" / "_rels" / "presentation.xml.rels"
@@ -288,52 +392,57 @@ def _add_override(content_types: str, part_name: str, content_type: str) -> str:
return content_types.replace("</Types>", override + "\n</Types>")
-def _add_notes_content_types(content_types: str, note_indices: set[int]) -> str:
+def _add_notes_content_types(content_types: str, note_parts: set[str]) -> str:
content_types = _add_override(content_types, "ppt/theme/theme2.xml", CONTENT_TYPE_THEME)
content_types = _add_override(
content_types,
"ppt/notesMasters/notesMaster1.xml",
CONTENT_TYPE_NOTES_MASTER,
)
- for index in sorted(note_indices):
+ for part_name in sorted(note_parts):
content_types = _add_override(
content_types,
- f"ppt/notesSlides/notesSlide{index}.xml",
+ part_name,
CONTENT_TYPE_NOTES_SLIDE,
)
return content_types
-def _apply_notes(extract_dir: Path, slide: SlidePart, note_md: Path) -> None:
+def _apply_notes(
+ extract_dir: Path,
+ slide: SlidePart,
+ note_md: Path,
+) -> str | None:
notes_text = markdown_to_plain_text(note_md.read_text(encoding="utf-8"))
if not notes_text:
- return
+ return None
_ensure_notes_master(extract_dir)
- notes_dir = extract_dir / "ppt" / "notesSlides"
- notes_dir.mkdir(parents=True, exist_ok=True)
- notes_xml_path = notes_dir / f"notesSlide{slide.index}.xml"
+ slide_rels = _relationship_file_for_part(extract_dir, slide.part_name)
+ _ensure_rels_file(slide_rels)
+ notes_part = _notes_slide_part_for_slide(extract_dir, slide)
+ if notes_part is None:
+ notes_part = _allocate_notes_slide_part(extract_dir)
+ target = posixpath.relpath(
+ notes_part,
+ start=posixpath.dirname(slide.part_name),
+ )
+ _append_relationship(slide_rels, NOTES_REL_TYPE, target)
+
+ notes_xml_path = extract_dir / notes_part
+ notes_xml_path.parent.mkdir(parents=True, exist_ok=True)
notes_xml_path.write_text(
create_notes_slide_xml(slide.slide_number, notes_text),
encoding="utf-8",
)
- notes_rels_dir = notes_dir / "_rels"
- notes_rels_dir.mkdir(parents=True, exist_ok=True)
- notes_rels_path = notes_rels_dir / f"notesSlide{slide.index}.xml.rels"
+ notes_rels_path = _relationship_file_for_part(extract_dir, notes_part)
+ notes_rels_path.parent.mkdir(parents=True, exist_ok=True)
notes_rels_path.write_text(
create_notes_slide_rels_xml(slide.slide_number),
encoding="utf-8",
)
-
- slide_rels = _relationship_file_for_part(extract_dir, slide.part_name)
- _ensure_rels_file(slide_rels)
- _remove_relationships_by_type(slide_rels, NOTES_REL_TYPE)
- _append_relationship(
- slide_rels,
- NOTES_REL_TYPE,
- f"../notesSlides/notesSlide{slide.index}.xml",
- )
+ return notes_part
def _apply_audio(
@@ -401,11 +510,15 @@ def _apply_audio(
return timings_enabled and wrote_advance
-def _update_content_types(extract_dir: Path, note_indices: set[int], audio_exts: set[str]) -> None:
+def _update_content_types(
+ extract_dir: Path,
+ note_parts: set[str],
+ audio_exts: set[str],
+) -> None:
content_types_path = extract_dir / "[Content_Types].xml"
content_types = content_types_path.read_text(encoding="utf-8")
- if note_indices:
- content_types = _add_notes_content_types(content_types, note_indices)
+ if note_parts:
+ content_types = _add_notes_content_types(content_types, note_parts)
for ext in sorted(audio_exts):
content_type = AUDIO_CONTENT_TYPES.get(ext)
if content_type:
@@ -822,7 +935,7 @@ def apply_project(args: argparse.Namespace) -> int:
_extract_pptx(source_pptx, extract_dir)
slides = read_slide_parts(extract_dir)
- note_indices: set[int] = set()
+ note_parts: set[str] = set()
audio_exts: set[str] = set()
audio_count = 0
transition_only_count = 0
@@ -830,8 +943,9 @@ def apply_project(args: argparse.Namespace) -> int:
for slide in slides:
note = _note_path(notes_dir, slide.index)
if "notes" in modules and note:
- _apply_notes(extract_dir, slide, note)
- note_indices.add(slide.index)
+ notes_part = _apply_notes(extract_dir, slide, note)
+ if notes_part is not None:
+ note_parts.add(notes_part)
audio = _audio_path(audio_dir, slide.index)
if "audio" in modules and audio:
@@ -875,7 +989,7 @@ def apply_project(args: argparse.Namespace) -> int:
)
transition_only_count += 1
- _update_content_types(extract_dir, note_indices, audio_exts)
+ _update_content_types(extract_dir, note_parts, audio_exts)
if wrote_auto_advance:
set_directory_use_timings(extract_dir)
output_path.parent.mkdir(parents=True, exist_ok=True)
@@ -906,7 +1020,7 @@ def apply_project(args: argparse.Namespace) -> int:
candidate_path.replace(output_path)
print(f"Output: {output_path}", file=sys.stderr)
- print(f"Notes applied: {len(note_indices)}", file=sys.stderr)
+ print(f"Notes applied: {len(note_parts)}", file=sys.stderr)
print(f"Audio embedded: {audio_count}", file=sys.stderr)
if transition_only_count:
print(f"Transition-only slides: {transition_only_count}", file=sys.stderr)
diff --git a/skills/ppt-master/scripts/pptx_template_import.py b/skills/ppt-master/scripts/pptx_template_import.py
index df359572..bd0bc4e7 100644
--- a/skills/ppt-master/scripts/pptx_template_import.py
+++ b/skills/ppt-master/scripts/pptx_template_import.py
@@ -23,16 +23,25 @@ from __future__ import annotations
import argparse
import json
+import shutil
+import tempfile
from pathlib import Path
from xml.etree import ElementTree as ET
from zipfile import BadZipFile
from console_encoding import configure_utf8_stdio
from template_import.manifest import build_manifest
-from template_import.native_structure import write_native_structure_bundle
+from template_import.native_structure import (
+ CONTRACT_NAME,
+ SOURCE_TEMPLATE_NAME,
+ write_native_structure_bundle,
+)
configure_utf8_stdio()
+_MANIFEST_NAME = "manifest.json"
+_CONVERSION_REPORT_NAME = "conversion-report.json"
+
def parse_args() -> argparse.Namespace:
"""Build the CLI argument parser for the import entry point."""
@@ -84,6 +93,37 @@ def parse_args() -> argparse.Namespace:
return parser.parse_args()
+def _managed_asset_paths(output_dir: Path) -> set[Path]:
+ """Read the previous manifest's exact exported-asset roster."""
+ manifest_path = output_dir / _MANIFEST_NAME
+ try:
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError):
+ return set()
+ if not isinstance(manifest, dict):
+ return set()
+ assets = manifest.get("assets")
+ if not isinstance(assets, dict):
+ return set()
+ export_dir = assets.get("exportDir")
+ asset_names = assets.get("allAssets")
+ if export_dir != "assets" or not isinstance(asset_names, list):
+ return set()
+ if any(
+ not isinstance(name, str)
+ or not name
+ or name in {".", ".."}
+ or "/" in name
+ or "\\" in name
+ for name in asset_names
+ ):
+ return set()
+ return {
+ Path("assets") / name
+ for name in asset_names
+ }
+
+
def main() -> int:
"""CLI entry point: write the PPTX reference workspace to disk."""
args = parse_args()
@@ -100,100 +140,138 @@ def main() -> int:
if args.output
else pptx_path.with_name(f"{pptx_path.stem}_template_import")
)
- output_dir.mkdir(parents=True, exist_ok=True)
if args.skip_manifest and args.manifest_only:
print("Error: --skip-manifest and --manifest-only cannot be used together")
return 1
- manifest = None
- native_structure = None
- manifest_path = output_dir / "manifest.json"
- if not args.skip_manifest:
- try:
- manifest = build_manifest(
- pptx_path,
- output_dir,
- include_flat_svg=(
- not args.manifest_only and args.inheritance_mode == "both"
+ previous_assets = _managed_asset_paths(output_dir)
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
+ staging_root = Path(tempfile.mkdtemp(
+ prefix=f".{output_dir.name}.import-",
+ dir=output_dir.parent,
+ ))
+ staged_dir = staging_root / "generated"
+ staged_dir.mkdir()
+
+ try:
+ manifest = None
+ native_structure = None
+ manifest_path = staged_dir / _MANIFEST_NAME
+ if not args.skip_manifest:
+ try:
+ manifest = build_manifest(
+ pptx_path,
+ staged_dir,
+ include_flat_svg=(
+ not args.manifest_only and args.inheritance_mode == "both"
+ ),
+ )
+ except (RuntimeError, OSError, ValueError) as exc:
+ print(f"Error: failed to extract PPTX metadata: {exc}")
+ return 1
+
+ manifest_path.write_text(
+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ try:
+ native_structure = write_native_structure_bundle(
+ pptx_path,
+ staged_dir,
+ manifest,
+ )
+ except (OSError, ValueError) as exc:
+ print(f"Error: failed to write native structure bundle: {exc}")
+ return 1
+
+ result = None
+ total_bytes = 0
+ if not args.manifest_only:
+ from pptx_to_svg import convert_pptx_to_svg
+ from pptx_to_svg.converter import ConvertOptions
+
+ options = ConvertOptions(
+ media_subdir="assets",
+ embed_images=args.embed_images,
+ keep_hidden=False,
+ inheritance_mode=args.inheritance_mode,
+ asset_name_map=(
+ manifest.get("assets", {}).get("assetMap", {})
+ if manifest else {}
),
)
- except (RuntimeError, OSError, ValueError) as exc:
- print(f"Error: failed to extract PPTX metadata: {exc}")
- return 1
+ try:
+ result = convert_pptx_to_svg(pptx_path, staged_dir, options)
+ except (BadZipFile, ET.ParseError, OSError, RuntimeError, ValueError) as exc:
+ print(f"Error: failed to convert PPTX template source: {exc}")
+ return 1
+ total_bytes = sum(
+ len(art.svg.encode("utf-8"))
+ for art in result.slides
+ )
+
+ from pptx_to_svg.converter import publish_staged_workspace
- manifest_path.write_text(
- json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
- encoding="utf-8",
- )
try:
- native_structure = write_native_structure_bundle(
- pptx_path,
+ publish_staged_workspace(
output_dir,
- manifest,
+ staged_dir,
+ managed_root_files={
+ _MANIFEST_NAME,
+ CONTRACT_NAME,
+ SOURCE_TEMPLATE_NAME,
+ _CONVERSION_REPORT_NAME,
+ },
+ managed_relative_paths=previous_assets,
)
- except (OSError, ValueError) as exc:
- print(f"Error: failed to write native structure bundle: {exc}")
+ except (OSError, RuntimeError, ValueError) as exc:
+ print(f"Error: failed to publish PPTX template workspace: {exc}")
return 1
- if args.manifest_only:
- print(f"Imported PPTX template source: {pptx_path.name}")
+ if args.manifest_only:
+ print(f"Imported PPTX template source: {pptx_path.name}")
+ print(f"Output directory: {output_dir}")
+ if manifest is not None:
+ print(f"Manifest: {manifest_path.name}")
+ print(f"Native structure: {CONTRACT_NAME}")
+ print(f"Source package analysis copy: {SOURCE_TEMPLATE_NAME}")
+ print(
+ "Source structure assessment: "
+ f"{native_structure['strategy']['recommendedMode']}"
+ )
+ print("Template output mode: explicit SVG structure")
+ print(f"Assets exported: {len(manifest['assets']['allAssets'])}")
+ print(f"Common assets: {len(manifest['assets']['commonAssets'])}")
+ print(f"Slides analyzed: {len(manifest['slides'])}")
+ print(f"Layouts (unique): {len(manifest.get('layouts', []))}")
+ print(f"Masters (unique): {len(manifest.get('masters', []))}")
+ return 0
+
+ print(f"Inheritance mode: {args.inheritance_mode}")
+ print(f"Exported SVG slides: {len(result.slides)}")
+ if args.inheritance_mode in {"layered", "both"}:
+ print(f"Exported masters: {len(result.masters)}")
+ print(f"Exported layouts: {len(result.layouts)}")
+ print("Inheritance graph: svg/inheritance.json")
+ if result.flat_slides:
+ print(f"Flat companion slides: {len(result.flat_slides)} (svg-flat/)")
+ if result.diagnostics:
+ print(
+ f"Source recovery warnings: {len(result.diagnostics)} "
+ f"({_CONVERSION_REPORT_NAME})"
+ )
+ print(f"SVG bytes (primary): {total_bytes}")
print(f"Output directory: {output_dir}")
- if manifest is not None:
- print(f"Manifest: {manifest_path.name}")
- print("Native structure: native_structure.json")
- print("Source package analysis copy: source_template.pptx")
+ if native_structure is not None:
print(
"Source structure assessment: "
- f"{native_structure['strategy']['recommendedMode']}"
+ f"{native_structure['strategy']['recommendedMode']}; "
+ "create-template rebuilds explicit SVG structure"
)
- print("Template output mode: explicit SVG structure")
- print(f"Assets exported: {len(manifest['assets']['allAssets'])}")
- print(f"Common assets: {len(manifest['assets']['commonAssets'])}")
- print(f"Slides analyzed: {len(manifest['slides'])}")
- print(f"Layouts (unique): {len(manifest.get('layouts', []))}")
- print(f"Masters (unique): {len(manifest.get('masters', []))}")
return 0
-
- from pptx_to_svg import convert_pptx_to_svg
- from pptx_to_svg.converter import ConvertOptions
-
- options = ConvertOptions(
- media_subdir="assets",
- embed_images=args.embed_images,
- keep_hidden=False,
- inheritance_mode=args.inheritance_mode,
- asset_name_map=manifest.get("assets", {}).get("assetMap", {}) if manifest else {},
- )
- try:
- result = convert_pptx_to_svg(pptx_path, output_dir, options)
- except (BadZipFile, ET.ParseError, OSError, RuntimeError, ValueError) as exc:
- print(f"Error: failed to convert PPTX template source: {exc}")
- return 1
- total_bytes = sum(len(art.svg.encode("utf-8")) for art in result.slides)
-
- print(f"Inheritance mode: {args.inheritance_mode}")
- print(f"Exported SVG slides: {len(result.slides)}")
- if args.inheritance_mode in {"layered", "both"}:
- print(f"Exported masters: {len(result.masters)}")
- print(f"Exported layouts: {len(result.layouts)}")
- print("Inheritance graph: svg/inheritance.json")
- if result.flat_slides:
- print(f"Flat companion slides: {len(result.flat_slides)} (svg-flat/)")
- if result.diagnostics:
- print(
- f"Source recovery warnings: {len(result.diagnostics)} "
- "(conversion-report.json)"
- )
- print(f"SVG bytes (primary): {total_bytes}")
- print(f"Output directory: {output_dir}")
- if native_structure is not None:
- print(
- "Source structure assessment: "
- f"{native_structure['strategy']['recommendedMode']}; "
- "create-template rebuilds explicit SVG structure"
- )
- return 0
+ finally:
+ shutil.rmtree(staging_root, ignore_errors=True)
if __name__ == "__main__":
diff --git a/skills/ppt-master/scripts/pptx_to_svg/converter.py b/skills/ppt-master/scripts/pptx_to_svg/converter.py
index fa867f4d..370b0dd4 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/converter.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/converter.py
@@ -14,10 +14,15 @@ loads the package and reports basic per-slide structure to verify wiring.
from __future__ import annotations
import json
+import os
import re
+import shutil
+import tempfile
from collections.abc import Callable
from dataclasses import dataclass, field
+from html import unescape
from pathlib import Path, PurePosixPath
+from urllib.parse import unquote, urlsplit
from .color_resolver import ColorPalette
from .emu_units import NS
@@ -32,6 +37,37 @@ from .slide_to_svg import assemble_part_solo, assemble_slide
_CJK_THEME_SCRIPTS = frozenset({"Hans", "Hant", "Jpan", "Hang"})
+_MANAGED_PRIMARY_SVG_RE = re.compile(
+ r"(?:slide_\d+|master_\d+_[A-Za-z0-9_-]+|layout_\d+_[A-Za-z0-9_-]+)\.svg"
+)
+_MANAGED_FLAT_SVG_RE = re.compile(r"slide_\d+\.svg")
+_SVG_HREF_RE = re.compile(
+ r"\b(?:href|xlink:href)\s*=\s*[\"']([^\"']+)[\"']"
+)
+
+
+def _validate_media_subdir(value: str) -> None:
+ """Reject media output paths that can escape the conversion workspace."""
+ path = Path(value)
+ if path.drive or path.anchor or path.is_absolute() or ".." in path.parts:
+ raise ValueError(
+ f"media_subdir must stay within the output workspace: {value!r}"
+ )
+
+
+def _validate_media_filename(filename: str) -> None:
+ """Require one media basename so asset maps cannot redirect writes."""
+ path = Path(filename)
+ if (
+ not filename
+ or filename in {".", ".."}
+ or path.drive
+ or path.anchor
+ or path.name != filename
+ or "/" in filename
+ or "\\" in filename
+ ):
+ raise ValueError(f"Media filename must be a basename: {filename!r}")
def _extract_theme_info(
@@ -241,6 +277,8 @@ def convert_pptx_to_svg(
f"inheritance_mode must be 'flat', 'layered', or 'both', "
f"got {options.inheritance_mode!r}"
)
+ if not options.embed_images:
+ _validate_media_subdir(options.media_subdir)
emit_layered = options.inheritance_mode in {"layered", "both"}
emit_flat = options.inheritance_mode in {"flat", "both"}
result = ConvertResult(
@@ -485,9 +523,269 @@ def _render_part(
)
-def _write_artifacts(output_dir: Path, result: ConvertResult,
- options: ConvertOptions) -> None:
- """Write SVG + media files to output_dir.
+def _path_lexists(path: Path) -> bool:
+ """Return whether a path or symlink exists without following the symlink."""
+ return path.exists() or path.is_symlink()
+
+
+def _managed_svg_paths(output_dir: Path) -> list[Path]:
+ """Return converter-owned SVG files without traversing user directories."""
+ managed: list[Path] = []
+ for dirname, filename_re in (
+ ("svg", _MANAGED_PRIMARY_SVG_RE),
+ ("svg-flat", _MANAGED_FLAT_SVG_RE),
+ ):
+ svg_dir = output_dir / dirname
+ if svg_dir.is_symlink():
+ managed.append(svg_dir)
+ continue
+ if not svg_dir.is_dir():
+ continue
+ managed.extend(
+ path
+ for path in svg_dir.iterdir()
+ if filename_re.fullmatch(path.name)
+ and (path.is_file() or path.is_symlink())
+ )
+ inheritance = svg_dir / "inheritance.json"
+ if dirname == "svg" and _path_lexists(inheritance):
+ managed.append(inheritance)
+ return managed
+
+
+def _referenced_local_paths(
+ output_dir: Path,
+ svg_paths: list[Path],
+) -> set[Path]:
+ """Resolve local media referenced by converter-owned SVGs."""
+ referenced: set[Path] = set()
+ output_abs = output_dir.absolute()
+ for svg_path in svg_paths:
+ if svg_path.is_symlink() or not svg_path.is_file():
+ continue
+ try:
+ svg_text = svg_path.read_text(encoding="utf-8")
+ except (OSError, UnicodeError):
+ continue
+ for raw_href in _SVG_HREF_RE.findall(svg_text):
+ href = unescape(raw_href)
+ parsed = urlsplit(href)
+ if parsed.scheme or parsed.netloc or not parsed.path:
+ continue
+ href_path = unquote(parsed.path)
+ if Path(href_path).is_absolute():
+ continue
+ target = Path(os.path.normpath(str(svg_path.parent / href_path)))
+ try:
+ relative = target.absolute().relative_to(output_abs)
+ except ValueError:
+ continue
+ if relative.parts:
+ referenced.add(relative)
+ return referenced
+
+
+def _validated_relative_paths(paths: set[str | Path]) -> set[Path]:
+ """Normalize caller-supplied managed paths and reject output escapes."""
+ normalized: set[Path] = set()
+ for value in paths:
+ path = Path(value)
+ if (
+ path.drive
+ or path.anchor
+ or path.is_absolute()
+ or not path.parts
+ or ".." in path.parts
+ ):
+ raise ValueError(f"Managed artifact path must stay relative: {value}")
+ normalized.add(path)
+ return normalized
+
+
+def _reject_symlink_ancestors(
+ root: Path,
+ relative_paths: set[Path],
+) -> None:
+ """Reject managed paths that would traverse a preserved user symlink."""
+ for relative in relative_paths:
+ current = root
+ for component in relative.parts[:-1]:
+ current /= component
+ if current.is_symlink():
+ raise RuntimeError(
+ "Managed artifact path crosses an unmanaged symlink: "
+ f"{relative}"
+ )
+
+
+def _remove_managed_paths(candidate_dir: Path, relative_paths: set[Path]) -> None:
+ """Remove only the previous converter roster from a candidate workspace."""
+ _reject_symlink_ancestors(candidate_dir, relative_paths)
+ parents: set[Path] = set()
+ for relative in sorted(
+ relative_paths,
+ key=lambda item: len(item.parts),
+ reverse=True,
+ ):
+ target = candidate_dir / relative
+ if target.is_symlink() or target.is_file():
+ target.unlink()
+ elif target.is_dir():
+ raise RuntimeError(
+ "Managed artifact path collides with a preserved directory: "
+ f"{relative}"
+ )
+ parent = target.parent
+ while parent != candidate_dir:
+ parents.add(parent)
+ parent = parent.parent
+
+ for parent in sorted(parents, key=lambda item: len(item.parts), reverse=True):
+ if parent.is_symlink() or not parent.is_dir():
+ continue
+ try:
+ parent.rmdir()
+ except OSError:
+ pass
+
+
+def _overlay_staged_tree(staged_dir: Path, candidate_dir: Path) -> None:
+ """Overlay generated artifacts without overwriting unmanaged user files."""
+ for source in sorted(staged_dir.rglob("*")):
+ relative = source.relative_to(staged_dir)
+ target = candidate_dir / relative
+ _reject_symlink_ancestors(candidate_dir, {relative})
+ if source.is_symlink():
+ raise RuntimeError(
+ f"Generated artifact must not be a symlink: {relative}"
+ )
+ if source.is_dir():
+ if (
+ target.is_symlink()
+ or (_path_lexists(target) and not target.is_dir())
+ ):
+ raise RuntimeError(
+ f"Generated artifact collides with unmanaged path: {relative}"
+ )
+ target.mkdir(parents=True, exist_ok=True)
+ continue
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if _path_lexists(target):
+ if target.is_dir() or target.is_symlink():
+ raise RuntimeError(
+ f"Generated artifact collides with unmanaged path: {relative}"
+ )
+ if target.read_bytes() != source.read_bytes():
+ raise RuntimeError(
+ f"Generated artifact collides with unmanaged file: {relative}"
+ )
+ shutil.copy2(source, target)
+
+
+def publish_staged_workspace(
+ output_dir: Path,
+ staged_dir: Path,
+ *,
+ managed_root_files: set[str | Path] | None = None,
+ managed_relative_paths: set[str | Path] | None = None,
+) -> None:
+ """Atomically publish generated artifacts while preserving user files.
+
+ Converter-owned SVGs, their local media references, and the named managed
+ artifacts are replaced as one roster. Everything else already present in
+ the output directory is copied into the candidate unchanged.
+ """
+ output_dir = output_dir.absolute()
+ staged_dir = staged_dir.absolute()
+ if (
+ output_dir == staged_dir
+ or output_dir in staged_dir.parents
+ or staged_dir in output_dir.parents
+ ):
+ raise ValueError(
+ "Staged and output workspaces must not contain one another"
+ )
+ output_resolved = output_dir.resolve(strict=False)
+ try:
+ Path.cwd().resolve().relative_to(output_resolved)
+ except ValueError:
+ pass
+ else:
+ raise RuntimeError(
+ "Output workspace must not contain the current working directory"
+ )
+ if not staged_dir.is_dir():
+ raise ValueError(f"Staged workspace does not exist: {staged_dir}")
+ if (
+ output_dir.is_symlink()
+ or (_path_lexists(output_dir) and not output_dir.is_dir())
+ ):
+ raise RuntimeError(f"Output path must be a real directory: {output_dir}")
+
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
+ transaction_dir = Path(tempfile.mkdtemp(
+ prefix=f".{output_dir.name}.publish-",
+ dir=output_dir.parent,
+ ))
+ candidate_dir = transaction_dir / "candidate"
+ backup_dir = transaction_dir / "previous"
+ preserve_backup = False
+
+ try:
+ if output_dir.is_dir():
+ shutil.copytree(output_dir, candidate_dir, symlinks=True)
+ else:
+ candidate_dir.mkdir()
+
+ managed_svg = _managed_svg_paths(output_dir)
+ relative_paths = {
+ path.relative_to(output_dir)
+ for path in managed_svg
+ }
+ relative_paths.update(_referenced_local_paths(output_dir, managed_svg))
+ relative_paths.add(Path("conversion-report.json"))
+ relative_paths.update(_validated_relative_paths(managed_root_files or set()))
+ relative_paths.update(_validated_relative_paths(managed_relative_paths or set()))
+ _remove_managed_paths(candidate_dir, relative_paths)
+ _overlay_staged_tree(staged_dir, candidate_dir)
+
+ if output_dir.is_dir():
+ try:
+ os.replace(output_dir, backup_dir)
+ os.replace(candidate_dir, output_dir)
+ except BaseException as publish_error:
+ try:
+ if _path_lexists(backup_dir):
+ if _path_lexists(output_dir):
+ failed_output = transaction_dir / "failed-publish"
+ os.replace(output_dir, failed_output)
+ os.replace(backup_dir, output_dir)
+ except BaseException as restore_error:
+ if (
+ not _path_lexists(backup_dir)
+ and _path_lexists(output_dir)
+ ):
+ raise publish_error
+ preserve_backup = _path_lexists(backup_dir)
+ raise RuntimeError(
+ "Failed to publish the new workspace and restore the "
+ "previous workspace; recovery directory: "
+ f"{transaction_dir}"
+ ) from restore_error
+ raise
+ else:
+ os.replace(candidate_dir, output_dir)
+ finally:
+ if not preserve_backup:
+ shutil.rmtree(transaction_dir, ignore_errors=True)
+
+
+def _write_artifact_tree(
+ output_dir: Path,
+ result: ConvertResult,
+ options: ConvertOptions,
+) -> None:
+ """Write a complete converter roster into an empty staging directory.
Layout:
- ``svg/`` primary view (layered when emitted, otherwise flat)
@@ -498,34 +796,32 @@ def _write_artifacts(output_dir: Path, result: ConvertResult,
svg_dir = output_dir / "svg"
svg_dir.mkdir(exist_ok=True)
media_dir = output_dir / options.media_subdir
- media_written: set[str] = set()
+ media_written: dict[str, bytes] = {}
- def _write_media(media: dict[str, bytes]) -> None:
+ def _collect_media(media: dict[str, bytes]) -> None:
for filename, blob in media.items():
+ _validate_media_filename(filename)
if filename in media_written:
+ if media_written[filename] != blob:
+ raise RuntimeError(
+ f"Asset filename collision with different bytes: {filename}"
+ )
continue
- media_dir.mkdir(parents=True, exist_ok=True)
- target = media_dir / filename
- if target.exists():
- if target.read_bytes() != blob:
- raise RuntimeError(f"Asset filename collision with different bytes: {filename}")
- else:
- target.write_bytes(blob)
- media_written.add(filename)
+ media_written[filename] = blob
# Layered mode: write masters and layouts first so they sort ahead of slides.
for art in result.masters:
(svg_dir / art.filename).write_text(art.svg, encoding="utf-8")
- _write_media(art.media_files)
+ _collect_media(art.media_files)
for art in result.layouts:
(svg_dir / art.filename).write_text(art.svg, encoding="utf-8")
- _write_media(art.media_files)
+ _collect_media(art.media_files)
# Slides (primary view).
for art in result.slides:
target = svg_dir / f"slide_{art.index:02d}.svg"
target.write_text(art.svg, encoding="utf-8")
- _write_media(art.media_files)
+ _collect_media(art.media_files)
# Inheritance graph alongside the layered SVGs (only meaningful when we
# actually emitted a layered view).
@@ -539,9 +835,44 @@ def _write_artifacts(output_dir: Path, result: ConvertResult,
for art in result.flat_slides:
target = flat_dir / f"slide_{art.index:02d}.svg"
target.write_text(art.svg, encoding="utf-8")
- _write_media(art.media_files)
+ _collect_media(art.media_files)
_write_conversion_report(output_dir, result)
+ if media_written:
+ media_dir.mkdir(parents=True, exist_ok=True)
+ for filename, blob in media_written.items():
+ target = media_dir / filename
+ if _path_lexists(target):
+ if (
+ target.is_symlink()
+ or not target.is_file()
+ or target.read_bytes() != blob
+ ):
+ raise RuntimeError(
+ f"Asset filename collision with different bytes: {filename}"
+ )
+ continue
+ target.write_bytes(blob)
+
+
+def _write_artifacts(
+ output_dir: Path,
+ result: ConvertResult,
+ options: ConvertOptions,
+) -> None:
+ """Stage a complete conversion, then atomically publish its exact roster."""
+ output_dir = output_dir.absolute()
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
+ staging_root = Path(tempfile.mkdtemp(
+ prefix=f".{output_dir.name}.convert-",
+ dir=output_dir.parent,
+ ))
+ staged_dir = staging_root / "generated"
+ try:
+ _write_artifact_tree(staged_dir, result, options)
+ publish_staged_workspace(output_dir, staged_dir)
+ finally:
+ shutil.rmtree(staging_root, ignore_errors=True)
def _write_conversion_report(output_dir: Path, result: ConvertResult) -> None:
diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
index 023a8a59..ca462992 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
@@ -64,7 +64,7 @@ from .ooxml_loader import (
SlideRef,
inherited_shape_visibility,
)
-from .pic_to_svg import convert_blip_fill, convert_picture
+from .pic_to_svg import MediaResolutionError, convert_blip_fill, convert_picture
from .prstgeom_to_svg import GeomResult, convert_prst_geom
from .preset_svg_markup import serialize_preset_layers
from .shape_walker import (
@@ -214,7 +214,7 @@ def assemble_slide(
ctx, canvas_w, canvas_h,
)
)
- except ValueError as exc:
+ except (ValueError, MediaResolutionError) as exc:
if strict:
raise
ctx.diagnose(
@@ -340,7 +340,7 @@ def assemble_part_solo(
)
try:
bg_xml = _emit_part_background(fake_slide, ctx, canvas_w, canvas_h)
- except ValueError as exc:
+ except (ValueError, MediaResolutionError) as exc:
if strict:
raise
ctx.diagnose(
@@ -458,7 +458,7 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->
embed_inline=ctx.embed_images,
asset_name_map=ctx.asset_name_map,
)
- except ValueError as exc:
+ except (ValueError, MediaResolutionError) as exc:
if ctx.strict:
raise
ctx.diagnose(
@@ -923,12 +923,22 @@ def _inject_clip_path(image_xml: str, clip_id: str) -> str:
def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
sp_pr = node.xml.find("p:spPr", NS)
geom = _resolve_geometry(node, sp_pr)
- result = convert_picture(
- node.xml, node.xfrm, ctx.slide_part, ctx.pkg,
- media_subdir=ctx.media_subdir,
- embed_inline=ctx.embed_images,
- asset_name_map=ctx.asset_name_map,
- )
+ try:
+ result = convert_picture(
+ node.xml, node.xfrm, ctx.slide_part, ctx.pkg,
+ media_subdir=ctx.media_subdir,
+ embed_inline=ctx.embed_images,
+ asset_name_map=ctx.asset_name_map,
+ )
+ except MediaResolutionError as exc:
+ if ctx.strict:
+ raise
+ ctx.diagnose(
+ "object-replaced",
+ str(exc),
+ "replace only this picture with a visible placeholder",
+ )
+ return _fallback_node_svg(node, ctx, top_level=top_level)
if not result.svg:
return ""
ctx.media.update(result.media)
@@ -1046,11 +1056,30 @@ def _convert_graphic_fallback(node: ShapeNode, ctx: AssemblyContext,
extra_attrs=replacement_attrs,
)
+ preview_svg = ""
+ if ctx.render_graphic_previews:
+ try:
+ preview_svg = _render_graphic_preview(node, ctx)
+ except MediaResolutionError as exc:
+ if ctx.strict:
+ raise
+ ctx.diagnose(
+ "preview-omitted",
+ str(exc),
+ "omit the missing baked preview and retain the native, "
+ "normalized, or placeholder fallback",
+ )
+
chart_replacement_attrs: list[str] = []
chart_payload_metadata = ""
if uri in {CHART_URI, CHARTEX_URI}:
rendered, chart_replacement_attrs, chart_payload_metadata = (
- _render_graphic_chart(node, ctx, graphic_data)
+ _render_graphic_chart(
+ node,
+ ctx,
+ graphic_data,
+ preview_svg,
+ )
)
if rendered:
inner = (
@@ -1066,17 +1095,25 @@ def _convert_graphic_fallback(node: ShapeNode, ctx: AssemblyContext,
extra_attrs=chart_replacement_attrs,
)
- if uri == "http://schemas.openxmlformats.org/presentationml/2006/ole" and ctx.render_graphic_previews:
- rendered = _render_graphic_preview(node, ctx)
- if rendered:
- labelled = rendered + "\n" + _graphic_preview_label(node, "ole preview")
+ if uri == "http://schemas.openxmlformats.org/presentationml/2006/ole":
+ if preview_svg:
+ labelled = (
+ preview_svg
+ + "\n"
+ + _graphic_preview_label(node, "ole preview")
+ )
return _wrap_shape_group(labelled, node, ctx, top_level=top_level)
- if ctx.render_graphic_previews:
- rendered = _render_graphic_preview(node, ctx)
- if rendered:
- labelled = rendered + "\n" + _graphic_preview_label(node, f"{uri.rsplit('/', 1)[-1]} preview")
- return _wrap_shape_group(labelled, node, ctx, top_level=top_level)
+ if preview_svg:
+ labelled = (
+ preview_svg
+ + "\n"
+ + _graphic_preview_label(
+ node,
+ f"{uri.rsplit('/', 1)[-1]} preview",
+ )
+ )
+ return _wrap_shape_group(labelled, node, ctx, top_level=top_level)
label = uri.rsplit("/", 1)[-1]
placeholder = (
@@ -1170,6 +1207,7 @@ def _render_graphic_chart(
node: ShapeNode,
ctx: AssemblyContext,
graphic_data: ET.Element | None,
+ preview_svg: str,
) -> tuple[str, list[str], str]:
"""Return a chart fallback plus native Chart replacement metadata."""
result = extract_native_chart_payload(
@@ -1192,9 +1230,7 @@ def _render_graphic_chart(
f'{_xml_escape(result.native_status)}"'
)
- rendered = ""
- if ctx.render_graphic_previews:
- rendered = _render_graphic_preview(node, ctx)
+ rendered = preview_svg
if rendered:
replacement_attrs.append('data-pptx-fallback-kind="source-preview"')
elif result.normalized_svg:
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 fa25d301..03189794 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -752,6 +752,8 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
# translation here and apply pivot-centre compensation to ``a:off``
# below instead.
rotate_pivot = _extract_rotate_pivot(transform) if not matrix_supported else None
+ if rotate_pivot is not None:
+ angle_deg = parse_transform_operations(transform)[0][1][0]
if matrix_supported:
child_ctx = ctx.child(
0, 0, 1.0, 1.0,
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 2c262709..8d7f807b 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -2584,6 +2584,16 @@ def _coalesce_text_runs(
return merged
+def _text_axis_transform(ctx: ConvertContext) -> tuple[bool, bool, bool]:
+ """Return whether text can consume the context matrix and its axis flips."""
+ if not ctx.use_transform_matrix:
+ return False, False, False
+ a, b, c, d, _e, _f = ctx.transform_matrix
+ if abs(b) > 1e-9 or abs(c) > 1e-9:
+ return False, False, False
+ return True, a < 0, d < 0
+
+
def _build_run_xml(
run: dict[str, Any],
default_fonts: dict[str, str],
@@ -2608,8 +2618,14 @@ def _build_run_xml(
def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
"""Convert SVG <text> to DrawingML text shape with multi-run support."""
- x = ctx_x(svg_length_x(elem.get('x'), ctx), ctx)
- y = ctx_y(svg_length_y(elem.get('y'), ctx), ctx)
+ raw_x = svg_length_x(elem.get('x'), ctx)
+ raw_y = svg_length_y(elem.get('y'), ctx)
+ use_axis_transform, reflect_x, reflect_y = _text_axis_transform(ctx)
+ if use_axis_transform:
+ x, y = transform_point(ctx.transform_matrix, raw_x, raw_y)
+ else:
+ x = ctx_x(raw_x, ctx)
+ y = ctx_y(raw_y, ctx)
resolved_font_size = ctx.text_font_sizes.get(id(elem))
font_size = (
resolved_font_size * ctx.scale_y
@@ -2627,6 +2643,11 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
text_anchor = parse_project_text_anchor(
_get_attr(elem, 'text-anchor', ctx) or 'start'
).canonical
+ if reflect_x:
+ text_anchor = {
+ 'start': 'end',
+ 'end': 'start',
+ }.get(text_anchor, text_anchor)
fill_raw = _get_attr(elem, 'fill', ctx) or '#000000'
fill_color = parse_hex_color(fill_raw) or '000000'
opacity = get_fill_opacity(elem, ctx)
@@ -2813,6 +2834,8 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
box_y = y - font_size * 0.85
box_w = text_width + padding * 2
box_h = text_height + padding
+ if reflect_y:
+ box_y = 2 * y - box_y - box_h
visual_box_x = box_x
visual_box_y = box_y
@@ -2823,10 +2846,22 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
if exact_text_frame is None:
raise ValueError('data-pptx-frame did not resolve to a text frame')
raw_frame_x, raw_frame_y, raw_frame_w, raw_frame_h = exact_text_frame
- frame_x_1 = ctx_x(raw_frame_x, ctx)
- frame_x_2 = ctx_x(raw_frame_x + raw_frame_w, ctx)
- frame_y_1 = ctx_y(raw_frame_y, ctx)
- frame_y_2 = ctx_y(raw_frame_y + raw_frame_h, ctx)
+ if use_axis_transform:
+ frame_x_1, frame_y_1 = transform_point(
+ ctx.transform_matrix,
+ raw_frame_x,
+ raw_frame_y,
+ )
+ frame_x_2, frame_y_2 = transform_point(
+ ctx.transform_matrix,
+ raw_frame_x + raw_frame_w,
+ raw_frame_y + raw_frame_h,
+ )
+ else:
+ frame_x_1 = ctx_x(raw_frame_x, ctx)
+ frame_x_2 = ctx_x(raw_frame_x + raw_frame_w, ctx)
+ frame_y_1 = ctx_y(raw_frame_y, ctx)
+ frame_y_2 = ctx_y(raw_frame_y + raw_frame_h, ctx)
box_x = min(frame_x_1, frame_x_2)
box_y = min(frame_y_1, frame_y_2)
box_w = abs(frame_x_2 - frame_x_1)
@@ -2875,6 +2910,13 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
raw_box_y = (box_y - ctx.translate_y) / sy
box_x = ctx.translate_x + sx * (a * raw_box_x + e)
box_y = ctx.translate_y + sy * (d * raw_box_y + f)
+ elif translate_only and use_axis_transform:
+ _a, _b, _c, _d, e, f = parse_transform_matrix(text_transform)
+ matrix_a, matrix_b, matrix_c, matrix_d, _matrix_e, _matrix_f = (
+ ctx.transform_matrix
+ )
+ box_x += matrix_a * e + matrix_c * f
+ box_y += matrix_b * e + matrix_d * f
# Text rotation. SVG's rotate(angle [cx cy]) rotates around (cx, cy), but
# DrawingML's <a:xfrm rot="..."> rotates the shape around its own center.
@@ -2885,10 +2927,19 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
if rotate_only:
rotate_args = text_operations[0][1]
angle_deg = rotate_args[0]
+ if reflect_x != reflect_y:
+ angle_deg = -angle_deg
text_rot = int(angle_deg * ANGLE_UNIT)
if len(rotate_args) == 3:
- pivot_x = ctx_x(rotate_args[1], ctx)
- pivot_y = ctx_y(rotate_args[2], ctx)
+ if use_axis_transform:
+ pivot_x, pivot_y = transform_point(
+ ctx.transform_matrix,
+ rotate_args[1],
+ rotate_args[2],
+ )
+ else:
+ pivot_x = ctx_x(rotate_args[1], ctx)
+ pivot_y = ctx_y(rotate_args[2], ctx)
cx_box = box_x + box_w / 2
cy_box = box_y + box_h / 2
rad = math.radians(angle_deg)
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 12f6dc75..8744c458 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
@@ -1101,6 +1101,22 @@ def _is_unit_axis_reflection(
operations: tuple[tuple[str, tuple[float, ...]], ...],
) -> bool:
"""Return whether a transform is translation plus an unscaled axis flip."""
+ has_explicit_flip = any(
+ (
+ name == 'scale'
+ and (
+ args[0] < 0
+ or (len(args) > 1 and args[1] < 0)
+ )
+ )
+ or (
+ name == 'matrix'
+ and (args[0] < 0 or args[3] < 0)
+ )
+ for name, args in operations
+ )
+ if not has_explicit_flip:
+ return False
matrix = _transform_operations_matrix(operations)
a, b, c, d, _e, _f = matrix
return (