AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
feat(pptx_to_svg): semantic OOXML→SVG converter as reverse of svg_to_pptx
hugohe38e434ab2e623
diff --git a/skills/ppt-master/scripts/pptx_template_import.py b/skills/ppt-master/scripts/pptx_template_import.pyindex 8d995d0b..e6ec9df2 100644--- a/skills/ppt-master/scripts/pptx_template_import.py+++ b/skills/ppt-master/scripts/pptx_template_import.py@@ -240,20 +240,35 @@ def parse_args() -> argparse.Namespace:action="store_true",help="Only extract manifest.json, analysis.md, and reusable assets without exporting slides to SVG",)+ parser.add_argument(+ "--legacy-render",+ action="store_true",+ help=(+ "Use the legacy renderer (PowerPoint COM on Windows, Keynote -> PDF "+ "on macOS). Lossy: text becomes <path>, every cropped picture spawns "+ "a new inline_*.png slice. The default semantic converter "+ "(pptx_to_svg) reads OOXML directly and preserves shape primitives."+ ),+ )parser.add_argument("--keep-raw",action="store_true",- help="Keep raw PowerPoint-exported SVG files in svg_raw/",+ help="(--legacy-render only) Keep raw PowerPoint-exported SVG files in svg_raw/",)parser.add_argument("--no-externalize",action="store_true",- help="Skip inline image externalization and keep raw SVG output only",+ help="(--legacy-render only) Skip inline image externalization",)parser.add_argument("--no-optimize",action="store_true",- help="Skip the second-pass structural optimization for cleaned reference SVG files",+ help="(--legacy-render only) Skip structural optimization of the cleaned reference SVGs",+ )+ parser.add_argument(+ "--embed-images",+ action="store_true",+ help="(default renderer only) Inline images as data: URIs instead of writing files to assets/",)return parser.parse_args()@@ -390,18 +405,82 @@ def main() -> int:print(f"Slides analyzed: {len(manifest['slides'])}")return 0+ # ---------- Slide rendering ----------+ if args.legacy_render:+ export_mode, slide_count, total_in, total_out = _render_slides_legacy(+ pptx_path, output_dir, args,+ )+ else:+ export_mode, slide_count, total_in, total_out = _render_slides_native(+ pptx_path, output_dir, args,+ )++ # reference_svg_selection.json (shared between both paths)+ cleaned_dir = output_dir / "svg"+ reference_selection = build_reference_svg_selection(+ manifest, sorted(cleaned_dir.glob("*.svg")),+ )+ (output_dir / "reference_svg_selection.json").write_text(+ json.dumps(reference_selection, ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )++ print(f"Export mode: {export_mode}")+ print(f"Exported SVG slides: {slide_count}")+ if total_in is not None and total_out is not None:+ print(f"SVG bytes: {total_in} -> {total_out}")+ print(f"Reference SVG selection: {output_dir / 'reference_svg_selection.json'}")+ print(f"Output directory: {output_dir}")+ return 0+++# ---------------------------------------------------------------------------+# Slide rendering — default (native, semantic) path+# ---------------------------------------------------------------------------++def _render_slides_native(+ pptx_path: Path,+ output_dir: Path,+ args: argparse.Namespace,+) -> tuple[str, int, int | None, int | None]:+ """Read OOXML directly via pptx_to_svg and emit shape-level SVGs.++ This path preserves text as <text>, picture primitives as <image>, and+ doesn't spawn inline_*.png crop slices. Default since stage G integration.+ """+ 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,+ )+ result = convert_pptx_to_svg(pptx_path, output_dir, options)+ total_bytes = sum(len(art.svg.encode("utf-8")) for art in result.slides)+ return "pptx_to_svg-native", len(result.slides), total_bytes, total_bytes+++# ---------------------------------------------------------------------------+# Slide rendering — legacy (PowerPoint COM / Keynote PDF) path+# ---------------------------------------------------------------------------++def _render_slides_legacy(+ pptx_path: Path,+ output_dir: Path,+ args: argparse.Namespace,+) -> tuple[str, int, int | None, int | None]:+ """Original lossy renderer: rasterize via PowerPoint or Keynote->PDF, then+ externalize/optimize. Preserved for cases where the new semantic converter+ misbehaves; intentionally opt-in (--legacy-render).+ """raw_dir = output_dir / "svg_raw"- try:- raw_svg_files, export_mode = export_pptx_slides_to_svg_with_fallback(pptx_path, raw_dir)- except Exception as exc:- print(f"Error: failed to export PPTX slides to SVG: {exc}")- return 1+ raw_svg_files, export_mode = export_pptx_slides_to_svg_with_fallback(+ pptx_path, raw_dir,+ )if args.no_externalize:- print(f"Export mode: {export_mode}")- print(f"Exported raw SVG slides: {len(raw_svg_files)}")- print(f"Output directory: {output_dir}")- return 0+ return export_mode, len(raw_svg_files), None, Nonecleaned_dir = output_dir / "svg"results = externalize_svg_batch(@@ -412,7 +491,9 @@ def main() -> int:final_svg_bytes = sum(item.output_svg_bytes for item in results)if not args.no_optimize:- optimize_results, optimize_output_dir = optimize_reference_batch([str(cleaned_dir)], precision=2)+ optimize_results, optimize_output_dir = optimize_reference_batch(+ [str(cleaned_dir)], precision=2,+ )before_opt = sum(item.original_bytes for item in optimize_results)after_opt = sum(item.optimized_bytes for item in optimize_results)final_svg_bytes = after_opt@@ -423,24 +504,13 @@ def main() -> int:if not args.keep_raw:for svg_file in raw_dir.glob("*.svg"):svg_file.unlink(missing_ok=True)- raw_dir.rmdir()-- reference_selection = build_reference_svg_selection(manifest, sorted(cleaned_dir.glob("*.svg")))- (output_dir / "reference_svg_selection.json").write_text(- json.dumps(reference_selection, ensure_ascii=False, indent=2) + "\n",- encoding="utf-8",- )+ if raw_dir.exists():+ raw_dir.rmdir()total_before = sum(item.original_svg_bytes for item in results)total_images = sum(item.images_externalized for item in results)-- print(f"Export mode: {export_mode}")- print(f"Exported SVG slides: {len(results)}")print(f"Inline images externalized: {total_images}")- print(f"SVG bytes: {total_before} -> {final_svg_bytes}")- print(f"Reference SVG selection: {output_dir / 'reference_svg_selection.json'}")- print(f"Output directory: {output_dir}")- return 0+ return export_mode, len(results), total_before, final_svg_bytesif __name__ == "__main__":diff --git a/skills/ppt-master/scripts/pptx_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg.pynew file mode 100644index 00000000..2bf59c09--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg.py@@ -0,0 +1,100 @@+#!/usr/bin/env python3+"""CLI entry: convert a .pptx file to one SVG per slide.++Usage:+ python3 pptx_to_svg.py <pptx_file> [-o <output_dir>] [--embed-images]+ [--media-subdir <name>] [--keep-hidden]++Output structure:+ <output_dir>/+ svg/+ slide_01.svg+ slide_02.svg+ ...+ <media_subdir>/ (default: assets/)+ image1.png+ image2.png+ ...++If -o is omitted, writes alongside the source file as <pptx_stem>_pptx_to_svg/.++This is the reverse of svg_to_pptx.py: it reads OOXML directly and emits+shape-level SVG without going through PowerPoint or PDF rendering.+"""++from __future__ import annotations++import argparse+import sys+from pathlib import Path++# Allow running this script from anywhere+sys.path.insert(0, str(Path(__file__).resolve().parent))++from pptx_to_svg import convert_pptx_to_svg+from pptx_to_svg.converter import ConvertOptions+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Convert .pptx to per-slide SVG by reading OOXML directly.",+ )+ parser.add_argument("pptx_file", help="Path to the source .pptx file")+ parser.add_argument(+ "-o", "--output",+ help="Output directory (default: <pptx_stem>_pptx_to_svg beside source)",+ )+ parser.add_argument(+ "--media-subdir", default="assets",+ help="Subdirectory for extracted media (default: assets)",+ )+ parser.add_argument(+ "--embed-images", action="store_true",+ help="Base64-embed images inline instead of writing files",+ )+ parser.add_argument(+ "--keep-hidden", action="store_true",+ help='Include shapes marked hidden="1"',+ )+ return parser.parse_args()+++def main() -> int:+ args = parse_args()+ pptx_path = Path(args.pptx_file).expanduser().resolve()+ if not pptx_path.exists():+ print(f"Error: file does not exist: {pptx_path}", file=sys.stderr)+ return 1+ if pptx_path.suffix.lower() != ".pptx":+ print(f"Error: expected a .pptx file, got: {pptx_path.name}",+ file=sys.stderr)+ return 1++ output_dir = (+ Path(args.output).expanduser().resolve() if args.output+ else pptx_path.with_name(f"{pptx_path.stem}_pptx_to_svg")+ )++ options = ConvertOptions(+ media_subdir=args.media_subdir,+ embed_images=args.embed_images,+ keep_hidden=args.keep_hidden,+ )++ result = convert_pptx_to_svg(pptx_path, output_dir, options)++ print(f"Source: {pptx_path.name}")+ print(f"Canvas: {result.canvas_px[0]:.0f} x {result.canvas_px[1]:.0f} px")+ if result.theme_colors:+ scheme = ", ".join(f"{k}={v}" for k, v in sorted(result.theme_colors.items()))+ print(f"Theme colors: {scheme}")+ if result.theme_fonts:+ fonts = ", ".join(f"{k}={v}" for k, v in result.theme_fonts.items())+ print(f"Theme fonts: {fonts}")+ print(f"Slides converted: {len(result.slides)}")+ print(f"Output: {output_dir}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/ppt-master/scripts/pptx_to_svg/__init__.py b/skills/ppt-master/scripts/pptx_to_svg/__init__.pynew file mode 100644index 00000000..446630d7--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/__init__.py@@ -0,0 +1,13 @@+"""PPTX -> SVG semantic converter (reverse of svg_to_pptx).++Reads OOXML (DrawingML) directly from a .pptx zip archive and emits SVG with+shape-level fidelity: <p:sp prst="rect"> -> <rect>, <p:txBody> -> <text>, etc.++Public entry: convert_pptx_to_svg().+"""++from __future__ import annotations++from .converter import convert_pptx_to_svg++__all__ = ["convert_pptx_to_svg"]diff --git a/skills/ppt-master/scripts/pptx_to_svg/color_resolver.py b/skills/ppt-master/scripts/pptx_to_svg/color_resolver.pynew file mode 100644index 00000000..459987b0--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/color_resolver.py@@ -0,0 +1,345 @@+"""DrawingML color resolution.++Resolves any of the 6 OOXML color types (srgbClr, schemeClr, sysClr, prstClr,+hslClr, scrgbClr) plus modifiers (tint/shade/lumMod/lumOff/satMod/satOff/+hueMod/hueOff/alpha) into an (#RRGGBB, alpha) pair.++Theme palette is resolved from the slide master's a:clrMap and theme1.xml's+a:clrScheme.+"""++from __future__ import annotations++import colorsys+from xml.etree import ElementTree as ET++from .emu_units import NS, percent_to_ratio+from .ooxml_loader import PartRef+++# ---------------------------------------------------------------------------+# Preset color names (DrawingML <a:prstClr val="...">)+# ---------------------------------------------------------------------------++# Source: ECMA-376 ST_PresetColorVal (subset — full list has ~140 entries).+PRST_COLORS = {+ "aliceBlue": "F0F8FF", "antiqueWhite": "FAEBD7", "aqua": "00FFFF",+ "aquamarine": "7FFFD4", "azure": "F0FFFF", "beige": "F5F5DC",+ "bisque": "FFE4C4", "black": "000000", "blanchedAlmond": "FFEBCD",+ "blue": "0000FF", "blueViolet": "8A2BE2", "brown": "A52A2A",+ "burlyWood": "DEB887", "cadetBlue": "5F9EA0", "chartreuse": "7FFF00",+ "chocolate": "D2691E", "coral": "FF7F50", "cornflowerBlue": "6495ED",+ "cornsilk": "FFF8DC", "crimson": "DC143C", "cyan": "00FFFF",+ "darkBlue": "00008B", "darkCyan": "008B8B", "darkGoldenrod": "B8860B",+ "darkGray": "A9A9A9", "darkGrey": "A9A9A9", "darkGreen": "006400",+ "darkKhaki": "BDB76B", "darkMagenta": "8B008B", "darkOliveGreen": "556B2F",+ "darkOrange": "FF8C00", "darkOrchid": "9932CC", "darkRed": "8B0000",+ "darkSalmon": "E9967A", "darkSeaGreen": "8FBC8F", "darkSlateBlue": "483D8B",+ "darkSlateGray": "2F4F4F", "darkSlateGrey": "2F4F4F",+ "darkTurquoise": "00CED1", "darkViolet": "9400D3", "deepPink": "FF1493",+ "deepSkyBlue": "00BFFF", "dimGray": "696969", "dimGrey": "696969",+ "dkBlue": "00008B", "dkCyan": "008B8B", "dkGoldenrod": "B8860B",+ "dkGray": "A9A9A9", "dkGrey": "A9A9A9", "dkGreen": "006400",+ "dkKhaki": "BDB76B", "dkMagenta": "8B008B", "dkOliveGreen": "556B2F",+ "dkOrange": "FF8C00", "dkOrchid": "9932CC", "dkRed": "8B0000",+ "dkSalmon": "E9967A", "dkSeaGreen": "8FBC8F", "dkSlateBlue": "483D8B",+ "dkSlateGray": "2F4F4F", "dkSlateGrey": "2F4F4F",+ "dkTurquoise": "00CED1", "dkViolet": "9400D3",+ "dodgerBlue": "1E90FF", "firebrick": "B22222", "floralWhite": "FFFAF0",+ "forestGreen": "228B22", "fuchsia": "FF00FF", "gainsboro": "DCDCDC",+ "ghostWhite": "F8F8FF", "gold": "FFD700", "goldenrod": "DAA520",+ "gray": "808080", "grey": "808080", "green": "008000",+ "greenYellow": "ADFF2F", "honeydew": "F0FFF0", "hotPink": "FF69B4",+ "indianRed": "CD5C5C", "indigo": "4B0082", "ivory": "FFFFF0",+ "khaki": "F0E68C", "lavender": "E6E6FA", "lavenderBlush": "FFF0F5",+ "lawnGreen": "7CFC00", "lemonChiffon": "FFFACD",+ "lightBlue": "ADD8E6", "lightCoral": "F08080", "lightCyan": "E0FFFF",+ "lightGoldenrodYellow": "FAFAD2", "lightGray": "D3D3D3",+ "lightGrey": "D3D3D3", "lightGreen": "90EE90", "lightPink": "FFB6C1",+ "lightSalmon": "FFA07A", "lightSeaGreen": "20B2AA",+ "lightSkyBlue": "87CEFA", "lightSlateGray": "778899",+ "lightSlateGrey": "778899", "lightSteelBlue": "B0C4DE",+ "lightYellow": "FFFFE0", "ltBlue": "ADD8E6", "ltCoral": "F08080",+ "ltCyan": "E0FFFF", "ltGoldenrodYellow": "FAFAD2", "ltGray": "D3D3D3",+ "ltGrey": "D3D3D3", "ltGreen": "90EE90", "ltPink": "FFB6C1",+ "ltSalmon": "FFA07A", "ltSeaGreen": "20B2AA", "ltSkyBlue": "87CEFA",+ "ltSlateGray": "778899", "ltSlateGrey": "778899",+ "ltSteelBlue": "B0C4DE", "ltYellow": "FFFFE0",+ "lime": "00FF00", "limeGreen": "32CD32", "linen": "FAF0E6",+ "magenta": "FF00FF", "maroon": "800000", "medAquamarine": "66CDAA",+ "medBlue": "0000CD", "medOrchid": "BA55D3", "medPurple": "9370DB",+ "medSeaGreen": "3CB371", "medSlateBlue": "7B68EE",+ "medSpringGreen": "00FA9A", "medTurquoise": "48D1CC",+ "medVioletRed": "C71585", "mediumAquamarine": "66CDAA",+ "mediumBlue": "0000CD", "mediumOrchid": "BA55D3", "mediumPurple": "9370DB",+ "mediumSeaGreen": "3CB371", "mediumSlateBlue": "7B68EE",+ "mediumSpringGreen": "00FA9A", "mediumTurquoise": "48D1CC",+ "mediumVioletRed": "C71585",+ "midnightBlue": "191970", "mintCream": "F5FFFA", "mistyRose": "FFE4E1",+ "moccasin": "FFE4B5", "navajoWhite": "FFDEAD", "navy": "000080",+ "oldLace": "FDF5E6", "olive": "808000", "oliveDrab": "6B8E23",+ "orange": "FFA500", "orangeRed": "FF4500", "orchid": "DA70D6",+ "paleGoldenrod": "EEE8AA", "paleGreen": "98FB98", "paleTurquoise": "AFEEEE",+ "paleVioletRed": "DB7093", "papayaWhip": "FFEFD5", "peachPuff": "FFDAB9",+ "peru": "CD853F", "pink": "FFC0CB", "plum": "DDA0DD",+ "powderBlue": "B0E0E6", "purple": "800080", "red": "FF0000",+ "rosyBrown": "BC8F8F", "royalBlue": "4169E1", "saddleBrown": "8B4513",+ "salmon": "FA8072", "sandyBrown": "F4A460", "seaGreen": "2E8B57",+ "seaShell": "FFF5EE", "sienna": "A0522D", "silver": "C0C0C0",+ "skyBlue": "87CEEB", "slateBlue": "6A5ACD", "slateGray": "708090",+ "slateGrey": "708090", "snow": "FFFAFA", "springGreen": "00FF7F",+ "steelBlue": "4682B4", "tan": "D2B48C", "teal": "008080",+ "thistle": "D8BFD8", "tomato": "FF6347", "turquoise": "40E0D0",+ "violet": "EE82EE", "wheat": "F5DEB3", "white": "FFFFFF",+ "whiteSmoke": "F5F5F5", "yellow": "FFFF00", "yellowGreen": "9ACD32",+}+++# Scheme color name normalization+SCHEME_ALIASES = {+ "bg1": "lt1", "bg2": "lt2",+ "tx1": "dk1", "tx2": "dk2",+}+++# ---------------------------------------------------------------------------+# ColorPalette+# ---------------------------------------------------------------------------++class ColorPalette:+ """Resolves scheme colors via the master's a:clrMap + theme1's a:clrScheme.++ a:clrMap remaps presentation-level scheme names (bg1/tx1) to theme-level+ names (lt1/dk1) — this is rarely overridden but must be honored.+ """++ def __init__(self, master: PartRef | None, theme: PartRef | None) -> None:+ self.scheme: dict[str, str] = {}+ self.clr_map: dict[str, str] = {}+ if theme is not None:+ self._load_scheme(theme.xml)+ if master is not None:+ self._load_clr_map(master.xml)++ def _load_scheme(self, theme_root: ET.Element) -> None:+ clr_scheme = theme_root.find(".//a:clrScheme", NS)+ if clr_scheme is None:+ return+ for child in list(clr_scheme):+ if not isinstance(child.tag, str):+ continue+ name = child.tag.split("}", 1)[-1]+ srgb = child.find("a:srgbClr", NS)+ sys_clr = child.find("a:sysClr", NS)+ if srgb is not None and srgb.attrib.get("val"):+ self.scheme[name] = srgb.attrib["val"].upper()+ elif sys_clr is not None:+ last = sys_clr.attrib.get("lastClr")+ if last:+ self.scheme[name] = last.upper()++ def _load_clr_map(self, master_root: ET.Element) -> None:+ clr_map = master_root.find("p:clrMap", NS)+ if clr_map is None:+ return+ # Each attribute on clrMap is a remap: bg1="lt1" tx1="dk1" ...+ for attr, val in clr_map.attrib.items():+ self.clr_map[attr] = val++ def resolve_scheme(self, name: str) -> str | None:+ """scheme name (e.g. 'accent1', 'bg1') -> 'RRGGBB'. None on miss."""+ # apply clrMap remap (bg1 -> lt1, tx1 -> dk1, etc.)+ mapped = self.clr_map.get(name, name)+ # canonical alias (bg1 -> lt1)+ mapped = SCHEME_ALIASES.get(mapped, mapped)+ return self.scheme.get(mapped)+++# ---------------------------------------------------------------------------+# Color resolution+# ---------------------------------------------------------------------------++# All concrete color element names under the a: namespace.+COLOR_TAGS = ("srgbClr", "schemeClr", "sysClr", "prstClr",+ "hslClr", "scrgbClr")+++def find_color_elem(parent: ET.Element | None) -> ET.Element | None:+ """Return the first child color element (any of the 6 OOXML color tags)."""+ if parent is None:+ return None+ for tag in COLOR_TAGS:+ elem = parent.find(f"a:{tag}", NS)+ if elem is not None:+ return elem+ return None+++def resolve_color(+ color_elem: ET.Element | None,+ palette: ColorPalette | None,+ *,+ placeholder_hex: str | None = None,+) -> tuple[str | None, float]:+ """Resolve a color element to (#RRGGBB, alpha).++ Args:+ color_elem: a:srgbClr / a:schemeClr / etc. May be None.+ palette: ColorPalette for resolving schemeClr.+ placeholder_hex: when a child uses schemeClr val="phClr" (placeholder+ color used inside theme styles), substitute this hex.++ Returns:+ (hex string with leading '#', alpha in [0,1]) or (None, 1.0) on failure.+ """+ if color_elem is None:+ return None, 1.0++ tag = color_elem.tag.split("}", 1)[-1]+ base_hex: str | None = None+ alpha: float = 1.0++ if tag == "srgbClr":+ val = color_elem.attrib.get("val", "")+ base_hex = _normalize_hex(val)+ elif tag == "schemeClr":+ name = color_elem.attrib.get("val", "")+ if name == "phClr":+ base_hex = _normalize_hex(placeholder_hex) if placeholder_hex else None+ elif palette is not None:+ base_hex = palette.resolve_scheme(name)+ elif tag == "sysClr":+ last = color_elem.attrib.get("lastClr") or color_elem.attrib.get("val")+ base_hex = _normalize_hex(last) if last else None+ elif tag == "prstClr":+ name = color_elem.attrib.get("val", "")+ base_hex = PRST_COLORS.get(name)+ elif tag == "hslClr":+ h = float(color_elem.attrib.get("hue", "0")) / 60000.0 # 1/60000 deg+ s = float(color_elem.attrib.get("sat", "0")) / 100000.0+ lum = float(color_elem.attrib.get("lum", "0")) / 100000.0+ base_hex = _hsl_to_hex(h, s, lum)+ elif tag == "scrgbClr":+ # 0..100000 per channel+ r = float(color_elem.attrib.get("r", "0")) / 100000.0+ g = float(color_elem.attrib.get("g", "0")) / 100000.0+ b = float(color_elem.attrib.get("b", "0")) / 100000.0+ base_hex = _rgb01_to_hex(r, g, b)++ if base_hex is None:+ return None, 1.0++ # Apply modifiers (children of the color element).+ base_hex, alpha = _apply_modifiers(base_hex, color_elem)+ return f"#{base_hex}", alpha+++def _apply_modifiers(hex_color: str, color_elem: ET.Element) -> tuple[str, float]:+ """Apply tint / shade / lumMod / lumOff / satMod / hueMod / alpha modifiers+ in document order. DrawingML stacks these on the color in order.+ """+ r, g, b = _hex_to_rgb01(hex_color)+ # Convert to HSL for luminance/saturation ops; convert back when emitting.+ h, lum, sat = colorsys.rgb_to_hls(r, g, b)+ alpha = 1.0++ for child in list(color_elem):+ if not isinstance(child.tag, str):+ continue+ tag = child.tag.split("}", 1)[-1]+ val_ratio = percent_to_ratio(child.attrib.get("val"), default=0.0)++ if tag == "tint":+ # Tint blends toward white. r' = r + (1-r)*(1-val) is the common+ # interpretation; OOXML actually defines tint on luminance.+ # Use luminance-based tint per ECMA-376.+ lum = lum * val_ratio + (1.0 - val_ratio)+ elif tag == "shade":+ # Shade blends toward black on luminance.+ lum = lum * val_ratio+ elif tag == "lumMod":+ lum = lum * val_ratio+ elif tag == "lumOff":+ lum = lum + val_ratio+ elif tag == "satMod":+ sat = sat * val_ratio+ elif tag == "satOff":+ sat = sat + val_ratio+ elif tag == "hueMod":+ h = (h * val_ratio) % 1.0+ elif tag == "hueOff":+ # hueOff is in 1/60000 deg+ try:+ deg = float(child.attrib.get("val", "0")) / 60000.0+ except ValueError:+ deg = 0.0+ h = (h + deg / 360.0) % 1.0+ elif tag == "alpha":+ alpha = max(0.0, min(1.0, val_ratio))+ elif tag == "alphaMod":+ alpha *= val_ratio+ elif tag == "alphaOff":+ alpha = max(0.0, min(1.0, alpha + val_ratio))+ elif tag == "gray":+ # Convert to grayscale based on luminance.+ sat = 0.0+ elif tag == "comp":+ # Complement: hue rotated 180°+ h = (h + 0.5) % 1.0+ elif tag == "inv":+ # RGB invert+ rr, gg, bb = colorsys.hls_to_rgb(h, lum, sat)+ rr, gg, bb = 1.0 - rr, 1.0 - gg, 1.0 - bb+ h, lum, sat = colorsys.rgb_to_hls(rr, gg, bb)++ # Clamp luminance / saturation to [0,1]+ lum = max(0.0, min(1.0, lum))+ sat = max(0.0, min(1.0, sat))++ rr, gg, bb = colorsys.hls_to_rgb(h, lum, sat)+ return _rgb01_to_hex(rr, gg, bb), alpha+++# ---------------------------------------------------------------------------+# Hex / RGB / HSL helpers+# ---------------------------------------------------------------------------++def _normalize_hex(value: str | None) -> str | None:+ """Strip '#' and validate 6-digit hex. Return uppercase or None on failure."""+ if value is None:+ return None+ v = value.strip()+ if v.startswith("#"):+ v = v[1:]+ if len(v) == 3:+ v = "".join(c * 2 for c in v)+ if len(v) != 6:+ return None+ try:+ int(v, 16)+ except ValueError:+ return None+ return v.upper()+++def _hex_to_rgb01(hex_color: str) -> tuple[float, float, float]:+ h = _normalize_hex(hex_color) or "000000"+ r = int(h[0:2], 16) / 255.0+ g = int(h[2:4], 16) / 255.0+ b = int(h[4:6], 16) / 255.0+ return r, g, b+++def _rgb01_to_hex(r: float, g: float, b: float) -> str:+ r = max(0.0, min(1.0, r))+ g = max(0.0, min(1.0, g))+ b = max(0.0, min(1.0, b))+ return f"{int(round(r * 255)):02X}{int(round(g * 255)):02X}{int(round(b * 255)):02X}"+++def _hsl_to_hex(h: float, s: float, l: float) -> str:+ h = h % 1.0 if h != 1.0 else 1.0+ s = max(0.0, min(1.0, s))+ l = max(0.0, min(1.0, l))+ r, g, b = colorsys.hls_to_rgb(h, l, s)+ return _rgb01_to_hex(r, g, b)diff --git a/skills/ppt-master/scripts/pptx_to_svg/converter.py b/skills/ppt-master/scripts/pptx_to_svg/converter.pynew file mode 100644index 00000000..0dbc9955--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/converter.py@@ -0,0 +1,168 @@+"""Top-level orchestrator for PPTX -> SVG conversion.++Public API: convert_pptx_to_svg(pptx_path, output_dir, options).++Composes the per-slide pipeline:+ OoxmlPackage -> shape_walker.walk_sp_tree+ -> per-shape dispatch (prstgeom / txbody / pic / ...)+ -> assembled SVG text + extracted media files++Stages B-F will fill in the per-shape dispatch. For Stage A this entry just+loads the package and reports basic per-slide structure to verify wiring.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path++from .color_resolver import ColorPalette+from .emu_units import NS+from .ooxml_loader import OoxmlPackage, SlideRef+from .slide_to_svg import assemble_slide+++@dataclass+class ConvertOptions:+ """Convert behavior knobs.++ media_subdir: where to write media files relative to output_dir. SVG image+ href will use './<media_subdir>/<filename>'.+ embed_images: when True, base64-encode images inline instead of writing+ files. Default False (matches svg_to_pptx default of external images).+ keep_hidden: include shapes marked hidden="1". Default False.+ """++ media_subdir: str = "assets"+ embed_images: bool = False+ keep_hidden: bool = False+++@dataclass+class SlideArtifact:+ """Result of converting a single slide."""++ index: int # 1-based+ svg: str+ media_files: dict[str, bytes] = field(default_factory=dict)+++@dataclass+class ConvertResult:+ """Result of converting an entire .pptx."""++ slides: list[SlideArtifact] = field(default_factory=list)+ canvas_px: tuple[float, float] = (1280.0, 720.0)+ theme_colors: dict[str, str] = field(default_factory=dict)+ theme_fonts: dict[str, str] = field(default_factory=dict)+++# ---------------------------------------------------------------------------+# Entry+# ---------------------------------------------------------------------------++def convert_pptx_to_svg(+ pptx_path: Path,+ output_dir: Path | None = None,+ options: ConvertOptions | None = None,+) -> ConvertResult:+ """Convert a .pptx file to one SVG per slide.++ Args:+ pptx_path: Source .pptx file.+ output_dir: When given, write svg/<slide_NN>.svg + media files there.+ When None, files are not written; callers can read SlideArtifact.svg.+ options: ConvertOptions; defaults to ConvertOptions().++ Returns:+ ConvertResult with per-slide SVG strings and resolved theme info.+ """+ options = options or ConvertOptions()+ result = ConvertResult()++ with OoxmlPackage(pptx_path) as pkg:+ result.canvas_px = pkg.slide_size_px++ # Theme + palette built once (multi-master case rarely happens in+ # template decks; if it does we re-resolve per slide).+ first_slide = pkg.get_slide(1)+ master = first_slide.master if first_slide else None+ theme = pkg.resolve_theme(master)+ palette = ColorPalette(master, theme)+ if theme is not None:+ from .color_resolver import find_color_elem, resolve_color+ # Surface theme colors / fonts onto the result (informational only).+ scheme = theme.xml.find(".//a:clrScheme", NS)+ if scheme is not None:+ for child in list(scheme):+ if not isinstance(child.tag, str):+ continue+ name = child.tag.split("}", 1)[-1]+ color_elem = find_color_elem(child)+ hex_, _ = resolve_color(color_elem, palette)+ if hex_:+ result.theme_colors[name] = hex_+ font_scheme = theme.xml.find(".//a:fontScheme", NS)+ if font_scheme is not None:+ for slot in ("majorFont", "minorFont"):+ fnt = font_scheme.find(f"a:{slot}", NS)+ if fnt is None:+ continue+ role_prefix = "major" if slot == "majorFont" else "minor"+ latin = fnt.find("a:latin", NS)+ if latin is not None and latin.attrib.get("typeface"):+ result.theme_fonts[f"{role_prefix}Latin"] = latin.attrib["typeface"]+ ea = fnt.find("a:ea", NS)+ if ea is not None and ea.attrib.get("typeface"):+ result.theme_fonts[f"{role_prefix}EastAsia"] = ea.attrib["typeface"]+ cs = fnt.find("a:cs", NS)+ if cs is not None and cs.attrib.get("typeface"):+ result.theme_fonts[f"{role_prefix}ComplexScript"] = cs.attrib["typeface"]++ # Per-slide conversion+ for slide in pkg.iter_slides():+ artifact = _convert_slide(pkg, slide, palette, options, result.theme_fonts)+ result.slides.append(artifact)++ if output_dir is not None:+ _write_artifacts(output_dir, result, options)++ return result+++def _convert_slide(+ pkg: OoxmlPackage,+ slide: SlideRef,+ palette: ColorPalette,+ options: ConvertOptions,+ theme_fonts: dict[str, str] | None = None,+) -> SlideArtifact:+ """Convert a single slide via the full shape pipeline."""+ svg, media = assemble_slide(+ pkg, slide, palette,+ theme_fonts=theme_fonts,+ media_subdir=options.media_subdir,+ embed_images=options.embed_images,+ keep_hidden=options.keep_hidden,+ )+ return SlideArtifact(index=slide.index, svg=svg, media_files=media)+++def _write_artifacts(output_dir: Path, result: ConvertResult,+ options: ConvertOptions) -> None:+ """Write SVG + media files to output_dir/svg and output_dir/<media_subdir>."""+ output_dir.mkdir(parents=True, exist_ok=True)+ svg_dir = output_dir / "svg"+ svg_dir.mkdir(exist_ok=True)+ media_dir = output_dir / options.media_subdir+ media_written: set[str] = set()++ for art in result.slides:+ target = svg_dir / f"slide_{art.index:02d}.svg"+ target.write_text(art.svg, encoding="utf-8")+ for filename, blob in art.media_files.items():+ if filename in media_written:+ continue+ media_dir.mkdir(parents=True, exist_ok=True)+ (media_dir / filename).write_bytes(blob)+ media_written.add(filename)diff --git a/skills/ppt-master/scripts/pptx_to_svg/custgeom_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/custgeom_to_svg.pynew file mode 100644index 00000000..efc2855f--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/custgeom_to_svg.py@@ -0,0 +1,192 @@+"""DrawingML <a:custGeom> -> SVG <path d="..."> conversion.++Reverse of svg_to_pptx/drawingml_paths.path_commands_to_drawingml.++Path command mapping:+ <a:moveTo> -> M+ <a:lnTo> -> L+ <a:cubicBezTo> -> C+ <a:quadBezTo> -> Q+ <a:arcTo> -> A (DrawingML uses center + sweep angles; we convert+ to SVG endpoint parameterization)+ <a:close/> -> Z++DrawingML <a:path w="..." h="..."> defines a local EMU coordinate system. We+remap path coordinates from path-local to slide-absolute pixels using the+shape's xfrm.+"""++from __future__ import annotations++import math+from xml.etree import ElementTree as ET++from .emu_units import NS, Xfrm, emu_to_px, fmt_num+++def convert_custom_geom(+ cust_geom: ET.Element,+ xfrm: Xfrm,+) -> str | None:+ """Return an SVG path d="..." string in slide-absolute coordinates, or None.+ """+ path_lst = cust_geom.find("a:pathLst", NS)+ if path_lst is None:+ return None++ paths = path_lst.findall("a:path", NS)+ if not paths:+ return None++ d_segments: list[str] = []+ for path_elem in paths:+ d = _convert_one_path(path_elem, xfrm)+ if d:+ d_segments.append(d)++ if not d_segments:+ return None+ return " ".join(d_segments)+++def _convert_one_path(path_elem: ET.Element, xfrm: Xfrm) -> str:+ """Convert a single <a:path> to SVG path commands (slide-absolute coords)."""+ try:+ path_w_emu = int(path_elem.attrib.get("w", "0"))+ path_h_emu = int(path_elem.attrib.get("h", "0"))+ except ValueError:+ return ""+ path_w_px = emu_to_px(path_w_emu) if path_w_emu else xfrm.w+ path_h_px = emu_to_px(path_h_emu) if path_h_emu else xfrm.h+ if path_w_px <= 0 or path_h_px <= 0:+ return ""+ sx = xfrm.w / path_w_px if path_w_px else 1.0+ sy = xfrm.h / path_h_px if path_h_px else 1.0++ def map_pt(x_emu: float, y_emu: float) -> tuple[float, float]:+ x = emu_to_px(x_emu) * sx + xfrm.x+ y = emu_to_px(y_emu) * sy + xfrm.y+ return x, y++ # Track current point so a:arcTo (center-based) can compute its endpoint+ cx, cy = 0.0, 0.0 # slide-absolute pixels++ parts: list[str] = []+ for child in list(path_elem):+ if not isinstance(child.tag, str):+ continue+ local = child.tag.split("}", 1)[-1]+ if local == "moveTo":+ pt = child.find("a:pt", NS)+ if pt is None:+ continue+ x, y = _read_pt(pt, map_pt)+ parts.append(f"M {fmt_num(x)} {fmt_num(y)}")+ cx, cy = x, y+ elif local == "lnTo":+ pt = child.find("a:pt", NS)+ if pt is None:+ continue+ x, y = _read_pt(pt, map_pt)+ parts.append(f"L {fmt_num(x)} {fmt_num(y)}")+ cx, cy = x, y+ elif local == "cubicBezTo":+ pts = child.findall("a:pt", NS)+ if len(pts) < 3:+ continue+ p1 = _read_pt(pts[0], map_pt)+ p2 = _read_pt(pts[1], map_pt)+ p3 = _read_pt(pts[2], map_pt)+ parts.append(+ f"C {fmt_num(p1[0])} {fmt_num(p1[1])} "+ f"{fmt_num(p2[0])} {fmt_num(p2[1])} "+ f"{fmt_num(p3[0])} {fmt_num(p3[1])}"+ )+ cx, cy = p3+ elif local == "quadBezTo":+ pts = child.findall("a:pt", NS)+ if len(pts) < 2:+ continue+ p1 = _read_pt(pts[0], map_pt)+ p2 = _read_pt(pts[1], map_pt)+ parts.append(+ f"Q {fmt_num(p1[0])} {fmt_num(p1[1])} "+ f"{fmt_num(p2[0])} {fmt_num(p2[1])}"+ )+ cx, cy = p2+ elif local == "arcTo":+ arc_d, end_x, end_y = _arc_to_svg(child, cx, cy, sx, sy)+ if arc_d:+ parts.append(arc_d)+ cx, cy = end_x, end_y+ elif local == "close":+ parts.append("Z")+ # SVG semantics: Z returns to subpath start; we don't track that+ # explicitly here. cx/cy stays as-is — subsequent moveTo will reset.++ return " ".join(parts)+++def _read_pt(pt_elem: ET.Element, mapper) -> tuple[float, float]:+ try:+ x = float(pt_elem.attrib.get("x", "0"))+ y = float(pt_elem.attrib.get("y", "0"))+ except ValueError:+ x = 0.0+ y = 0.0+ return mapper(x, y)+++def _arc_to_svg(+ arc_elem: ET.Element,+ cx: float, cy: float,+ sx: float, sy: float,+) -> tuple[str, float, float]:+ """Convert <a:arcTo wR hR stAng swAng/> to an SVG A command.++ DrawingML semantics: starting at the current point, draw an elliptical arc+ where the ellipse has radii (wR, hR) in path-local EMU. stAng/swAng are+ 1/60000 degrees, with 0° = +x axis, increasing clockwise.++ The center of the ellipse is at:+ center.x = cur.x - wR * cos(stAng)+ center.y = cur.y - hR * sin(stAng)+ The end point is on the same ellipse at angle (stAng + swAng).++ We emit a single SVG A command. SVG's sweep_flag = 1 means clockwise; the+ DrawingML convention is also clockwise so we pass sweep_flag = 1 when+ swAng > 0.+ """+ try:+ wR_emu = float(arc_elem.attrib.get("wR", "0"))+ hR_emu = float(arc_elem.attrib.get("hR", "0"))+ st_ang = float(arc_elem.attrib.get("stAng", "0"))+ sw_ang = float(arc_elem.attrib.get("swAng", "0"))+ except ValueError:+ return "", cx, cy++ if wR_emu <= 0 or hR_emu <= 0:+ return "", cx, cy++ rx = emu_to_px(wR_emu) * sx+ ry = emu_to_px(hR_emu) * sy+ st_rad = math.radians(st_ang / 60000.0)+ sw_rad = math.radians(sw_ang / 60000.0)+ end_rad = st_rad + sw_rad++ # Center of the ellipse in slide-absolute coords+ arc_cx = cx - rx * math.cos(st_rad)+ arc_cy = cy - ry * math.sin(st_rad)+ end_x = arc_cx + rx * math.cos(end_rad)+ end_y = arc_cy + ry * math.sin(end_rad)++ abs_sw = abs(sw_ang) / 60000.0+ large_arc = 1 if abs_sw > 180.0 else 0+ sweep = 1 if sw_ang >= 0 else 0++ return (+ f"A {fmt_num(rx)} {fmt_num(ry)} 0 {large_arc} {sweep} "+ f"{fmt_num(end_x)} {fmt_num(end_y)}",+ end_x,+ end_y,+ )diff --git a/skills/ppt-master/scripts/pptx_to_svg/effect_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/effect_to_svg.pynew file mode 100644index 00000000..79c7ac50--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/effect_to_svg.py@@ -0,0 +1,210 @@+"""DrawingML <a:effectLst> -> SVG <filter> conversion.++Reverse of svg_to_pptx/drawingml_styles.build_effect_xml.++Covers the most common DrawingML effects:+- <a:outerShdw> -> feDropShadow (or feGaussianBlur+feOffset+feFlood)+- <a:innerShdw> -> approximated via inverted SourceAlpha pipeline+- <a:glow> -> outer glow (no offset, uses flood color)+- <a:blur> -> feGaussianBlur on whole shape+- <a:softEdge> -> feGaussianBlur (approximation; SVG has no direct match)++Output: each call returns (filter_id, defs_xml). Caller adds filter="url(#id)"+to the shape and accumulates defs_xml into the slide's <defs>.+"""++from __future__ import annotations++import math+from xml.etree import ElementTree as ET++from .color_resolver import ColorPalette, find_color_elem, resolve_color+from .emu_units import NS, emu_to_px, fmt_num+++def convert_effects(+ sp_pr: ET.Element | None,+ palette: ColorPalette | None,+ *,+ id_prefix: str = "fx",+ id_seq: list[int] | None = None,+) -> tuple[str | None, list[str]]:+ """Inspect <p:spPr> for <a:effectLst> and return (filter_id, defs_xml).++ If no effect is present returns (None, []). Multiple effects are layered+ inside one <filter> using SVG primitive results.+ """+ if sp_pr is None:+ return None, []+ effect_lst = sp_pr.find("a:effectLst", NS)+ if effect_lst is None:+ return None, []+ if len(list(effect_lst)) == 0:+ return None, []++ if id_seq is None:+ id_seq = [0]+ id_seq[0] += 1+ filter_id = f"{id_prefix}{id_seq[0]}"++ primitives: list[str] = []+ last_result = "SourceGraphic"+ # Filter region needs to extend beyond the bounding box to render shadows+ # and glows; choose generous defaults.+ filter_x = "-25%"+ filter_y = "-25%"+ filter_w = "150%"+ filter_h = "150%"++ for child in list(effect_lst):+ if not isinstance(child.tag, str):+ continue+ local = child.tag.split("}", 1)[-1]+ prim, last_result = _convert_one_effect(child, last_result, palette)+ if prim:+ primitives.append(prim)++ if not primitives:+ return None, []++ defs_xml = (+ f'<filter id="{filter_id}" x="{filter_x}" y="{filter_y}" '+ f'width="{filter_w}" height="{filter_h}">'+ + "".join(primitives)+ + "</filter>"+ )+ return filter_id, [defs_xml]+++# ---------------------------------------------------------------------------+# Per-effect conversion+# ---------------------------------------------------------------------------++def _convert_one_effect(+ elem: ET.Element,+ last_result: str,+ palette: ColorPalette | None,+) -> tuple[str, str]:+ """Convert one effect to SVG filter primitives.++ Returns (primitives_xml, new_last_result_name).+ """+ local = elem.tag.split("}", 1)[-1]+ if local == "outerShdw":+ return _outer_shadow(elem, last_result, palette)+ if local == "innerShdw":+ return _inner_shadow(elem, last_result, palette)+ if local == "glow":+ return _glow(elem, last_result, palette)+ if local == "blur":+ return _blur(elem, last_result)+ if local == "softEdge":+ return _soft_edge(elem, last_result)+ if local == "reflection":+ # v1 approximation: skip (would require feImage + feFlood + transform)+ return "", last_result+ return "", last_result+++def _color_alpha(elem: ET.Element, palette: ColorPalette | None) -> tuple[str, float]:+ color = find_color_elem(elem)+ hex_, alpha = resolve_color(color, palette)+ return hex_ or "#000000", alpha+++def _direction_offset(elem: ET.Element) -> tuple[float, float]:+ """Read dir / dist into (dx, dy) px."""+ try:+ direction_units = float(elem.attrib.get("dir", "0"))+ dist_emu = float(elem.attrib.get("dist", "0"))+ except ValueError:+ return 0.0, 0.0+ direction_deg = direction_units / 60000.0+ dist_px = emu_to_px(dist_emu)+ rad = math.radians(direction_deg)+ return dist_px * math.cos(rad), dist_px * math.sin(rad)+++def _blur_radius(elem: ET.Element, attr: str = "blurRad", default_emu: float = 0.0) -> float:+ try:+ v = float(elem.attrib.get(attr, str(default_emu)))+ except ValueError:+ return 0.0+ return emu_to_px(v)+++def _outer_shadow(elem: ET.Element, last_result: str,+ palette: ColorPalette | None) -> tuple[str, str]:+ dx, dy = _direction_offset(elem)+ blur = _blur_radius(elem, "blurRad")+ color, alpha = _color_alpha(elem, palette)+ # std deviation ~= blur radius / 2 (rough; PowerPoint shadows are larger)+ std = max(blur / 2.0, 0.1)+ # Use feDropShadow for compactness — it's well-supported in modern browsers.+ return (+ f'<feDropShadow dx="{fmt_num(dx)}" dy="{fmt_num(dy)}" '+ f'stdDeviation="{fmt_num(std)}" '+ f'flood-color="{color}" flood-opacity="{fmt_num(alpha, 4)}"/>',+ "shadow",+ )+++def _inner_shadow(elem: ET.Element, last_result: str,+ palette: ColorPalette | None) -> tuple[str, str]:+ """Inner shadow via inverted alpha + offset + blur + composite-in.++ Approximation: produces a darkened inner edge similar to PowerPoint.+ """+ dx, dy = _direction_offset(elem)+ blur = _blur_radius(elem, "blurRad")+ color, alpha = _color_alpha(elem, palette)+ std = max(blur / 2.0, 0.1)+ # Pipeline:+ # feFlood (color) -> compose with inverted alpha -> blur -> offset ->+ # composite-in original alpha+ return (+ f'<feFlood flood-color="{color}" flood-opacity="{fmt_num(alpha, 4)}" result="flood"/>'+ f'<feComposite in="flood" in2="SourceAlpha" operator="out" result="inverted"/>'+ f'<feGaussianBlur in="inverted" stdDeviation="{fmt_num(std)}" result="blurred"/>'+ f'<feOffset in="blurred" dx="{fmt_num(dx)}" dy="{fmt_num(dy)}" result="offset"/>'+ f'<feComposite in="offset" in2="SourceAlpha" operator="in" result="innerShadow"/>'+ f'<feMerge><feMergeNode in="SourceGraphic"/><feMergeNode in="innerShadow"/></feMerge>',+ "innerShadow",+ )+++def _glow(elem: ET.Element, last_result: str,+ palette: ColorPalette | None) -> tuple[str, str]:+ rad = _blur_radius(elem, "rad")+ color, alpha = _color_alpha(elem, palette)+ std = max(rad / 2.0, 0.1)+ return (+ f'<feMorphology operator="dilate" radius="{fmt_num(rad / 4.0)}" '+ f'in="SourceAlpha" result="dilated"/>'+ f'<feGaussianBlur in="dilated" stdDeviation="{fmt_num(std)}" result="blurred"/>'+ f'<feFlood flood-color="{color}" flood-opacity="{fmt_num(alpha, 4)}" result="flood"/>'+ f'<feComposite in="flood" in2="blurred" operator="in" result="glow"/>'+ f'<feMerge><feMergeNode in="glow"/><feMergeNode in="SourceGraphic"/></feMerge>',+ "glow",+ )+++def _blur(elem: ET.Element, last_result: str) -> tuple[str, str]:+ rad = _blur_radius(elem, "rad")+ std = max(rad / 2.0, 0.1)+ return (+ f'<feGaussianBlur stdDeviation="{fmt_num(std)}"/>',+ "blurred",+ )+++def _soft_edge(elem: ET.Element, last_result: str) -> tuple[str, str]:+ # softEdge fades the edges; approximate with an alpha-only Gaussian blur+ # then composite-in. v1 just outputs a gentle blur.+ rad = _blur_radius(elem, "rad")+ std = max(rad / 4.0, 0.1)+ return (+ f'<feGaussianBlur in="SourceAlpha" stdDeviation="{fmt_num(std)}" result="softEdge"/>'+ f'<feComposite in="SourceGraphic" in2="softEdge" operator="in"/>',+ "softEdge",+ )diff --git a/skills/ppt-master/scripts/pptx_to_svg/emu_units.py b/skills/ppt-master/scripts/pptx_to_svg/emu_units.pynew file mode 100644index 00000000..155a2060--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/emu_units.py@@ -0,0 +1,223 @@+"""EMU <-> pixel conversion and DrawingML unit constants.++Mirrors svg_to_pptx/drawingml_utils.py and pptx_dimensions.py, in reverse.++DrawingML unit conventions:+- Coordinates / sizes: EMU (English Metric Unit). 914400 EMU = 1 inch = 96 px.+- Font size: hundredths of a point. 1 px = 0.75 pt = 75 hundredths-of-a-point.+- Angle: 60000ths of a degree.+- Color tint/shade/lumMod/lumOff/satMod: percent in 1000ths (100% = 100000).+- srcRect / fillRect: percent in 1000ths of the unit rect.+"""++from __future__ import annotations++from xml.etree import ElementTree as ET++EMU_PER_INCH = 914400+EMU_PER_PX = 9525 # 96 dpi+HUNDREDTHS_PT_PER_PX = 75 # 1 px = 0.75 pt = 75 hundredths+ANGLE_UNIT = 60000 # 1 degree = 60000 angle units+PERCENT_UNIT = 100000 # 100% = 100000 (DrawingML "ST_PositivePercentage")+SRCRECT_UNIT = 100000 # srcRect l/t/r/b are in 1000ths of percent (i.e. 100000 = 100%)+++# Namespaces used throughout OOXML+NS = {+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",+ "rel": "http://schemas.openxmlformats.org/package/2006/relationships",+ "ct": "http://schemas.openxmlformats.org/package/2006/content-types",+ "asvg": "http://schemas.microsoft.com/office/drawing/2016/SVG/main",+ "mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",+}++# Register so ET output emits clean prefixes (writers normally don't need this+# since the SVG output uses the SVG namespace, but keep it consistent).+for prefix, uri in NS.items():+ try:+ ET.register_namespace(prefix, uri)+ except (ValueError, AttributeError):+ pass+++# ---------------------------------------------------------------------------+# Length conversions+# ---------------------------------------------------------------------------++def emu_to_px(emu: float | int | None, default: float = 0.0) -> float:+ """Convert EMU to SVG px (96 dpi). None / unparsable -> default."""+ if emu is None:+ return default+ try:+ return float(emu) / EMU_PER_PX+ except (ValueError, TypeError):+ return default+++def emu_attr_to_px(elem: ET.Element | None, attr: str, default: float = 0.0) -> float:+ """Read EMU integer attribute and return px."""+ if elem is None:+ return default+ return emu_to_px(elem.get(attr), default)+++def hundredths_pt_to_px(val: float | int | str | None, default: float = 0.0) -> float:+ """Convert font size (a:rPr@sz) to px. 100 = 1 pt = 4/3 px."""+ if val is None:+ return default+ try:+ return float(val) / HUNDREDTHS_PT_PER_PX+ except (ValueError, TypeError):+ return default+++def angle_to_deg(val: float | int | str | None, default: float = 0.0) -> float:+ """Convert DrawingML angle (1/60000 deg) to plain degrees."""+ if val is None:+ return default+ try:+ return float(val) / ANGLE_UNIT+ except (ValueError, TypeError):+ return default+++def percent_to_ratio(val: float | int | str | None, default: float = 0.0) -> float:+ """DrawingML positive percent (100000 = 100%) -> ratio in [0, 1]."""+ if val is None:+ return default+ try:+ return float(val) / PERCENT_UNIT+ except (ValueError, TypeError):+ return default+++# ---------------------------------------------------------------------------+# xfrm / transform parsing+# ---------------------------------------------------------------------------++class Xfrm:+ """Resolved <a:xfrm> in pixel space.++ Attributes:+ x, y: top-left position (px).+ w, h: size (px).+ rot: rotation in degrees, clockwise around the shape center.+ flip_h: bool — horizontal flip.+ flip_v: bool — vertical flip.+ ch_x, ch_y, ch_w, ch_h: only set when this is a group <p:grpSpPr>'s+ xfrm; describes the child coordinate frame (a:chOff / a:chExt).+ None on leaf shapes.+ """++ __slots__ = ("x", "y", "w", "h", "rot", "flip_h", "flip_v",+ "ch_x", "ch_y", "ch_w", "ch_h")++ def __init__(+ self,+ x: float = 0.0,+ y: float = 0.0,+ w: float = 0.0,+ h: float = 0.0,+ rot: float = 0.0,+ flip_h: bool = False,+ flip_v: bool = False,+ ch_x: float | None = None,+ ch_y: float | None = None,+ ch_w: float | None = None,+ ch_h: float | None = None,+ ) -> None:+ self.x = x+ self.y = y+ self.w = w+ self.h = h+ self.rot = rot+ self.flip_h = flip_h+ self.flip_v = flip_v+ self.ch_x = ch_x+ self.ch_y = ch_y+ self.ch_w = ch_w+ self.ch_h = ch_h++ def __repr__(self) -> str:+ parts = [f"x={self.x:.1f}", f"y={self.y:.1f}",+ f"w={self.w:.1f}", f"h={self.h:.1f}"]+ if self.rot:+ parts.append(f"rot={self.rot:.2f}")+ if self.flip_h:+ parts.append("flipH")+ if self.flip_v:+ parts.append("flipV")+ return f"Xfrm({', '.join(parts)})"++ def to_svg_transform(self) -> str | None:+ """Build SVG transform attribute for rotation / flip around the center.++ Returns None if no rotation / flip is needed.+ """+ if not self.rot and not self.flip_h and not self.flip_v:+ return None+ cx = self.x + self.w / 2.0+ cy = self.y + self.h / 2.0+ parts: list[str] = []+ if self.rot:+ parts.append(f"rotate({_fmt(self.rot)} {_fmt(cx)} {_fmt(cy)})")+ if self.flip_h or self.flip_v:+ sx = -1 if self.flip_h else 1+ sy = -1 if self.flip_v else 1+ # scale around shape center+ parts.append(f"translate({_fmt(cx)} {_fmt(cy)})")+ parts.append(f"scale({sx} {sy})")+ parts.append(f"translate({_fmt(-cx)} {_fmt(-cy)})")+ return " ".join(parts) if parts else None+++def parse_xfrm(xfrm_elem: ET.Element | None) -> Xfrm:+ """Parse <a:xfrm> into an Xfrm object. None -> zero Xfrm."""+ if xfrm_elem is None:+ return Xfrm()++ rot = angle_to_deg(xfrm_elem.get("rot"))+ flip_h = xfrm_elem.get("flipH") == "1"+ flip_v = xfrm_elem.get("flipV") == "1"++ off = xfrm_elem.find("a:off", NS)+ ext = xfrm_elem.find("a:ext", NS)+ ch_off = xfrm_elem.find("a:chOff", NS)+ ch_ext = xfrm_elem.find("a:chExt", NS)++ x = emu_attr_to_px(off, "x")+ y = emu_attr_to_px(off, "y")+ w = emu_attr_to_px(ext, "cx")+ h = emu_attr_to_px(ext, "cy")++ ch_x = emu_attr_to_px(ch_off, "x") if ch_off is not None else None+ ch_y = emu_attr_to_px(ch_off, "y") if ch_off is not None else None+ ch_w = emu_attr_to_px(ch_ext, "cx") if ch_ext is not None else None+ ch_h = emu_attr_to_px(ch_ext, "cy") if ch_ext is not None else None++ return Xfrm(x=x, y=y, w=w, h=h, rot=rot,+ flip_h=flip_h, flip_v=flip_v,+ ch_x=ch_x, ch_y=ch_y, ch_w=ch_w, ch_h=ch_h)+++# ---------------------------------------------------------------------------+# Number formatting for SVG output+# ---------------------------------------------------------------------------++def _fmt(val: float, ndigits: int = 2) -> str:+ """Format a number for SVG attributes: trim trailing zeros, keep ints clean."""+ if val == 0:+ return "0"+ rounded = round(val, ndigits)+ if rounded == int(rounded):+ return str(int(rounded))+ s = f"{rounded:.{ndigits}f}"+ # trim trailing zeros after decimal+ if "." in s:+ s = s.rstrip("0").rstrip(".")+ return s+++fmt_num = _fmtdiff --git a/skills/ppt-master/scripts/pptx_to_svg/fill_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/fill_to_svg.pynew file mode 100644index 00000000..0890c5aa--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/fill_to_svg.py@@ -0,0 +1,213 @@+"""DrawingML fill -> SVG fill conversion.++Handles:+- <a:solidFill> -> fill="#XXXXXX" (+ fill-opacity)+- <a:noFill/> -> fill="none"+- <a:gradFill> -> linearGradient/radialGradient in <defs>, fill="url(#id)"+- <a:blipFill> -> handled by pic_to_svg (this module short-circuits)++Returned FillResult is a struct of attribute dict + optional <defs> XML so the+slide assembler can collect gradient defs without conflicting IDs.+"""++from __future__ import annotations++import math+from dataclasses import dataclass, field+from xml.etree import ElementTree as ET++from .color_resolver import ColorPalette, find_color_elem, resolve_color+from .emu_units import NS, fmt_num, percent_to_ratio+++@dataclass+class FillResult:+ """Resolved fill: SVG attributes to apply + optional <defs> entries."""++ attrs: dict[str, str] = field(default_factory=dict)+ defs: list[str] = field(default_factory=list) # XML strings of <linearGradient>/<radialGradient>++ @classmethod+ def none_fill(cls) -> "FillResult":+ return cls(attrs={"fill": "none"})++ @classmethod+ def inherit(cls) -> "FillResult":+ # No fill resolved — let caller decide whether to default+ return cls()+++def resolve_fill(+ sp_pr: ET.Element | None,+ palette: ColorPalette | None,+ *,+ id_prefix: str = "g",+ id_seq: list[int] | None = None,+) -> FillResult:+ """Inspect <p:spPr>'s fill children and emit an SVG fill descriptor.++ Args:+ sp_pr: <p:spPr> or any element that may directly hold a fill child.+ palette: ColorPalette for scheme color resolution.+ id_prefix: prefix for generated gradient IDs.+ id_seq: external counter (single-element list) so callers can share+ unique gradient IDs across the whole slide.++ Returns:+ FillResult. If no recognized fill is found, result.attrs is empty —+ the caller should apply its own default (typically transparent /+ inherit from the source SVG).+ """+ if sp_pr is None:+ return FillResult.inherit()++ # Direct child fill (in priority order: explicit -> derived).+ for tag, handler in (+ ("noFill", _resolve_no_fill),+ ("solidFill", _resolve_solid_fill),+ ("gradFill", _resolve_grad_fill),+ ("blipFill", _resolve_blip_fill),+ ("pattFill", _resolve_patt_fill),+ ):+ elem = sp_pr.find(f"a:{tag}", NS)+ if elem is not None:+ return handler(elem, palette, id_prefix, id_seq)++ return FillResult.inherit()+++# ---------------------------------------------------------------------------+# Per-fill handlers+# ---------------------------------------------------------------------------++def _resolve_no_fill(_elem, _palette, _prefix, _seq) -> FillResult:+ return FillResult.none_fill()+++def _resolve_solid_fill(elem: ET.Element, palette: ColorPalette | None,+ _prefix: str, _seq) -> FillResult:+ color_elem = find_color_elem(elem)+ hex_, alpha = resolve_color(color_elem, palette)+ if hex_ is None:+ return FillResult.inherit()+ attrs: dict[str, str] = {"fill": hex_}+ if alpha < 1.0:+ attrs["fill-opacity"] = fmt_num(alpha, 4)+ return FillResult(attrs=attrs)+++def _resolve_grad_fill(elem: ET.Element, palette: ColorPalette | None,+ prefix: str, seq) -> FillResult:+ """Convert <a:gradFill> to an SVG linearGradient or radialGradient."""+ if seq is None:+ seq = [0]+ seq[0] += 1+ grad_id = f"{prefix}grad{seq[0]}"++ # Stops+ gs_lst = elem.find("a:gsLst", NS)+ if gs_lst is None:+ return FillResult.inherit()+ stops_xml = []+ for gs in gs_lst.findall("a:gs", NS):+ pos_pct = percent_to_ratio(gs.attrib.get("pos"), default=0.0)+ color_elem = find_color_elem(gs)+ hex_, alpha = resolve_color(color_elem, palette)+ if hex_ is None:+ continue+ opacity_attr = f' stop-opacity="{fmt_num(alpha, 4)}"' if alpha < 1.0 else ""+ stops_xml.append(+ f'<stop offset="{fmt_num(pos_pct, 4)}" stop-color="{hex_}"{opacity_attr}/>'+ )+ if not stops_xml:+ return FillResult.inherit()++ # Linear vs radial vs path+ lin = elem.find("a:lin", NS)+ rad = elem.find("a:path", NS)++ if lin is not None:+ # ang is 1/60000 deg. 0° = horizontal left-to-right.+ try:+ angle_deg = float(lin.attrib.get("ang", "0")) / 60000.0+ except ValueError:+ angle_deg = 0.0+ x1, y1, x2, y2 = _angle_to_unit_endpoints(angle_deg)+ defs_xml = (+ f'<linearGradient id="{grad_id}" '+ f'x1="{fmt_num(x1, 4)}" y1="{fmt_num(y1, 4)}" '+ f'x2="{fmt_num(x2, 4)}" y2="{fmt_num(y2, 4)}">'+ + "".join(stops_xml)+ + "</linearGradient>"+ )+ elif rad is not None:+ # Treat as radial regardless of path="circle" / "rect" / "shape" — SVG+ # only has circle/ellipse, and path="circle" maps to fillToRect=center.+ defs_xml = (+ f'<radialGradient id="{grad_id}" cx="0.5" cy="0.5" r="0.5">'+ + "".join(stops_xml)+ + "</radialGradient>"+ )+ else:+ # No direction specified — default to horizontal linear+ defs_xml = (+ f'<linearGradient id="{grad_id}" x1="0" y1="0" x2="1" y2="0">'+ + "".join(stops_xml)+ + "</linearGradient>"+ )++ return FillResult(+ attrs={"fill": f"url(#{grad_id})"},+ defs=[defs_xml],+ )+++def _resolve_blip_fill(_elem, _palette, _prefix, _seq) -> FillResult:+ """blipFill on <p:spPr> means a shape filled with an image — handled at+ pic_to_svg level. For now mark as transparent so the shape's outline+ still draws and pic_to_svg can layer the image on top.+ """+ return FillResult.none_fill()+++def _resolve_patt_fill(elem: ET.Element, palette: ColorPalette | None,+ _prefix, _seq) -> FillResult:+ """Pattern fills (<a:pattFill prst="..."/> with fg/bg colors). Approximate+ with the foreground color so the shape isn't transparent. Future work:+ emit a real <pattern> in defs.+ """+ fg = elem.find("a:fgClr", NS)+ color_elem = find_color_elem(fg)+ hex_, alpha = resolve_color(color_elem, palette)+ if hex_ is None:+ return FillResult.inherit()+ attrs: dict[str, str] = {"fill": hex_}+ if alpha < 1.0:+ attrs["fill-opacity"] = fmt_num(alpha, 4)+ return FillResult(attrs=attrs)+++# ---------------------------------------------------------------------------+# Geometry helpers+# ---------------------------------------------------------------------------++def _angle_to_unit_endpoints(angle_deg: float) -> tuple[float, float, float, float]:+ """Convert a DrawingML linear gradient angle to SVG x1/y1/x2/y2 in unit box.++ DrawingML 0° = horizontal pointing right; angle is clockwise.+ SVG default linearGradient is also unit-box (objectBoundingBox).+ """+ rad = math.radians(angle_deg % 360)+ cos_a = math.cos(rad)+ sin_a = math.sin(rad)+ # Center of unit box+ cx, cy = 0.5, 0.5+ # Half-extent in the direction of the angle vector.+ # We project the unit box onto the angle direction; the line endpoints are+ # the projections of the box corners.+ half = abs(cos_a) * 0.5 + abs(sin_a) * 0.5+ x1 = cx - cos_a * half+ y1 = cy - sin_a * half+ x2 = cx + cos_a * half+ y2 = cy + sin_a * half+ return x1, y1, x2, y2diff --git a/skills/ppt-master/scripts/pptx_to_svg/ln_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/ln_to_svg.pynew file mode 100644index 00000000..a5e288b1--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/ln_to_svg.py@@ -0,0 +1,230 @@+"""DrawingML <a:ln> -> SVG stroke conversion.++Reverse of svg_to_pptx/drawingml_styles.build_stroke_xml.++Produces an SVG attribute dict with stroke / stroke-width / stroke-opacity /+stroke-dasharray / stroke-linecap / stroke-linejoin / marker-start /+marker-end (markers also need a <defs> entry which is returned alongside).+"""++from __future__ import annotations++from dataclasses import dataclass, field+from xml.etree import ElementTree as ET++from .color_resolver import ColorPalette, find_color_elem, resolve_color+from .emu_units import NS, emu_to_px, fmt_num+++@dataclass+class StrokeResult:+ """Resolved stroke: SVG attributes to apply + optional <defs> for markers."""++ attrs: dict[str, str] = field(default_factory=dict)+ defs: list[str] = field(default_factory=list)+++# Reverse of svg_to_pptx DASH_PRESETS (preset name -> dasharray).+PRST_DASH_TO_ARRAY = {+ "solid": None, # no dasharray+ "dot": "1 3",+ "dash": "4 4",+ "lgDash": "8 4",+ "dashDot": "4 4 1 4",+ "lgDashDot": "8 4 2 4",+ "lgDashDotDot": "8 4 2 4 2 4",+ "sysDash": "3 3",+ "sysDot": "1 3",+ "sysDashDot": "3 3 1 3",+ "sysDashDotDot": "3 3 1 3 1 3",+}++# DrawingML cap -> SVG stroke-linecap+CAP_MAP = {+ "rnd": "round",+ "sq": "square",+ "flat": "butt",+}+++def resolve_stroke(+ sp_pr: ET.Element | None,+ palette: ColorPalette | None,+ *,+ id_prefix: str = "m",+ id_seq: list[int] | None = None,+) -> StrokeResult:+ """Resolve <a:ln> child of <p:spPr>.++ Returns:+ StrokeResult.attrs is empty if no <a:ln> present (caller falls back to+ the spec default). If <a:ln> exists with <a:noFill/>, attrs has+ stroke="none".+ """+ if sp_pr is None:+ return StrokeResult()++ ln = sp_pr.find("a:ln", NS)+ if ln is None:+ return StrokeResult()++ attrs: dict[str, str] = {}+ defs: list[str] = []++ # Width (a:ln@w in EMU)+ width_emu = ln.attrib.get("w")+ if width_emu is not None:+ try:+ width_px = emu_to_px(int(width_emu))+ attrs["stroke-width"] = fmt_num(width_px, 3)+ except (ValueError, TypeError):+ pass++ # Cap+ cap = ln.attrib.get("cap")+ if cap and cap in CAP_MAP:+ attrs["stroke-linecap"] = CAP_MAP[cap]++ # Fill: noFill / solidFill / gradFill+ no_fill = ln.find("a:noFill", NS)+ if no_fill is not None:+ attrs["stroke"] = "none"+ else:+ solid = ln.find("a:solidFill", NS)+ if solid is not None:+ color_elem = find_color_elem(solid)+ hex_, alpha = resolve_color(color_elem, palette)+ if hex_:+ attrs["stroke"] = hex_+ if alpha < 1.0:+ attrs["stroke-opacity"] = fmt_num(alpha, 4)+ else:+ grad = ln.find("a:gradFill", NS)+ if grad is not None:+ # Approximate gradient stroke as the first stop color (SVG+ # supports gradient strokes via fill="url()" but it adds a lot+ # of plumbing; first-stop is good enough for v1).+ first_gs = grad.find("a:gsLst/a:gs", NS)+ if first_gs is not None:+ color_elem = find_color_elem(first_gs)+ hex_, alpha = resolve_color(color_elem, palette)+ if hex_:+ attrs["stroke"] = hex_+ if alpha < 1.0:+ attrs["stroke-opacity"] = fmt_num(alpha, 4)++ # Dash pattern+ prst_dash = ln.find("a:prstDash", NS)+ if prst_dash is not None:+ preset = prst_dash.attrib.get("val", "")+ dasharray = PRST_DASH_TO_ARRAY.get(preset)+ if dasharray:+ attrs["stroke-dasharray"] = dasharray+ else:+ cust_dash = ln.find("a:custDash", NS)+ if cust_dash is not None:+ ds_parts: list[str] = []+ sw = float(attrs.get("stroke-width", "1") or "1") or 1.0+ for ds in cust_dash.findall("a:ds", NS):+ # d, sp are percentages of stroke width (1000ths)+ try:+ d_pct = int(ds.attrib.get("d", "0"))+ sp_pct = int(ds.attrib.get("sp", "0"))+ except ValueError:+ continue+ ds_parts.append(fmt_num(d_pct / 100000.0 * sw, 2))+ ds_parts.append(fmt_num(sp_pct / 100000.0 * sw, 2))+ if ds_parts:+ attrs["stroke-dasharray"] = " ".join(ds_parts)++ # Join+ if ln.find("a:round", NS) is not None:+ attrs["stroke-linejoin"] = "round"+ elif ln.find("a:bevel", NS) is not None:+ attrs["stroke-linejoin"] = "bevel"+ elif ln.find("a:miter", NS) is not None:+ attrs["stroke-linejoin"] = "miter"++ # Arrow markers (head / tail)+ if id_seq is None:+ id_seq = [0]+ for which, attr in (("headEnd", "marker-start"), ("tailEnd", "marker-end")):+ end_elem = ln.find(f"a:{which}", NS)+ if end_elem is None:+ continue+ marker_id, marker_def = _build_arrow_marker(+ end_elem,+ attrs.get("stroke", "#000000"),+ id_prefix=id_prefix,+ seq=id_seq,+ reversed_=(which == "headEnd"),+ )+ if marker_id is None:+ continue+ defs.append(marker_def)+ attrs[attr] = f"url(#{marker_id})"++ return StrokeResult(attrs=attrs, defs=defs)+++# ---------------------------------------------------------------------------+# Arrow marker generation+# ---------------------------------------------------------------------------++# Bucket -> markerWidth/markerHeight ratio (in stroke widths)+SIZE_BUCKET = {"sm": 1.5, "med": 2.5, "lg": 3.5}+++def _build_arrow_marker(+ end_elem: ET.Element,+ stroke_color: str,+ *,+ id_prefix: str,+ seq: list[int],+ reversed_: bool,+) -> tuple[str | None, str]:+ """Build an SVG <marker> def for an <a:headEnd>/<a:tailEnd>."""+ typ = end_elem.attrib.get("type", "")+ if typ in ("none", ""):+ return None, ""++ w_b = end_elem.attrib.get("w", "med")+ l_b = end_elem.attrib.get("len", "med")+ mw = SIZE_BUCKET.get(l_b, 2.5)+ mh = SIZE_BUCKET.get(w_b, 2.5)++ seq[0] += 1+ marker_id = f"{id_prefix}arrow{seq[0]}"++ # SVG markers are drawn in their own viewBox; we use a 0..10 box and place+ # the path so refX is at the line endpoint.+ if typ == "triangle":+ path = "M 0 0 L 10 5 L 0 10 z"+ elif typ == "stealth":+ path = "M 0 0 L 10 5 L 0 10 L 3 5 z"+ elif typ == "arrow":+ path = "M 0 0 L 10 5 L 0 10"+ elif typ == "diamond":+ path = "M 0 5 L 5 0 L 10 5 L 5 10 z"+ elif typ == "oval":+ path = "" # use circle below+ else:+ # Unknown type — fall back to triangle so user still sees something+ path = "M 0 0 L 10 5 L 0 10 z"++ if typ == "oval":+ body = f'<circle cx="5" cy="5" r="4" fill="{stroke_color}"/>'+ else:+ body = f'<path d="{path}" fill="{stroke_color}"/>'++ orient = "auto-start-reverse" if reversed_ else "auto"+ fill_attr = "" if typ == "arrow" else "" # no extra+ # Note: stroke="none" prevents marker from inheriting parent stroke.+ marker_def = (+ f'<marker id="{marker_id}" viewBox="0 0 10 10" '+ f'refX="{"0" if reversed_ else "10"}" refY="5" '+ f'markerWidth="{fmt_num(mw, 2)}" markerHeight="{fmt_num(mh, 2)}" '+ f'orient="{orient}" markerUnits="strokeWidth">'+ f"{body}</marker>"+ )+ return marker_id, marker_defdiff --git a/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py b/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.pynew file mode 100644index 00000000..c5303311--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py@@ -0,0 +1,302 @@+"""OOXML loader: read .pptx zip package, resolve relationships, expose+slide / layout / master / theme / media as a navigable structure.++Mirrors what manifest.py does for analysis, but keeps the parsed XML roots+accessible for downstream shape conversion.+"""++from __future__ import annotations++import posixpath+import zipfile+from dataclasses import dataclass, field+from pathlib import Path, PurePosixPath+from typing import Iterator+from xml.etree import ElementTree as ET++from .emu_units import NS, emu_attr_to_px+++# ---------------------------------------------------------------------------+# Relationship parsing+# ---------------------------------------------------------------------------++REL_NS = NS["rel"]+PACKAGE_REL = "_rels/.rels"+PRESENTATION_REL_PREFIX = "ppt/_rels/presentation.xml.rels"+++def _normalize_part_path(target: str, base: str | None = None) -> str:+ """Resolve a relationship target against its rels source.++ PPTX rels typically use paths relative to the rels file's parent directory,+ e.g. slide1.xml.rels says target="../theme/theme1.xml". The result is+ normalized to a posix path with no leading slash and no '..'.+ """+ target = target.replace("\\", "/")+ if target.startswith("/"):+ return target.lstrip("/")+ if base is None:+ return target+ base_dir = posixpath.dirname(base.rstrip("/"))+ joined = posixpath.normpath(posixpath.join(base_dir, target))+ return joined.lstrip("/")+++def _rels_path_for(part_path: str) -> str:+ """Given a part path 'ppt/slides/slide1.xml', return its rels path."""+ parent, name = posixpath.split(part_path)+ if not parent:+ return f"_rels/{name}.rels"+ return f"{parent}/_rels/{name}.rels"+++def _parse_rels(zf: zipfile.ZipFile, rels_path: str) -> dict[str, dict[str, str]]:+ """Parse a .rels file. Returns {rId: {'type': ..., 'target': absolute_part_path}}."""+ if rels_path not in zf.namelist():+ return {}+ try:+ root = ET.fromstring(zf.read(rels_path))+ except ET.ParseError:+ return {}++ base = rels_path.replace("/_rels/", "/") # source part path+ base = base[:-len(".rels")] # strip .rels suffix+ rels: dict[str, dict[str, str]] = {}+ for child in root.findall(f"{{{REL_NS}}}Relationship"):+ rid = child.attrib.get("Id", "")+ rtype = child.attrib.get("Type", "")+ target = child.attrib.get("Target", "")+ target_mode = child.attrib.get("TargetMode", "")+ # External relationships (e.g. hyperlinks) keep the raw target.+ if target_mode == "External":+ rels[rid] = {"type": rtype, "target": target, "external": "1"}+ continue+ absolute = _normalize_part_path(target, base)+ rels[rid] = {"type": rtype, "target": absolute}+ return rels+++def _load_xml(zf: zipfile.ZipFile, part_path: str) -> ET.Element | None:+ if part_path not in zf.namelist():+ return None+ try:+ return ET.fromstring(zf.read(part_path))+ except ET.ParseError:+ return None+++# ---------------------------------------------------------------------------+# Data classes for navigable parts+# ---------------------------------------------------------------------------++@dataclass+class PartRef:+ """A loaded XML part with its rels resolved."""++ path: str+ xml: ET.Element+ rels: dict[str, dict[str, str]] = field(default_factory=dict)++ def resolve_rel(self, rid: str) -> str | None:+ """Resolve an rId to an absolute part path. Returns None if missing."""+ info = self.rels.get(rid)+ if info is None:+ return None+ if info.get("external"):+ return None+ return info.get("target")+++@dataclass+class SlideRef:+ """One slide, with its layout / master chain attached."""++ index: int # 1-based+ part: PartRef+ layout: PartRef | None+ master: PartRef | None+++# ---------------------------------------------------------------------------+# OoxmlPackage+# ---------------------------------------------------------------------------++# Relationship type constants+REL_TYPES = {+ "presentation": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",+ "slide": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide",+ "slideLayout": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout",+ "slideMaster": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster",+ "theme": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",+ "image": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",+ "media": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/media",+}+++class OoxmlPackage:+ """Loaded .pptx ready for shape walking.++ Usage:+ with OoxmlPackage(Path("foo.pptx")) as pkg:+ for slide in pkg.iter_slides():+ root = slide.part.xml+ ...+ """++ def __init__(self, pptx_path: Path) -> None:+ self.path = pptx_path+ self.zip: zipfile.ZipFile | None = None+ self.presentation: PartRef | None = None+ self.slide_size_px: tuple[float, float] = (1280.0, 720.0)+ self.slide_size_emu: tuple[int, int] = (12192000, 6858000)+ self._slides: list[SlideRef] = []+ self._layouts: dict[str, PartRef] = {}+ self._masters: dict[str, PartRef] = {}+ self._themes: dict[str, PartRef] = {}++ # ------------------- context manager -------------------++ def __enter__(self) -> "OoxmlPackage":+ self.open()+ return self++ def __exit__(self, exc_type, exc, tb) -> None:+ self.close()++ def open(self) -> None:+ if self.zip is not None:+ return+ self.zip = zipfile.ZipFile(self.path, "r")+ self._load_presentation()+ self._load_slides()++ def close(self) -> None:+ if self.zip is not None:+ self.zip.close()+ self.zip = None++ # ------------------- low-level helpers -------------------++ def _load_part(self, part_path: str) -> PartRef | None:+ assert self.zip is not None+ xml = _load_xml(self.zip, part_path)+ if xml is None:+ return None+ rels = _parse_rels(self.zip, _rels_path_for(part_path))+ return PartRef(path=part_path, xml=xml, rels=rels)++ def read_media(self, part_path: str) -> bytes | None:+ """Return raw bytes of an embedded media part (e.g. ppt/media/image1.png)."""+ assert self.zip is not None+ if part_path not in self.zip.namelist():+ return None+ return self.zip.read(part_path)++ def media_filename(self, part_path: str) -> str:+ """Last segment of the media path, e.g. 'image1.png'."""+ return PurePosixPath(part_path).name++ # ------------------- loading sequence -------------------++ def _load_presentation(self) -> None:+ assert self.zip is not None+ # /_rels/.rels -> presentation.xml+ package_rels = _parse_rels(self.zip, PACKAGE_REL)+ pres_path = None+ for info in package_rels.values():+ if info.get("type") == REL_TYPES["presentation"]:+ pres_path = info["target"]+ break+ if pres_path is None:+ pres_path = "ppt/presentation.xml"++ self.presentation = self._load_part(pres_path)+ if self.presentation is None:+ raise RuntimeError(f"presentation.xml missing in {self.path}")++ # slide size+ size = self.presentation.xml.find("p:sldSz", NS)+ if size is not None:+ cx = int(size.attrib.get("cx", "12192000"))+ cy = int(size.attrib.get("cy", "6858000"))+ self.slide_size_emu = (cx, cy)+ self.slide_size_px = (cx / 9525.0, cy / 9525.0)++ def _load_slides(self) -> None:+ assert self.zip is not None and self.presentation is not None+ # presentation.xml has <p:sldIdLst><p:sldId r:id="rId..."/></p:sldIdLst>+ # in document order.+ sld_id_lst = self.presentation.xml.find("p:sldIdLst", NS)+ if sld_id_lst is None:+ return++ for index, sld_id in enumerate(sld_id_lst.findall("p:sldId", NS), start=1):+ rid = sld_id.attrib.get(f"{{{NS['r']}}}id")+ if not rid:+ continue+ slide_path = self.presentation.resolve_rel(rid)+ if not slide_path:+ continue+ slide_part = self._load_part(slide_path)+ if slide_part is None:+ continue+ layout = self._resolve_layout(slide_part)+ master = self._resolve_master(layout) if layout else None+ self._slides.append(SlideRef(+ index=index, part=slide_part, layout=layout, master=master,+ ))++ def _resolve_layout(self, slide: PartRef) -> PartRef | None:+ for info in slide.rels.values():+ if info.get("type") == REL_TYPES["slideLayout"]:+ target = info["target"]+ cached = self._layouts.get(target)+ if cached is None:+ cached = self._load_part(target)+ if cached is not None:+ self._layouts[target] = cached+ return cached+ return None++ def _resolve_master(self, layout: PartRef) -> PartRef | None:+ for info in layout.rels.values():+ if info.get("type") == REL_TYPES["slideMaster"]:+ target = info["target"]+ cached = self._masters.get(target)+ if cached is None:+ cached = self._load_part(target)+ if cached is not None:+ self._masters[target] = cached+ return cached+ return None++ def resolve_theme(self, master: PartRef | None) -> PartRef | None:+ """Return the theme part referenced by a slide master."""+ if master is None:+ return None+ for info in master.rels.values():+ if info.get("type") == REL_TYPES["theme"]:+ target = info["target"]+ cached = self._themes.get(target)+ if cached is None:+ cached = self._load_part(target)+ if cached is not None:+ self._themes[target] = cached+ return cached+ return None++ # ------------------- public iteration -------------------++ def iter_slides(self) -> Iterator[SlideRef]:+ yield from self._slides++ @property+ def slide_count(self) -> int:+ return len(self._slides)++ def get_slide(self, index: int) -> SlideRef | None:+ """1-based index lookup."""+ if 1 <= index <= len(self._slides):+ return self._slides[index - 1]+ return Nonediff --git a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.pynew file mode 100644index 00000000..ef3606ca--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py@@ -0,0 +1,187 @@+"""DrawingML <p:pic> -> SVG <image> conversion.++Reverse of svg_to_pptx convert_image.++DrawingML structure:+ <p:pic>+ <p:blipFill>+ <a:blip r:embed="rIdN"/>+ <a:srcRect l/t/r/b="1/100000"/> (optional crop)+ <a:stretch><a:fillRect/></a:stretch> (default: fill the shape)+ </p:blipFill>+ <p:spPr>+ <a:xfrm/>+ <a:prstGeom prst="rect"/> (usually rect; can be other)+ </p:spPr>+ </p:pic>++Strategy:+- Default (no srcRect, plain stretch) -> a single <image> filling the box,+ preserveAspectRatio="none".+- With srcRect -> wrap the <image> in a nested <svg viewBox> in the unit+ rectangle [0,1] x [0,1], so cropping is expressed as the visible viewBox+ region. preserveAspectRatio="none" both inside and outside.+- Image bytes are written through the result; the slide assembler decides+ the href format (external file vs base64).+"""++from __future__ import annotations++import base64+import mimetypes+from dataclasses import dataclass, field+from xml.etree import ElementTree as ET++from .emu_units import NS, Xfrm, fmt_num+from .ooxml_loader import OoxmlPackage, PartRef+++@dataclass+class PictureResult:+ """Resolved picture: SVG element string + extracted media bytes."""++ svg: str = ""+ # Map of {filename: bytes} that the assembler should emit alongside+ # the SVG. Filename is the basename inside the package's media dir.+ media: dict[str, bytes] = field(default_factory=dict)+++def convert_picture(+ pic_elem: ET.Element,+ xfrm: Xfrm,+ slide_part: PartRef,+ pkg: OoxmlPackage,+ *,+ media_subdir: str = "assets",+ embed_inline: bool = False,+) -> PictureResult:+ """Translate <p:pic> to SVG <image> (or nested <svg>+<image> for cropping)."""+ blip_fill = pic_elem.find("p:blipFill", NS)+ if blip_fill is None:+ return PictureResult()++ blip = blip_fill.find("a:blip", NS)+ if blip is None:+ return PictureResult()++ rid = blip.attrib.get(f"{{{NS['r']}}}embed")+ if not rid:+ return PictureResult()++ target = slide_part.resolve_rel(rid)+ if not target:+ return PictureResult()++ # Read the bytes+ img_bytes = pkg.read_media(target)+ if img_bytes is None:+ return PictureResult()++ filename = pkg.media_filename(target)+ href = _build_href(filename, img_bytes, media_subdir, embed_inline)++ # srcRect: l/t/r/b in 1/100000ths (so 50000 = 50%).+ src_rect = blip_fill.find("a:srcRect", NS)+ crop = _parse_src_rect(src_rect)++ # stretch / tile: default stretch+fillRect means "fill, ignore aspect ratio".+ has_stretch = blip_fill.find("a:stretch") is not None+ if not has_stretch:+ # tile mode is rare; for v1 fall back to plain image.+ pass++ if crop is None:+ # Plain unclipped image+ svg = (+ f'<image href="{href}" x="{fmt_num(xfrm.x)}" y="{fmt_num(xfrm.y)}" '+ f'width="{fmt_num(xfrm.w)}" height="{fmt_num(xfrm.h)}" '+ f'preserveAspectRatio="none"/>'+ )+ else:+ # Crop expressed as a unit-rectangle viewBox on a nested <svg>.+ vb_l, vb_t, vb_w, vb_h = crop+ svg = (+ f'<svg x="{fmt_num(xfrm.x)}" y="{fmt_num(xfrm.y)}" '+ f'width="{fmt_num(xfrm.w)}" height="{fmt_num(xfrm.h)}" '+ f'viewBox="{fmt_num(vb_l, 5)} {fmt_num(vb_t, 5)} '+ f'{fmt_num(vb_w, 5)} {fmt_num(vb_h, 5)}" '+ f'preserveAspectRatio="none">'+ f'<image href="{href}" x="0" y="0" width="1" height="1" '+ f'preserveAspectRatio="none"/>'+ f"</svg>"+ )++ media: dict[str, bytes] = {}+ if not embed_inline:+ media[filename] = img_bytes+ return PictureResult(svg=svg, media=media)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _parse_src_rect(elem: ET.Element | None) -> tuple[float, float, float, float] | None:+ """Convert <a:srcRect l t r b="1/100000"/> to (x, y, w, h) in unit space."""+ if elem is None:+ return None+ if not (elem.attrib.keys() & {"l", "t", "r", "b"}):+ return None+ l = _pct_attr(elem, "l")+ t = _pct_attr(elem, "t")+ r = _pct_attr(elem, "r")+ b = _pct_attr(elem, "b")+ # All zero -> equivalent to no crop+ if l == 0 and t == 0 and r == 0 and b == 0:+ return None+ vb_x = l+ vb_y = t+ vb_w = max(0.0, 1.0 - l - r)+ vb_h = max(0.0, 1.0 - t - b)+ if vb_w <= 0 or vb_h <= 0:+ return None+ return vb_x, vb_y, vb_w, vb_h+++def _pct_attr(elem: ET.Element, name: str) -> float:+ val = elem.attrib.get(name)+ if val is None:+ return 0.0+ try:+ return float(val) / 100000.0+ except ValueError:+ return 0.0+++def _build_href(filename: str, img_bytes: bytes, subdir: str, embed: bool) -> str:+ """Build an <image href=...> value (relative path or data URI).++ The path is relative to the SVG file's location. The slide assembler writes+ SVGs to <output>/svg/, so media files in <output>/<subdir>/ resolve via+ a leading "../".+ """+ if embed:+ mime = (+ mimetypes.guess_type(filename)[0]+ or _sniff_mime(img_bytes)+ or "application/octet-stream"+ )+ encoded = base64.b64encode(img_bytes).decode("ascii")+ return f"data:{mime};base64,{encoded}"+ rel = f"../{subdir}/{filename}" if subdir else f"../{filename}"+ return rel+++def _sniff_mime(data: bytes) -> str | None:+ """Best-effort MIME sniffing for embedded images."""+ if data.startswith(b"\x89PNG\r\n\x1a\n"):+ return "image/png"+ if data.startswith(b"\xff\xd8\xff"):+ return "image/jpeg"+ if data.startswith(b"GIF87a") or data.startswith(b"GIF89a"):+ return "image/gif"+ if data.startswith(b"<svg") or data.startswith(b"<?xml"):+ return "image/svg+xml"+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":+ return "image/webp"+ return Nonediff --git a/skills/ppt-master/scripts/pptx_to_svg/prstgeom_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/prstgeom_to_svg.pynew file mode 100644index 00000000..81a3878b--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/prstgeom_to_svg.py@@ -0,0 +1,460 @@+"""DrawingML <a:prstGeom> -> SVG geometry conversion.++svg_to_pptx only emits 4 prstGeom presets (rect / roundRect / ellipse / line);+everything else goes through custGeom. So the reverse pipeline only needs+strong support for those four to handle round-tripped decks. We additionally+include an extended preset map covering the most common PowerPoint-authored+shapes (triangle, diamond, hexagon, parallelogram, arrow, star, etc.) so+hand-built decks like muban.pptx don't fall through to a placeholder.++Each handler returns a SHAPE_TAG + attribute dict that the slide assembler+wraps with fill/stroke/effect attributes plus the absolute (x, y) translation.+"""++from __future__ import annotations++import math+from dataclasses import dataclass, field+from xml.etree import ElementTree as ET++from .emu_units import NS, Xfrm, fmt_num+++# ---------------------------------------------------------------------------+# GeomResult+# ---------------------------------------------------------------------------++@dataclass+class GeomResult:+ """Result of converting a prst preset to SVG.++ `tag` is the SVG element tag (rect / ellipse / line / polygon / path /+ polyline). `attrs` are absolute SVG coordinates already in slide space.+ `path_d` (when tag == 'path') is the d attribute. The slide assembler+ merges fill/stroke attrs from fill_to_svg/ln_to_svg.+ """++ tag: str+ attrs: dict[str, str] = field(default_factory=dict)+ # When tag == 'path' use path_d for the d attribute.+ path_d: str | None = None+ # When tag == 'polygon' / 'polyline' use points for the points attribute.+ points: str | None = None+++# ---------------------------------------------------------------------------+# Adjustment helper+# ---------------------------------------------------------------------------++def _adj_value(sp_pr: ET.Element | None, adj_name: str = "adj",+ default_pct: float = 0.0) -> float:+ """Read an adjustment value from <a:avLst><a:gd name="..." fmla="val N"/>.++ Returns the value as a fraction in [0, 1] of the relevant dimension. If+ the gd is absent or the formula is unparseable, returns default_pct.+ """+ if sp_pr is None:+ return default_pct+ av_lst = sp_pr.find(".//a:avLst", NS)+ if av_lst is None:+ return default_pct+ for gd in av_lst.findall("a:gd", NS):+ if gd.attrib.get("name") == adj_name:+ fmla = gd.attrib.get("fmla", "")+ if fmla.startswith("val "):+ try:+ return float(fmla[4:]) / 100000.0+ except ValueError:+ return default_pct+ return default_pct+++# ---------------------------------------------------------------------------+# Dispatch+# ---------------------------------------------------------------------------++def convert_prst_geom(+ prst: str,+ xfrm: Xfrm,+ sp_pr: ET.Element | None,+) -> GeomResult | None:+ """Convert <a:prstGeom prst="..."> to a GeomResult.++ Returns None if the preset has no v1 mapping; the caller can then choose+ to render a fallback rect.+ """+ if xfrm.w <= 0 or xfrm.h <= 0:+ return None+ handler = _PRESET_HANDLERS.get(prst)+ if handler is None:+ return None+ return handler(xfrm, sp_pr)+++# ---------------------------------------------------------------------------+# Per-preset handlers+# ---------------------------------------------------------------------------++def _rect(xfrm: Xfrm, _sp_pr) -> GeomResult:+ return GeomResult(+ tag="rect",+ attrs={+ "x": fmt_num(xfrm.x),+ "y": fmt_num(xfrm.y),+ "width": fmt_num(xfrm.w),+ "height": fmt_num(xfrm.h),+ },+ )+++def _round_rect(xfrm: Xfrm, sp_pr) -> GeomResult:+ """roundRect adj = ratio of corner radius to half of shorter side.++ DrawingML default adj = 16667 (16.667%) when avLst is absent.+ """+ adj = _adj_value(sp_pr, "adj", default_pct=0.16667)+ short = min(xfrm.w, xfrm.h)+ radius = adj * short / 2.0 # adj is fraction of "half shorter side"+ # Actually DrawingML "adj" for roundRect is fraction of the shorter side+ # itself (i.e. up to 50000 = half side = capsule). svg_to_pptx writes+ # adj = radius / shorterSide * 100000, so we invert: radius = adj * shorter.+ radius = adj * short+ radius = min(radius, short / 2.0)+ return GeomResult(+ tag="rect",+ attrs={+ "x": fmt_num(xfrm.x),+ "y": fmt_num(xfrm.y),+ "width": fmt_num(xfrm.w),+ "height": fmt_num(xfrm.h),+ "rx": fmt_num(radius),+ "ry": fmt_num(radius),+ },+ )+++def _ellipse(xfrm: Xfrm, _sp_pr) -> GeomResult:+ cx = xfrm.x + xfrm.w / 2.0+ cy = xfrm.y + xfrm.h / 2.0+ rx = xfrm.w / 2.0+ ry = xfrm.h / 2.0+ return GeomResult(+ tag="ellipse",+ attrs={+ "cx": fmt_num(cx), "cy": fmt_num(cy),+ "rx": fmt_num(rx), "ry": fmt_num(ry),+ },+ )+++def _line(xfrm: Xfrm, _sp_pr) -> GeomResult:+ # cxnSp line endpoints: x1,y1 = (x, y); x2,y2 = (x+w, y+h). flipH/flipV+ # already baked into the xfrm via to_svg_transform.+ return GeomResult(+ tag="line",+ attrs={+ "x1": fmt_num(xfrm.x), "y1": fmt_num(xfrm.y),+ "x2": fmt_num(xfrm.x + xfrm.w), "y2": fmt_num(xfrm.y + xfrm.h),+ },+ )+++# ---------- Polygon-based shapes ----------++def _polygon(points: list[tuple[float, float]]) -> GeomResult:+ pts = " ".join(f"{fmt_num(x)},{fmt_num(y)}" for x, y in points)+ return GeomResult(tag="polygon", points=pts)+++def _triangle(xfrm: Xfrm, sp_pr) -> GeomResult:+ """Isoceles triangle. adj controls apex x position (default 50%)."""+ adj = _adj_value(sp_pr, "adj", default_pct=0.5)+ apex_x = xfrm.x + adj * xfrm.w+ return _polygon([+ (apex_x, xfrm.y),+ (xfrm.x + xfrm.w, xfrm.y + xfrm.h),+ (xfrm.x, xfrm.y + xfrm.h),+ ])+++def _rt_triangle(xfrm: Xfrm, _sp_pr) -> GeomResult:+ return _polygon([+ (xfrm.x, xfrm.y),+ (xfrm.x, xfrm.y + xfrm.h),+ (xfrm.x + xfrm.w, xfrm.y + xfrm.h),+ ])+++def _diamond(xfrm: Xfrm, _sp_pr) -> GeomResult:+ cx = xfrm.x + xfrm.w / 2.0+ cy = xfrm.y + xfrm.h / 2.0+ return _polygon([+ (cx, xfrm.y),+ (xfrm.x + xfrm.w, cy),+ (cx, xfrm.y + xfrm.h),+ (xfrm.x, cy),+ ])+++def _parallelogram(xfrm: Xfrm, sp_pr) -> GeomResult:+ """adj = horizontal skew offset as fraction of width (default 25%)."""+ adj = _adj_value(sp_pr, "adj", default_pct=0.25)+ skew = adj * xfrm.w+ return _polygon([+ (xfrm.x + skew, xfrm.y),+ (xfrm.x + xfrm.w, xfrm.y),+ (xfrm.x + xfrm.w - skew, xfrm.y + xfrm.h),+ (xfrm.x, xfrm.y + xfrm.h),+ ])+++def _trapezoid(xfrm: Xfrm, sp_pr) -> GeomResult:+ """adj = horizontal inset of top edge (default 25%)."""+ adj = _adj_value(sp_pr, "adj", default_pct=0.25)+ inset = adj * xfrm.w+ return _polygon([+ (xfrm.x + inset, xfrm.y),+ (xfrm.x + xfrm.w - inset, xfrm.y),+ (xfrm.x + xfrm.w, xfrm.y + xfrm.h),+ (xfrm.x, xfrm.y + xfrm.h),+ ])+++def _regular_polygon(xfrm: Xfrm, n_sides: int, *, rot_deg: float = -90.0) -> GeomResult:+ """Regular polygon inscribed in the bounding box."""+ cx = xfrm.x + xfrm.w / 2.0+ cy = xfrm.y + xfrm.h / 2.0+ rx = xfrm.w / 2.0+ ry = xfrm.h / 2.0+ pts: list[tuple[float, float]] = []+ for i in range(n_sides):+ ang = math.radians(rot_deg + i * 360.0 / n_sides)+ pts.append((cx + rx * math.cos(ang), cy + ry * math.sin(ang)))+ return _polygon(pts)+++def _pentagon(xfrm: Xfrm, _sp_pr) -> GeomResult:+ return _regular_polygon(xfrm, 5)+++def _hexagon(xfrm: Xfrm, _sp_pr) -> GeomResult:+ return _regular_polygon(xfrm, 6, rot_deg=0)+++def _heptagon(xfrm: Xfrm, _sp_pr) -> GeomResult:+ return _regular_polygon(xfrm, 7)+++def _octagon(xfrm: Xfrm, _sp_pr) -> GeomResult:+ return _regular_polygon(xfrm, 8, rot_deg=22.5)+++def _decagon(xfrm: Xfrm, _sp_pr) -> GeomResult:+ return _regular_polygon(xfrm, 10)+++def _dodecagon(xfrm: Xfrm, _sp_pr) -> GeomResult:+ return _regular_polygon(xfrm, 12)+++def _star(n_points: int):+ def handler(xfrm: Xfrm, _sp_pr) -> GeomResult:+ cx = xfrm.x + xfrm.w / 2.0+ cy = xfrm.y + xfrm.h / 2.0+ r_outer_x = xfrm.w / 2.0+ r_outer_y = xfrm.h / 2.0+ # Inner radius: classic 5-pointed star uses ~0.382 of outer.+ inner_ratio = 0.382 if n_points == 5 else 0.5+ r_inner_x = r_outer_x * inner_ratio+ r_inner_y = r_outer_y * inner_ratio+ pts: list[tuple[float, float]] = []+ for i in range(n_points * 2):+ angle = math.radians(-90 + i * (360.0 / (n_points * 2)))+ rx = r_outer_x if i % 2 == 0 else r_inner_x+ ry = r_outer_y if i % 2 == 0 else r_inner_y+ pts.append((cx + rx * math.cos(angle), cy + ry * math.sin(angle)))+ return _polygon(pts)+ return handler+++# ---------- Arrow shapes ----------++def _right_arrow(xfrm: Xfrm, sp_pr) -> GeomResult:+ """Right-pointing block arrow. adj1 = head width / shape height (50%);+ adj2 = head length / shape width (50%)."""+ adj1 = _adj_value(sp_pr, "adj1", default_pct=0.5)+ adj2 = _adj_value(sp_pr, "adj2", default_pct=0.5)+ head_h = xfrm.h * adj1+ head_w = xfrm.w * adj2+ body_y_top = xfrm.y + (xfrm.h - head_h) / 2.0+ body_y_bot = xfrm.y + (xfrm.h + head_h) / 2.0+ head_x = xfrm.x + xfrm.w - head_w+ return _polygon([+ (xfrm.x, body_y_top),+ (head_x, body_y_top),+ (head_x, xfrm.y),+ (xfrm.x + xfrm.w, xfrm.y + xfrm.h / 2.0),+ (head_x, xfrm.y + xfrm.h),+ (head_x, body_y_bot),+ (xfrm.x, body_y_bot),+ ])+++def _left_arrow(xfrm: Xfrm, sp_pr) -> GeomResult:+ adj1 = _adj_value(sp_pr, "adj1", default_pct=0.5)+ adj2 = _adj_value(sp_pr, "adj2", default_pct=0.5)+ head_h = xfrm.h * adj1+ head_w = xfrm.w * adj2+ body_y_top = xfrm.y + (xfrm.h - head_h) / 2.0+ body_y_bot = xfrm.y + (xfrm.h + head_h) / 2.0+ head_x = xfrm.x + head_w+ return _polygon([+ (xfrm.x + xfrm.w, body_y_top),+ (head_x, body_y_top),+ (head_x, xfrm.y),+ (xfrm.x, xfrm.y + xfrm.h / 2.0),+ (head_x, xfrm.y + xfrm.h),+ (head_x, body_y_bot),+ (xfrm.x + xfrm.w, body_y_bot),+ ])+++def _down_arrow(xfrm: Xfrm, sp_pr) -> GeomResult:+ adj1 = _adj_value(sp_pr, "adj1", default_pct=0.5)+ adj2 = _adj_value(sp_pr, "adj2", default_pct=0.5)+ head_w = xfrm.w * adj1+ head_h = xfrm.h * adj2+ body_x_l = xfrm.x + (xfrm.w - head_w) / 2.0+ body_x_r = xfrm.x + (xfrm.w + head_w) / 2.0+ head_y = xfrm.y + xfrm.h - head_h+ return _polygon([+ (body_x_l, xfrm.y),+ (body_x_l, head_y),+ (xfrm.x, head_y),+ (xfrm.x + xfrm.w / 2.0, xfrm.y + xfrm.h),+ (xfrm.x + xfrm.w, head_y),+ (body_x_r, head_y),+ (body_x_r, xfrm.y),+ ])+++def _up_arrow(xfrm: Xfrm, sp_pr) -> GeomResult:+ adj1 = _adj_value(sp_pr, "adj1", default_pct=0.5)+ adj2 = _adj_value(sp_pr, "adj2", default_pct=0.5)+ head_w = xfrm.w * adj1+ head_h = xfrm.h * adj2+ body_x_l = xfrm.x + (xfrm.w - head_w) / 2.0+ body_x_r = xfrm.x + (xfrm.w + head_w) / 2.0+ head_y = xfrm.y + head_h+ return _polygon([+ (body_x_l, xfrm.y + xfrm.h),+ (body_x_l, head_y),+ (xfrm.x, head_y),+ (xfrm.x + xfrm.w / 2.0, xfrm.y),+ (xfrm.x + xfrm.w, head_y),+ (body_x_r, head_y),+ (body_x_r, xfrm.y + xfrm.h),+ ])+++# ---------- Pie / chord / arc (path-based) ----------++def _pie(xfrm: Xfrm, sp_pr) -> GeomResult:+ """Pie slice. adj1 = start angle, adj2 = end angle (1/60000 deg)."""+ adj1 = _adj_value(sp_pr, "adj1", default_pct=0.0) # default 0°+ adj2 = _adj_value(sp_pr, "adj2", default_pct=270.0 / 360.0) # default 270°+ # adj is in 100000ths of percent → degrees by * 360+ start_deg = adj1 * 360.0+ end_deg = adj2 * 360.0+ return _arc_path(xfrm, start_deg, end_deg, mode="pie")+++def _chord(xfrm: Xfrm, sp_pr) -> GeomResult:+ adj1 = _adj_value(sp_pr, "adj1", default_pct=0.0)+ adj2 = _adj_value(sp_pr, "adj2", default_pct=270.0 / 360.0)+ return _arc_path(xfrm, adj1 * 360.0, adj2 * 360.0, mode="chord")+++def _arc(xfrm: Xfrm, sp_pr) -> GeomResult:+ adj1 = _adj_value(sp_pr, "adj1", default_pct=270.0 / 360.0)+ adj2 = _adj_value(sp_pr, "adj2", default_pct=0.0)+ return _arc_path(xfrm, adj1 * 360.0, adj2 * 360.0, mode="arc")+++def _arc_path(xfrm: Xfrm, start_deg: float, end_deg: float, *, mode: str) -> GeomResult:+ cx = xfrm.x + xfrm.w / 2.0+ cy = xfrm.y + xfrm.h / 2.0+ rx = xfrm.w / 2.0+ ry = xfrm.h / 2.0+ sa = math.radians(start_deg)+ ea = math.radians(end_deg)+ sx = cx + rx * math.cos(sa)+ sy = cy + ry * math.sin(sa)+ ex = cx + rx * math.cos(ea)+ ey = cy + ry * math.sin(ea)+ # Sweep direction: PowerPoint draws clockwise; SVG arc sweep_flag = 1 = clockwise.+ delta = (end_deg - start_deg) % 360.0+ large_arc = 1 if delta > 180 else 0+ sweep = 1+ parts = [f"M {fmt_num(sx)} {fmt_num(sy)}",+ f"A {fmt_num(rx)} {fmt_num(ry)} 0 {large_arc} {sweep} {fmt_num(ex)} {fmt_num(ey)}"]+ if mode == "pie":+ parts.append(f"L {fmt_num(cx)} {fmt_num(cy)}")+ parts.append("Z")+ elif mode == "chord":+ parts.append("Z")+ return GeomResult(tag="path", path_d=" ".join(parts))+++# ---------------------------------------------------------------------------+# Preset table+# ---------------------------------------------------------------------------++_PRESET_HANDLERS = {+ # Core 4 (svg_to_pptx round-trip)+ "rect": _rect,+ "roundRect": _round_rect,+ "ellipse": _ellipse,+ "line": _line,++ # Polygons+ "triangle": _triangle,+ "rtTriangle": _rt_triangle,+ "diamond": _diamond,+ "parallelogram": _parallelogram,+ "trapezoid": _trapezoid,+ "pentagon": _pentagon,+ "hexagon": _hexagon,+ "heptagon": _heptagon,+ "octagon": _octagon,+ "decagon": _decagon,+ "dodecagon": _dodecagon,++ # Stars+ "star4": _star(4),+ "star5": _star(5),+ "star6": _star(6),+ "star7": _star(7),+ "star8": _star(8),+ "star10": _star(10),+ "star12": _star(12),+ "star16": _star(16),+ "star24": _star(24),+ "star32": _star(32),++ # Arrows+ "rightArrow": _right_arrow,+ "leftArrow": _left_arrow,+ "downArrow": _down_arrow,+ "upArrow": _up_arrow,++ # Pie / chord / arc+ "pie": _pie,+ "chord": _chord,+ "arc": _arc,+}+++def supported_presets() -> set[str]:+ """Return the set of recognized prst values for diagnostics."""+ return set(_PRESET_HANDLERS.keys())diff --git a/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py b/skills/ppt-master/scripts/pptx_to_svg/shape_walker.pynew file mode 100644index 00000000..2fa22423--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py@@ -0,0 +1,201 @@+"""Shape tree walker.++Reads <p:spTree> from a slide / layout / master and emits a normalized+ShapeNode tree that downstream converters can dispatch on.++Handles:+- <p:sp> -> SHAPE+- <p:pic> -> PICTURE+- <p:cxnSp> -> CONNECTOR+- <p:grpSp> -> GROUP (recurses; resolves a:chOff/a:chExt frame)+- <p:graphicFrame> -> GRAPHIC (table / chart / SmartArt — emitted as opaque+ placeholder for v1 so callers can decide a fallback)+"""++from __future__ import annotations++from dataclasses import dataclass, field+from xml.etree import ElementTree as ET++from .emu_units import NS, Xfrm, parse_xfrm+++# ---------------------------------------------------------------------------+# ShapeNode+# ---------------------------------------------------------------------------++SHAPE = "sp"+PICTURE = "pic"+CONNECTOR = "cxnSp"+GROUP = "grpSp"+GRAPHIC = "graphicFrame"+++@dataclass+class PlaceholderInfo:+ """Resolved <p:ph> attributes for a shape if any."""++ type: str | None = None # title / body / ctrTitle / subTitle / ftr / dt / ...+ idx: str | None = None+ sz: str | None = None # full / half / quarter+ orient: str | None = None+++@dataclass+class ShapeNode:+ """Normalized shape entry produced by the walker."""++ kind: str # one of SHAPE / PICTURE / CONNECTOR / GROUP / GRAPHIC+ xml: ET.Element # original element+ xfrm: Xfrm # resolved geometry in absolute slide pixel space+ name: str = ""+ spid: str = ""+ hidden: bool = False+ placeholder: PlaceholderInfo | None = None+ # GROUP only: children, in z-order+ children: list["ShapeNode"] = field(default_factory=list)+++# ---------------------------------------------------------------------------+# Walker+# ---------------------------------------------------------------------------++def _read_nv_sp_pr(parent: ET.Element, nv_tag: str) -> tuple[str, str, bool, PlaceholderInfo | None]:+ """Extract name/id/hidden/placeholder from an nvXXXPr container.++ nv_tag is one of nvSpPr / nvPicPr / nvCxnSpPr / nvGrpSpPr / nvGraphicFramePr.+ """+ container = parent.find(f"p:{nv_tag}", NS)+ name = ""+ spid = ""+ hidden = False+ ph: PlaceholderInfo | None = None+ if container is None:+ return name, spid, hidden, ph++ cnv = container.find("p:cNvPr", NS)+ if cnv is not None:+ name = cnv.attrib.get("name", "")+ spid = cnv.attrib.get("id", "")+ if cnv.attrib.get("hidden") == "1":+ hidden = True++ nv_sp_pr = container.find("p:nvSpPr", NS)+ if nv_sp_pr is not None:+ ph_elem = nv_sp_pr.find("p:ph", NS)+ if ph_elem is not None:+ ph = PlaceholderInfo(+ type=ph_elem.attrib.get("type"),+ idx=ph_elem.attrib.get("idx"),+ sz=ph_elem.attrib.get("sz"),+ orient=ph_elem.attrib.get("orient"),+ )++ return name, spid, hidden, ph+++def _resolve_xfrm(shape: ET.Element, kind: str) -> ET.Element | None:+ """Find the <a:xfrm> element under the right spPr / grpSpPr container."""+ if kind == GROUP:+ sp_pr = shape.find("p:grpSpPr", NS)+ elif kind == GRAPHIC:+ # graphicFrame uses p:xfrm directly (no a: namespace)+ return shape.find("p:xfrm", NS)+ else:+ sp_pr = shape.find("p:spPr", NS)+ if sp_pr is None:+ return None+ return sp_pr.find("a:xfrm", NS)+++def _adjust_for_group(child_xfrm: Xfrm, group_xfrm: Xfrm) -> Xfrm:+ """Map a child shape's xfrm from group's child coordinate space into the+ parent (group) coordinate space.++ DrawingML group rule: a child's a:off/a:ext is in the group's chOff/chExt+ coordinate system. We map to the group's actual off/ext on the slide.++ If the group has no chOff/chExt, fall back to identity translation.+ """+ if (group_xfrm.ch_w is None or group_xfrm.ch_h is None+ or group_xfrm.ch_w == 0 or group_xfrm.ch_h == 0):+ # No child frame — children already in slide space; just translate.+ return child_xfrm++ # Linear map: child-frame -> group's (off..off+ext)+ sx = group_xfrm.w / group_xfrm.ch_w if group_xfrm.ch_w else 1.0+ sy = group_xfrm.h / group_xfrm.ch_h if group_xfrm.ch_h else 1.0+ ch_x = group_xfrm.ch_x or 0.0+ ch_y = group_xfrm.ch_y or 0.0++ new_x = group_xfrm.x + (child_xfrm.x - ch_x) * sx+ new_y = group_xfrm.y + (child_xfrm.y - ch_y) * sy+ new_w = child_xfrm.w * sx+ new_h = child_xfrm.h * sy++ return Xfrm(+ x=new_x, y=new_y, w=new_w, h=new_h,+ rot=child_xfrm.rot,+ flip_h=child_xfrm.flip_h,+ flip_v=child_xfrm.flip_v,+ ch_x=child_xfrm.ch_x, ch_y=child_xfrm.ch_y,+ ch_w=child_xfrm.ch_w, ch_h=child_xfrm.ch_h,+ )+++# Mapping from element tag -> kind / nv tag.+_KIND_MAP = {+ "sp": (SHAPE, "nvSpPr"),+ "pic": (PICTURE, "nvPicPr"),+ "cxnSp": (CONNECTOR, "nvCxnSpPr"),+ "grpSp": (GROUP, "nvGrpSpPr"),+ "graphicFrame": (GRAPHIC, "nvGraphicFramePr"),+}+++def _walk_container(+ container: ET.Element,+ parent_group_xfrm: Xfrm | None,+) -> list[ShapeNode]:+ """Walk a p:spTree or p:grpSp subtree. Children kept in document (z) order.+ """+ nodes: list[ShapeNode] = []+ for child in list(container):+ if not isinstance(child.tag, str):+ continue+ local = child.tag.split("}", 1)[-1]+ kind_info = _KIND_MAP.get(local)+ if kind_info is None:+ continue+ kind, nv_tag = kind_info++ name, spid, hidden, ph = _read_nv_sp_pr(child, nv_tag)+ xfrm = parse_xfrm(_resolve_xfrm(child, kind))++ # If we're inside a group, remap to slide-absolute coordinates+ if parent_group_xfrm is not None:+ xfrm = _adjust_for_group(xfrm, parent_group_xfrm)++ node = ShapeNode(+ kind=kind, xml=child, xfrm=xfrm,+ name=name, spid=spid, hidden=hidden, placeholder=ph,+ )++ if kind == GROUP:+ node.children = _walk_container(child, xfrm)++ nodes.append(node)+ return nodes+++def walk_sp_tree(slide_xml: ET.Element) -> list[ShapeNode]:+ """Top-level entry: return shape nodes for a slide / layout / master XML."""+ sp_tree = slide_xml.find("p:cSld/p:spTree", NS)+ if sp_tree is None:+ return []+ return _walk_container(sp_tree, parent_group_xfrm=None)+++def get_background(slide_xml: ET.Element) -> ET.Element | None:+ """Return the <p:bg> element if the slide defines its own background."""+ return slide_xml.find("p:cSld/p:bg", NS)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.pynew file mode 100644index 00000000..d0fb58fb--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py@@ -0,0 +1,363 @@+"""Per-slide composition: dispatches every ShapeNode through the right+converter, accumulates <defs>, and produces one final SVG string.++The output structure mirrors what svg_to_pptx expects so the deck can be+round-tripped:+ <svg viewBox="0 0 W H">+ <defs>+ <linearGradient id=.../>+ <marker id=.../>+ <filter id=.../>+ </defs>+ <!-- background -->+ <rect ... /> (slide background, if any)+ <g id="shape-1">...</g>+ <g id="shape-2">...</g>+ ...+ </svg>++Each top-level <g> wraps one shape and is treated by svg_to_pptx as an+animation anchor.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from xml.etree import ElementTree as ET++from .color_resolver import ColorPalette+from .custgeom_to_svg import convert_custom_geom+from .effect_to_svg import convert_effects+from .emu_units import NS, fmt_num+from .fill_to_svg import resolve_fill+from .ln_to_svg import resolve_stroke+from .ooxml_loader import OoxmlPackage, PartRef, SlideRef+from .pic_to_svg import convert_picture+from .prstgeom_to_svg import GeomResult, convert_prst_geom+from .shape_walker import (+ CONNECTOR, GRAPHIC, GROUP, PICTURE, SHAPE,+ ShapeNode, get_background, walk_sp_tree,+)+from .txbody_to_svg import TextResult, convert_txbody+++# ---------------------------------------------------------------------------+# AssemblyContext+# ---------------------------------------------------------------------------++@dataclass+class AssemblyContext:+ """Per-slide accumulator for unique IDs + media + defs."""++ palette: ColorPalette | None+ pkg: OoxmlPackage+ slide_part: PartRef+ theme_fonts: dict[str, str] = field(default_factory=dict)+ media_subdir: str = "assets"+ embed_images: bool = False+ keep_hidden: bool = False++ # Sequence counters (single-element lists so handlers can mutate)+ grad_seq: list[int] = field(default_factory=lambda: [0])+ marker_seq: list[int] = field(default_factory=lambda: [0])+ filter_seq: list[int] = field(default_factory=lambda: [0])+ shape_seq: list[int] = field(default_factory=lambda: [0])++ # Accumulated outputs+ defs: list[str] = field(default_factory=list)+ media: dict[str, bytes] = field(default_factory=dict)+++# ---------------------------------------------------------------------------+# Public entry+# ---------------------------------------------------------------------------++def assemble_slide(+ pkg: OoxmlPackage,+ slide: SlideRef,+ palette: ColorPalette | None,+ *,+ theme_fonts: dict[str, str] | None = None,+ media_subdir: str = "assets",+ embed_images: bool = False,+ keep_hidden: bool = False,+) -> tuple[str, dict[str, bytes]]:+ """Convert one slide to a complete SVG string + media files map."""+ ctx = AssemblyContext(+ palette=palette,+ pkg=pkg,+ slide_part=slide.part,+ theme_fonts=theme_fonts or {},+ media_subdir=media_subdir,+ embed_images=embed_images,+ keep_hidden=keep_hidden,+ )++ canvas_w, canvas_h = pkg.slide_size_px++ # Background (cSld/bg) — emit as the first body element.+ body_parts: list[str] = []+ bg_xml = _emit_background(slide, ctx, canvas_w, canvas_h)+ if bg_xml:+ body_parts.append(bg_xml)++ # Walk shapes+ nodes = walk_sp_tree(slide.part.xml)+ for node in nodes:+ chunk = _convert_node(node, ctx, top_level=True)+ if chunk:+ body_parts.append(chunk)++ # Compose final SVG+ defs_xml = "".join(ctx.defs) if ctx.defs else ""+ defs_block = f"<defs>{defs_xml}</defs>" if defs_xml else ""++ svg = (+ f'<svg xmlns="http://www.w3.org/2000/svg" '+ f'xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" '+ f'width="{fmt_num(canvas_w)}" height="{fmt_num(canvas_h)}" '+ f'viewBox="0 0 {fmt_num(canvas_w)} {fmt_num(canvas_h)}">'+ f"{defs_block}"+ + "\n".join(body_parts)+ + "</svg>"+ )+ return svg, ctx.media+++# ---------------------------------------------------------------------------+# Per-node dispatch+# ---------------------------------------------------------------------------++def _convert_node(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:+ if node.hidden and not ctx.keep_hidden:+ return ""+ if node.kind == SHAPE:+ return _convert_shape(node, ctx, top_level=top_level)+ if node.kind == PICTURE:+ return _convert_picture(node, ctx, top_level=top_level)+ if node.kind == CONNECTOR:+ return _convert_connector(node, ctx, top_level=top_level)+ if node.kind == GROUP:+ return _convert_group(node, ctx, top_level=top_level)+ if node.kind == GRAPHIC:+ return _convert_graphic_fallback(node, ctx, top_level=top_level)+ return ""+++# ---------------------------------------------------------------------------+# Shape (<p:sp>)+# ---------------------------------------------------------------------------++def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:+ sp_pr = node.xml.find("p:spPr", NS)++ # Geometry+ geom_xml = _build_geometry_xml(node, sp_pr, ctx)++ # Text body (a:txBody)+ tx_body = node.xml.find("p:txBody", NS)+ text_result = convert_txbody(+ tx_body, node.xfrm, ctx.palette,+ theme_fonts=ctx.theme_fonts,+ ) if tx_body is not None else TextResult()++ inner = (geom_xml + ("\n" + text_result.svg if text_result.svg else ""))+ return _wrap_shape_group(inner, node, ctx, top_level=top_level)+++def _build_geometry_xml(node: ShapeNode, sp_pr: ET.Element | None,+ ctx: AssemblyContext) -> str:+ """Build the SVG geometry element with fill/stroke/effect attributes."""+ # Resolve geometry+ prst_geom = sp_pr.find("a:prstGeom", NS) if sp_pr is not None else None+ cust_geom = sp_pr.find("a:custGeom", NS) if sp_pr is not None else None++ geom: GeomResult | None = None+ if prst_geom is not None:+ prst = prst_geom.attrib.get("prst", "rect")+ geom = convert_prst_geom(prst, node.xfrm, prst_geom)+ if geom is None:+ # Unknown prst — fall back to rect bounding box+ geom = convert_prst_geom("rect", node.xfrm, None)+ elif cust_geom is not None:+ d = convert_custom_geom(cust_geom, node.xfrm)+ if d:+ geom = GeomResult(tag="path", path_d=d)+ else:+ # No geometry hint at all — render bounding rect+ geom = convert_prst_geom("rect", node.xfrm, None)++ if geom is None or node.xfrm.w <= 0 or node.xfrm.h <= 0:+ return ""++ # Fill / stroke / effect+ fill = resolve_fill(sp_pr, ctx.palette,+ id_prefix="g", id_seq=ctx.grad_seq)+ stroke = resolve_stroke(sp_pr, ctx.palette,+ id_prefix="m", id_seq=ctx.marker_seq)+ filter_id, effect_defs = convert_effects(sp_pr, ctx.palette,+ id_prefix="fx",+ id_seq=ctx.filter_seq)++ ctx.defs.extend(fill.defs)+ ctx.defs.extend(stroke.defs)+ ctx.defs.extend(effect_defs)++ attrs = {**fill.attrs, **stroke.attrs}+ if filter_id is not None:+ attrs["filter"] = f"url(#{filter_id})"++ # Default fill / stroke when not specified by spPr (matches PowerPoint+ # behavior: a:noFill on shape-level fill if there's a txBody, else any+ # explicit fill present in spPr should already have been captured).+ if "fill" not in attrs:+ # Default: transparent so the shape doesn't paint over text/images.+ # PowerPoint's actual default is theme accent + style, but mimicking+ # that requires reading slideMaster styles which is out of v1 scope.+ attrs["fill"] = "none"+ if "stroke" not in attrs:+ # Spec default for shapes is no stroke unless ln says otherwise.+ # Skip emitting stroke="none" to keep markup tight.+ pass++ geom_attrs_xml = _attrs_to_xml({**geom.attrs, **attrs})++ if geom.tag == "path":+ return f'<path d="{geom.path_d}"{geom_attrs_xml}/>'+ if geom.tag in ("polygon", "polyline"):+ return f'<{geom.tag} points="{geom.points}"{geom_attrs_xml}/>'+ return f"<{geom.tag}{geom_attrs_xml}/>"+++# ---------------------------------------------------------------------------+# Picture (<p:pic>)+# ---------------------------------------------------------------------------++def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:+ result = convert_picture(+ node.xml, node.xfrm, ctx.slide_part, ctx.pkg,+ media_subdir=ctx.media_subdir,+ embed_inline=ctx.embed_images,+ )+ if not result.svg:+ return ""+ ctx.media.update(result.media)+ return _wrap_shape_group(result.svg, node, ctx, top_level=top_level)+++# ---------------------------------------------------------------------------+# Connector (<p:cxnSp>)+# ---------------------------------------------------------------------------++def _convert_connector(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:+ sp_pr = node.xml.find("p:spPr", NS)+ geom_xml = _build_geometry_xml(node, sp_pr, ctx)+ return _wrap_shape_group(geom_xml, node, ctx, top_level=top_level)+++# ---------------------------------------------------------------------------+# Group (<p:grpSp>)+# ---------------------------------------------------------------------------++def _convert_group(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:+ """Render group contents flat (children already remapped to slide space)."""+ inner_parts: list[str] = []+ for child in node.children:+ chunk = _convert_node(child, ctx, top_level=False)+ if chunk:+ inner_parts.append(chunk)+ if not inner_parts:+ return ""+ inner = "\n".join(inner_parts)+ return _wrap_shape_group(inner, node, ctx, top_level=top_level)+++# ---------------------------------------------------------------------------+# Graphic frame fallback (<p:graphicFrame>)+# ---------------------------------------------------------------------------++def _convert_graphic_fallback(node: ShapeNode, ctx: AssemblyContext,+ *, top_level: bool) -> str:+ """v1 fallback: render the bounding box with a dashed outline + label."""+ # Detect what's inside (chart / table / smartArt) for the comment.+ graphic_data = node.xml.find("a:graphic/a:graphicData", NS)+ uri = graphic_data.attrib.get("uri", "graphicFrame") if graphic_data is not None else "graphicFrame"+ label = uri.rsplit("/", 1)[-1]+ placeholder = (+ f'<rect x="{fmt_num(node.xfrm.x)}" y="{fmt_num(node.xfrm.y)}" '+ f'width="{fmt_num(node.xfrm.w)}" height="{fmt_num(node.xfrm.h)}" '+ f'fill="none" stroke="#999999" stroke-dasharray="4 4"/>'+ f'<text x="{fmt_num(node.xfrm.x + node.xfrm.w / 2)}" '+ f'y="{fmt_num(node.xfrm.y + node.xfrm.h / 2)}" '+ f'text-anchor="middle" font-size="14" fill="#999999">'+ f"[{_xml_escape(label)}]</text>"+ )+ return _wrap_shape_group(placeholder, node, ctx, top_level=top_level)+++# ---------------------------------------------------------------------------+# Background+# ---------------------------------------------------------------------------++def _emit_background(slide: SlideRef, ctx: AssemblyContext,+ w: float, h: float) -> str:+ """Inspect <p:bg> on slide / layout / master in inheritance order."""+ for part in (slide.part, slide.layout, slide.master):+ if part is None:+ continue+ bg = get_background(part.xml)+ if bg is None:+ continue+ bg_pr = bg.find("p:bgPr", NS)+ if bg_pr is None:+ continue+ fill = resolve_fill(bg_pr, ctx.palette,+ id_prefix="bg", id_seq=ctx.grad_seq)+ ctx.defs.extend(fill.defs)+ if not fill.attrs:+ return ""+ # Convert dict to attributes+ attrs_xml = _attrs_to_xml(fill.attrs)+ return (f'<rect x="0" y="0" width="{fmt_num(w)}" height="{fmt_num(h)}"'+ f"{attrs_xml}/>")+ return ""+++# ---------------------------------------------------------------------------+# Wrap / utilities+# ---------------------------------------------------------------------------++def _wrap_shape_group(inner: str, node: ShapeNode, ctx: AssemblyContext,+ *, top_level: bool) -> str:+ """Wrap a shape's body in a <g> that carries the transform (rotation /+ flip) and an id for animation anchoring."""+ if not inner.strip():+ return ""++ transform = node.xfrm.to_svg_transform()+ ctx.shape_seq[0] += 1+ seq = ctx.shape_seq[0]+ sid = node.spid or str(seq)+ g_id = f"shape-{sid}"++ attrs: list[str] = [f'id="{g_id}"']+ if node.name:+ attrs.append(f'data-name="{_xml_escape(node.name)}"')+ if node.placeholder is not None and node.placeholder.type:+ attrs.append(f'data-ph-type="{_xml_escape(node.placeholder.type)}"')+ if transform:+ attrs.append(f'transform="{transform}"')+ return f"<g {' '.join(attrs)}>\n{inner}\n</g>"+++def _attrs_to_xml(attrs: dict[str, str]) -> str:+ if not attrs:+ return ""+ return "".join(f' {k}="{v}"' for k, v in attrs.items())+++def _xml_escape(text: str) -> str:+ return (text.replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+ .replace('"', """))diff --git a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.pynew file mode 100644index 00000000..bdc229fa--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py@@ -0,0 +1,721 @@+"""DrawingML <p:txBody> -> SVG <text> conversion.++Reverse of svg_to_pptx/drawingml_elements.convert_text.++Strategy (v1):+- Each <a:p> paragraph emits one <text> element (one line of baseline).+ Multiple <a:r> runs in one paragraph become <tspan>s sharing the text+ element's x.+- Vertical layout: y of first paragraph is determined by anchor (t/ctr/b)+ and tIns/bIns. Subsequent paragraphs stack downward with line height+ derived from the largest font in the paragraph * 1.2 (default leading).+- Horizontal layout: text-anchor follows pPr@algn. x is computed from the+ text frame plus lIns/rIns and the alignment.+- No automatic word wrap (PPT's wrap is layout-time; v1 trusts the existing+ text frame width and emits text as-is). a:br produces an explicit linebreak.+- Bullet points (a:buChar / a:buAutoNum) are NOT rendered as PPT bullet+ glyphs — instead we prepend a literal '• ' / 'N. ' so the visual lands.++Color / font / size attributes propagate from a:rPr; missing attributes fall+back to the paragraph's endParaRPr or to spec-default values.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from xml.etree import ElementTree as ET++from .color_resolver import ColorPalette, find_color_elem, resolve_color+from .emu_units import (+ NS, Xfrm, fmt_num, emu_to_px, hundredths_pt_to_px,+)+++# ---------------------------------------------------------------------------+# Defaults (matches DrawingML spec)+# ---------------------------------------------------------------------------++# Default body insets when bodyPr omits them: 0.1 inch left/right, 0.05 top/bot.+DEFAULT_INSETS_EMU = {"l": 91440, "t": 45720, "r": 91440, "b": 45720}++# Default font size = 1800 (= 18 pt = 24 px). Spec is actually 1800 (18pt).+DEFAULT_FONT_SIZE_PX = 24.0+DEFAULT_LINE_HEIGHT_RATIO = 1.2 # leading multiplier+DEFAULT_FILL_HEX = "#000000"+++@dataclass+class TextRun:+ """A single run with resolved style + text."""++ text: str+ font_size_px: float+ font_family: str # full font-family stack (latin, ea fallback joined)+ fill: str+ fill_opacity: float = 1.0+ bold: bool = False+ italic: bool = False+ underline: bool = False+ strikethrough: bool = False+ letter_spacing_px: float = 0.0+ is_break: bool = False # marks an a:br within a paragraph+++@dataclass+class TextParagraph:+ """One <a:p>: a list of runs sharing alignment + level."""++ runs: list[TextRun] = field(default_factory=list)+ align: str = "l" # l / ctr / r / just / dist+ level: int = 0+ indent_px: float = 0.0+ margin_left_px: float = 0.0+ line_height_ratio: float = DEFAULT_LINE_HEIGHT_RATIO+ space_before_px: float = 0.0+ space_after_px: float = 0.0+ bullet_prefix: str = "" # rendered prefix like '• ' or '1. '+++@dataclass+class TextResult:+ """Resolved text body ready for SVG emission.++ `svg` is one or more <text> elements, already absolutely positioned+ inside the slide coordinate system. `defs` is empty for now.+ """++ svg: str = ""+ defs: list[str] = field(default_factory=list)+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------++def convert_txbody(+ tx_body: ET.Element | None,+ xfrm: Xfrm,+ palette: ColorPalette | None,+ *,+ theme_fonts: dict[str, str] | None = None,+) -> TextResult:+ """Convert <p:txBody> under the given shape geometry to SVG <text>(s)."""+ if tx_body is None:+ return TextResult()++ body_pr = tx_body.find("a:bodyPr", NS)+ paragraphs = _parse_paragraphs(tx_body, palette, theme_fonts or {})+ if not paragraphs or not _has_visible_text(paragraphs):+ return TextResult()++ # Insets + anchor + wrap+ lins = _read_emu_attr(body_pr, "lIns", DEFAULT_INSETS_EMU["l"])+ tins = _read_emu_attr(body_pr, "tIns", DEFAULT_INSETS_EMU["t"])+ rins = _read_emu_attr(body_pr, "rIns", DEFAULT_INSETS_EMU["r"])+ bins = _read_emu_attr(body_pr, "bIns", DEFAULT_INSETS_EMU["b"])+ anchor = body_pr.attrib.get("anchor", "t") if body_pr is not None else "t"+ wrap_mode = body_pr.attrib.get("wrap", "square") if body_pr is not None else "square"++ inner_x = xfrm.x + lins+ inner_y = xfrm.y + tins+ inner_w = max(xfrm.w - lins - rins, 1.0)+ inner_h = max(xfrm.h - tins - bins, 1.0)++ # Pre-wrap each paragraph into concrete display lines.+ wrap_width = inner_w if wrap_mode == "square" else float("inf")+ para_lines: list[list[list[TextRun]]] = [+ _wrap_paragraph_into_lines(p, wrap_width) for p in paragraphs+ ]++ # Pre-compute heights to support anchor=ctr / b+ para_heights = [+ _paragraph_height_from_lines(p, lines)+ for p, lines in zip(paragraphs, para_lines)+ ]+ total_h = sum(para_heights)+ if anchor == "ctr":+ cursor_y = inner_y + max(0.0, (inner_h - total_h) / 2.0)+ elif anchor == "b":+ cursor_y = inner_y + max(0.0, inner_h - total_h)+ else:+ cursor_y = inner_y++ text_blocks: list[str] = []+ for para, lines, height in zip(paragraphs, para_lines, para_heights):+ cursor_y += para.space_before_px+ text_blocks.append(_emit_paragraph(para, lines, inner_x, inner_w, cursor_y))+ cursor_y += height + para.space_after_px++ return TextResult(svg="\n".join(text_blocks))+++# ---------------------------------------------------------------------------+# Parsing helpers+# ---------------------------------------------------------------------------++def _read_emu_attr(elem: ET.Element | None, attr: str, default_emu: int) -> float:+ """Read an EMU integer attribute and return px."""+ if elem is None:+ return emu_to_px(default_emu)+ val = elem.attrib.get(attr)+ if val is None:+ return emu_to_px(default_emu)+ try:+ return emu_to_px(int(val))+ except ValueError:+ return emu_to_px(default_emu)+++def _parse_paragraphs(+ tx_body: ET.Element,+ palette: ColorPalette | None,+ theme_fonts: dict[str, str],+) -> list[TextParagraph]:+ """Walk <a:p> children producing TextParagraph objects."""+ paragraphs: list[TextParagraph] = []++ for p_elem in tx_body.findall("a:p", NS):+ para = _parse_paragraph(p_elem, palette, theme_fonts)+ paragraphs.append(para)++ return paragraphs+++def _parse_paragraph(+ p_elem: ET.Element,+ palette: ColorPalette | None,+ theme_fonts: dict[str, str],+) -> TextParagraph:+ para = TextParagraph()++ p_pr = p_elem.find("a:pPr", NS)+ if p_pr is not None:+ para.align = p_pr.attrib.get("algn", "l")+ try:+ para.level = int(p_pr.attrib.get("lvl", "0"))+ except ValueError:+ para.level = 0+ try:+ para.margin_left_px = emu_to_px(int(p_pr.attrib.get("marL", "0")))+ except ValueError:+ para.margin_left_px = 0.0+ try:+ para.indent_px = emu_to_px(int(p_pr.attrib.get("indent", "0")))+ except ValueError:+ para.indent_px = 0.0+ ln_spc = p_pr.find("a:lnSpc", NS)+ if ln_spc is not None:+ spc_pct = ln_spc.find("a:spcPct", NS)+ if spc_pct is not None:+ try:+ para.line_height_ratio = float(spc_pct.attrib.get("val", "100000")) / 100000.0+ except ValueError:+ pass+ spc_bef = p_pr.find("a:spcBef/a:spcPts", NS)+ if spc_bef is not None:+ try:+ para.space_before_px = hundredths_pt_to_px(int(spc_bef.attrib.get("val", "0")))+ except ValueError:+ pass+ spc_aft = p_pr.find("a:spcAft/a:spcPts", NS)+ if spc_aft is not None:+ try:+ para.space_after_px = hundredths_pt_to_px(int(spc_aft.attrib.get("val", "0")))+ except ValueError:+ pass++ # Bullet+ para.bullet_prefix = _resolve_bullet_prefix(p_pr)++ # Default endParaRPr style (applies if a run has no rPr)+ end_rpr = p_elem.find("a:endParaRPr", NS)++ for child in list(p_elem):+ if not isinstance(child.tag, str):+ continue+ local = child.tag.split("}", 1)[-1]+ if local == "r":+ rpr = child.find("a:rPr", NS)+ text_elem = child.find("a:t", NS)+ text = text_elem.text or "" if text_elem is not None else ""+ run = _build_run(text, rpr, end_rpr, palette, theme_fonts)+ para.runs.append(run)+ elif local == "br":+ para.runs.append(TextRun(+ text="", font_size_px=DEFAULT_FONT_SIZE_PX,+ font_family="sans-serif", fill=DEFAULT_FILL_HEX,+ is_break=True,+ ))+ elif local == "fld":+ # Field (datetime / slidenum). Use the literal a:t fallback.+ rpr = child.find("a:rPr", NS)+ text_elem = child.find("a:t", NS)+ text = text_elem.text or "" if text_elem is not None else ""+ if text:+ run = _build_run(text, rpr, end_rpr, palette, theme_fonts)+ para.runs.append(run)++ return para+++def _build_run(+ text: str,+ rpr: ET.Element | None,+ end_rpr: ET.Element | None,+ palette: ColorPalette | None,+ theme_fonts: dict[str, str],+) -> TextRun:+ """Resolve a single <a:r> run from its rPr (with endParaRPr as default)."""+ # font-size: rPr@sz; default 1800 (18pt = 24px)+ sz = _attr_chain((rpr, end_rpr), "sz")+ font_size_px = hundredths_pt_to_px(sz, DEFAULT_FONT_SIZE_PX)++ # Bold / italic+ bold = _attr_chain((rpr, end_rpr), "b") == "1"+ italic = _attr_chain((rpr, end_rpr), "i") == "1"++ # Underline / strike+ u_val = _attr_chain((rpr, end_rpr), "u")+ underline = u_val not in (None, "", "none")+ strike_val = _attr_chain((rpr, end_rpr), "strike")+ strikethrough = strike_val in ("sngStrike", "dblStrike")++ # Letter spacing (rPr@spc, in 1/100 pt)+ spc = _attr_chain((rpr, end_rpr), "spc")+ letter_spacing_px = 0.0+ if spc is not None:+ try:+ letter_spacing_px = float(spc) / 100.0 * 4.0 / 3.0 # pt -> px+ except ValueError:+ pass++ # Color+ fill = DEFAULT_FILL_HEX+ fill_opacity = 1.0+ color_source = None+ for src in (rpr, end_rpr):+ if src is None:+ continue+ solid = src.find("a:solidFill", NS)+ if solid is not None:+ color_source = solid+ break+ if color_source is not None:+ color_elem = find_color_elem(color_source)+ hex_, alpha = resolve_color(color_elem, palette)+ if hex_:+ fill = hex_+ fill_opacity = alpha++ # Font typeface+ latin_face = _typeface(rpr, "latin") or _typeface(end_rpr, "latin")+ ea_face = _typeface(rpr, "ea") or _typeface(end_rpr, "ea")+ cs_face = _typeface(rpr, "cs") or _typeface(end_rpr, "cs")++ # Resolve theme refs (e.g. typeface="+mn-lt" / "+mj-ea")+ latin_face = _resolve_theme_typeface(latin_face, theme_fonts)+ ea_face = _resolve_theme_typeface(ea_face, theme_fonts)+ cs_face = _resolve_theme_typeface(cs_face, theme_fonts)++ font_family = _build_font_stack(latin_face, ea_face, cs_face)++ return TextRun(+ text=text,+ font_size_px=font_size_px,+ font_family=font_family,+ fill=fill,+ fill_opacity=fill_opacity,+ bold=bold,+ italic=italic,+ underline=underline,+ strikethrough=strikethrough,+ letter_spacing_px=letter_spacing_px,+ )+++def _attr_chain(sources: tuple[ET.Element | None, ...], attr: str) -> str | None:+ """Return the first non-empty value of `attr` from any source element."""+ for src in sources:+ if src is None:+ continue+ v = src.attrib.get(attr)+ if v is not None:+ return v+ return None+++def _typeface(rpr: ET.Element | None, child_tag: str) -> str | None:+ if rpr is None:+ return None+ elem = rpr.find(f"a:{child_tag}", NS)+ if elem is None:+ return None+ val = elem.attrib.get("typeface")+ return val or None+++def _resolve_theme_typeface(face: str | None, theme_fonts: dict[str, str]) -> str | None:+ """Theme references look like '+mj-lt' (major latin) / '+mn-ea' (minor EA)."""+ if not face or not face.startswith("+"):+ return face+ code = face[1:]+ if code == "mj-lt":+ return theme_fonts.get("majorLatin") or face+ if code == "mn-lt":+ return theme_fonts.get("minorLatin") or face+ if code == "mj-ea":+ return theme_fonts.get("majorEastAsia") or theme_fonts.get("majorLatin") or face+ if code == "mn-ea":+ return theme_fonts.get("minorEastAsia") or theme_fonts.get("minorLatin") or face+ return face+++def _build_font_stack(latin: str | None, ea: str | None, cs: str | None) -> str:+ """Build a CSS font-family stack: original PPT names first, then fallbacks."""+ parts: list[str] = []+ seen: set[str] = set()+ for face in (latin, ea, cs):+ if face and face not in seen:+ parts.append(_quote_font(face))+ seen.add(face)+ # Generic fallback so the browser can render even if PPT fonts are absent.+ parts.append("sans-serif")+ return ", ".join(parts)+++def _quote_font(name: str) -> str:+ """Quote a font name if it contains spaces or non-ASCII chars.++ Uses XML entity-escaped double quotes (") so the resulting CSS string+ survives being embedded inside an SVG attribute that itself uses double+ quotes. CSS parsers accept the unescaped form after attribute parsing.+ """+ if any(c.isspace() or ord(c) > 127 for c in name):+ return f""{name}""+ return name+++def _resolve_bullet_prefix(p_pr: ET.Element) -> str:+ """Render bullet glyphs / numbering as a literal text prefix."""+ bu_none = p_pr.find("a:buNone", NS)+ if bu_none is not None:+ return ""+ bu_char = p_pr.find("a:buChar", NS)+ if bu_char is not None:+ ch = bu_char.attrib.get("char", "•")+ return f"{ch} "+ bu_auto = p_pr.find("a:buAutoNum", NS)+ if bu_auto is not None:+ # Type-aware numbering (arabicPeriod / romanLcParenR / etc.) is too+ # ambiguous without paragraph history; use a placeholder.+ return "• "+ return ""+++# ---------------------------------------------------------------------------+# Layout / emission+# ---------------------------------------------------------------------------++def _has_visible_text(paragraphs: list[TextParagraph]) -> bool:+ for p in paragraphs:+ for r in p.runs:+ if r.text.strip():+ return True+ return False+++# ---------------------------------------------------------------------------+# Word-wrap / text measurement+# ---------------------------------------------------------------------------++def _is_cjk(ch: str) -> bool:+ """Check if a character is CJK (Chinese/Japanese/Korean) or full-width."""+ cp = ord(ch)+ return (0x4E00 <= cp <= 0x9FFF or 0x3400 <= cp <= 0x4DBF or+ 0x2E80 <= cp <= 0x2EFF or 0x3000 <= cp <= 0x303F or+ 0xFF00 <= cp <= 0xFFEF or 0xF900 <= cp <= 0xFAFF or+ 0x20000 <= cp <= 0x2A6DF)+++def _char_width(ch: str, font_size: float, bold: bool) -> float:+ """Estimate a single character's rendered width in pixels.++ Mirrors svg_to_pptx/drawingml_utils.estimate_text_width so wrapping breaks+ align with the same heuristic used to estimate text-box sizes elsewhere.+ """+ if _is_cjk(ch):+ w = font_size # CJK is approximately 1em per glyph+ elif ch == ' ':+ w = font_size * 0.3+ elif ch in 'mMwWOQ':+ w = font_size * 0.75+ elif ch in 'iIlj1!|':+ w = font_size * 0.3+ else:+ w = font_size * 0.55+ if bold:+ w *= 1.05+ return w+++def _estimate_run_width(text: str, run: TextRun) -> float:+ return sum(_char_width(c, run.font_size_px, run.bold) for c in text) * 1.05+++def _find_break_point(+ text: str, start: int, max_width: float, run: TextRun,+) -> tuple[int, float]:+ """Find the longest prefix of text[start:] that fits in max_width.++ Returns (end_index, used_width). Prefers breaking after whitespace, after+ CJK characters, or after hyphens. If even the first character doesn't fit,+ returns (start, 0.0) — the caller should flush the current line first.+ """+ cur_w = 0.0+ last_break = start+ last_break_w = 0.0++ for i in range(start, len(text)):+ ch = text[i]+ ch_w = _char_width(ch, run.font_size_px, run.bold)+ if cur_w + ch_w > max_width:+ if last_break > start:+ return last_break, last_break_w+ return start, 0.0+ cur_w += ch_w+ # Update last_break point+ if ch.isspace() or _is_cjk(ch) or ch in "-—、,。!?:;":+ last_break = i + 1+ last_break_w = cur_w+ # Whole rest fits+ return len(text), cur_w+++def _wrap_paragraph_into_lines(+ para: TextParagraph,+ max_width: float,+) -> list[list[TextRun]]:+ """Split a paragraph's runs into display lines respecting `max_width`.++ Each line is a list of (possibly truncated) TextRuns. Explicit a:br runs+ force a new line. When max_width is +inf the original runs are returned+ unchanged (one logical line per a:br segment).++ Bullet prefix is prepended to the first non-empty run if present.+ """+ lines: list[list[TextRun]] = [[]]+ cur_w = 0.0++ if para.bullet_prefix and para.runs:+ first_run = next((r for r in para.runs if not r.is_break), None)+ if first_run is not None:+ bullet_run = _copy_run(first_run, text=para.bullet_prefix)+ lines[-1].append(bullet_run)+ cur_w = _estimate_run_width(para.bullet_prefix, bullet_run)++ for run in para.runs:+ if run.is_break:+ lines.append([])+ cur_w = 0.0+ continue+ if not run.text:+ continue+ text = run.text+ i = 0+ while i < len(text):+ remaining = text[i:]+ avail = max_width - cur_w+ if avail <= 0 and lines[-1]:+ # Line is full; start a new one+ lines.append([])+ cur_w = 0.0+ avail = max_width++ end, used = _find_break_point(remaining, 0, avail, run)+ if end == 0:+ # Nothing fits even from a fresh line — force one char to avoid+ # an infinite loop.+ if lines[-1]:+ lines.append([])+ cur_w = 0.0+ continue+ end = 1+ used = _char_width(remaining[0], run.font_size_px, run.bold)++ chunk = remaining[:end]+ lines[-1].append(_copy_run(run, text=chunk))+ cur_w += used+ i += end++ if i < len(text):+ # More to render — wrap to next line+ lines.append([])+ cur_w = 0.0++ return lines+++def _copy_run(run: TextRun, *, text: str) -> TextRun:+ return TextRun(+ text=text,+ font_size_px=run.font_size_px,+ font_family=run.font_family,+ fill=run.fill,+ fill_opacity=run.fill_opacity,+ bold=run.bold,+ italic=run.italic,+ underline=run.underline,+ strikethrough=run.strikethrough,+ letter_spacing_px=run.letter_spacing_px,+ )+++def _paragraph_height_from_lines(p: TextParagraph,+ lines: list[list[TextRun]]) -> float:+ """Total px height after wrapping. Each line uses its own max font size."""+ if not lines:+ return DEFAULT_FONT_SIZE_PX * p.line_height_ratio+ height = 0.0+ for line in lines:+ max_font = max((r.font_size_px for r in line), default=DEFAULT_FONT_SIZE_PX)+ height += max_font * p.line_height_ratio+ return height+++def _paragraph_height(p: TextParagraph) -> float:+ """Legacy helper kept for callers that don't pre-wrap (currently unused)."""+ lines = 1+ max_font = 0.0+ for r in p.runs:+ if r.is_break:+ lines += 1+ continue+ max_font = max(max_font, r.font_size_px)+ if max_font == 0.0:+ max_font = DEFAULT_FONT_SIZE_PX+ return lines * max_font * p.line_height_ratio+++def _emit_paragraph(+ para: TextParagraph,+ lines: list[list[TextRun]],+ inner_x: float, inner_w: float,+ top_y: float,+) -> str:+ """Render a paragraph (already split into lines) as one <text> element.++ Each pre-wrapped display line becomes a sequence of <tspan>s: the first+ tspan on a line carries the explicit x and dy (line-height advance);+ subsequent tspans on the same line inherit x.+ """+ align = para.align+ if align == "ctr":+ anchor_x = inner_x + inner_w / 2.0+ text_anchor = "middle"+ elif align == "r":+ anchor_x = inner_x + inner_w+ text_anchor = "end"+ else: # 'l' / 'just' / 'dist' / unknown+ anchor_x = inner_x + para.indent_px + para.margin_left_px+ text_anchor = "start"++ if not lines or all(not line for line in lines):+ return ""++ # First non-empty line drives the text-level baseline + default style+ first_line_idx = next((i for i, ln in enumerate(lines) if ln), 0)+ first_line = lines[first_line_idx]+ first_run = first_line[0] if first_line else None+ first_font = first_run.font_size_px if first_run else DEFAULT_FONT_SIZE_PX+ first_baseline = top_y + 0.85 * first_font++ spans: list[str] = []+ for line_idx, line in enumerate(lines):+ if not line:+ # Blank line (e.g. consecutive a:br): still advance baseline+ spans.append(+ f'<tspan x="{fmt_num(anchor_x)}" '+ f'dy="{fmt_num(first_font * para.line_height_ratio)}"></tspan>'+ )+ continue+ line_font = max(r.font_size_px for r in line)+ for run_idx, run in enumerate(line):+ attrs = _run_tspan_attrs(run)+ if run_idx == 0 and line_idx > 0:+ # Start-of-line tspan: position via x + dy+ spans.append(+ f'<tspan x="{fmt_num(anchor_x)}" '+ f'dy="{fmt_num(line_font * para.line_height_ratio)}"'+ f'{attrs}>{_xml_escape(run.text)}</tspan>'+ )+ else:+ spans.append(+ f"<tspan{attrs}>{_xml_escape(run.text)}</tspan>"+ )++ base_attrs = _text_base_attrs(first_run, anchor_x, first_baseline, text_anchor)+ return f"<text{base_attrs}>{''.join(spans)}</text>"+++def _text_base_attrs(run: TextRun | None, x: float, y: float,+ text_anchor: str) -> str:+ parts = [+ f'x="{fmt_num(x)}"',+ f'y="{fmt_num(y)}"',+ f'text-anchor="{text_anchor}"',+ ]+ if run is None:+ return " " + " ".join(parts)+ parts.append(f'font-family="{run.font_family}"')+ parts.append(f'font-size="{fmt_num(run.font_size_px)}"')+ parts.append(f'fill="{run.fill}"')+ if run.fill_opacity < 1.0:+ parts.append(f'fill-opacity="{fmt_num(run.fill_opacity, 4)}"')+ if run.bold:+ parts.append('font-weight="bold"')+ if run.italic:+ parts.append('font-style="italic"')+ if run.underline and run.strikethrough:+ parts.append('text-decoration="underline line-through"')+ elif run.underline:+ parts.append('text-decoration="underline"')+ elif run.strikethrough:+ parts.append('text-decoration="line-through"')+ if run.letter_spacing_px:+ parts.append(f'letter-spacing="{fmt_num(run.letter_spacing_px)}"')+ return " " + " ".join(parts)+++def _run_tspan_attrs(run: TextRun) -> str:+ """Per-run overrides on a <tspan>. Only emit attributes that differ from+ the run that drove the parent <text> (we keep things simple: emit only+ overrides that can plausibly change run-to-run, never re-emit common+ defaults). For v1 we just always emit fill / font-size / weight to be+ safe — tspan inherits when omitted, so callers can simplify later.+ """+ parts = [+ f'fill="{run.fill}"',+ f'font-size="{fmt_num(run.font_size_px)}"',+ ]+ if run.fill_opacity < 1.0:+ parts.append(f'fill-opacity="{fmt_num(run.fill_opacity, 4)}"')+ if run.bold:+ parts.append('font-weight="bold"')+ if run.italic:+ parts.append('font-style="italic"')+ if run.underline and run.strikethrough:+ parts.append('text-decoration="underline line-through"')+ elif run.underline:+ parts.append('text-decoration="underline"')+ elif run.strikethrough:+ parts.append('text-decoration="line-through"')+ if run.letter_spacing_px:+ parts.append(f'letter-spacing="{fmt_num(run.letter_spacing_px)}"')+ return " " + " ".join(parts)+++def _xml_escape(text: str) -> str:+ return (text.replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+ .replace('"', """))