AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
fix(pptx-to-svg): recover malformed source constructs locally
hugohe36a70ad672ddc
diff --git a/skills/ppt-master/scripts/beautify_identity.py b/skills/ppt-master/scripts/beautify_identity.pyindex b5aaac00..43a82561 100644--- a/skills/ppt-master/scripts/beautify_identity.py+++ b/skills/ppt-master/scripts/beautify_identity.py@@ -184,7 +184,7 @@ def extract_identity(pptx_path: Path) -> dict:first = pkg.get_slide(1)master = first.master if first else Nonetheme = pkg.resolve_theme(master)- palette_resolver = ColorPalette(master, theme)+ palette_resolver = ColorPalette(master, theme, strict=False)# Presentation-level scheme names; ColorPalette applies clrMap + aliases.scheme = {diff --git a/skills/ppt-master/scripts/pptx_template_import.py b/skills/ppt-master/scripts/pptx_template_import.pyindex 5bfab469..48b32d49 100644--- a/skills/ppt-master/scripts/pptx_template_import.py+++ b/skills/ppt-master/scripts/pptx_template_import.py@@ -23,6 +23,8 @@ from __future__ import annotationsimport argparseimport jsonfrom pathlib import Path+from xml.etree import ElementTree as ET+from zipfile import BadZipFilefrom console_encoding import configure_utf8_stdiofrom template_import.manifest import build_manifest@@ -157,7 +159,11 @@ def main() -> int:inheritance_mode=args.inheritance_mode,asset_name_map=manifest.get("assets", {}).get("assetMap", {}) if manifest else {},)- result = convert_pptx_to_svg(pptx_path, output_dir, options)+ try:+ result = convert_pptx_to_svg(pptx_path, output_dir, options)+ except (BadZipFile, ET.ParseError, OSError, RuntimeError, ValueError) as exc:+ print(f"Error: failed to convert PPTX template source: {exc}")+ return 1total_bytes = sum(len(art.svg.encode("utf-8")) for art in result.slides)print(f"Inheritance mode: {args.inheritance_mode}")@@ -168,6 +174,11 @@ def main() -> int:print("Inheritance graph: svg/inheritance.json")if result.flat_slides:print(f"Flat companion slides: {len(result.flat_slides)} (svg-flat/)")+ if result.diagnostics:+ print(+ f"Source recovery warnings: {len(result.diagnostics)} "+ "(conversion-report.json)"+ )print(f"SVG bytes (primary): {total_bytes}")print(f"Output directory: {output_dir}")if native_structure is not None:diff --git a/skills/ppt-master/scripts/pptx_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg.pyindex 98679313..60340ee4 100644--- a/skills/ppt-master/scripts/pptx_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg.py@@ -5,6 +5,7 @@ Usage:python3 pptx_to_svg.py <pptx_file> [-o <output_dir>] [--embed-images][--media-subdir <name>] [--keep-hidden][--inheritance-mode {both,layered,flat}]+ [--strict]Output structure (default --inheritance-mode both):<output_dir>/@@ -27,6 +28,7 @@ import argparseimport sysfrom pathlib import Pathfrom xml.etree import ElementTree as ET+from zipfile import BadZipFile# Allow running this script from anywheresys.path.insert(0, str(Path(__file__).resolve().parent))@@ -95,6 +97,14 @@ def parse_args() -> argparse.Namespace:"self-contained slides under svg/ for backward compatibility."),)+ parser.add_argument(+ "--strict",+ action="store_true",+ help=(+ "Stop on the first unsupported/malformed source construct instead "+ "of the default tolerant conversion with diagnostics"+ ),+ )return parser.parse_args()@@ -119,9 +129,14 @@ def main() -> int:embed_images=args.embed_images,keep_hidden=args.keep_hidden,inheritance_mode=args.inheritance_mode,+ strict=args.strict,)- result = convert_pptx_to_svg(pptx_path, output_dir, options)+ try:+ result = convert_pptx_to_svg(pptx_path, output_dir, options)+ except (BadZipFile, ET.ParseError, OSError, RuntimeError, ValueError) as exc:+ print(f"Error: PPTX-to-SVG conversion failed: {exc}", file=sys.stderr)+ return 1print(f"Source: {pptx_path.name}")print(f"Canvas: {result.canvas_px[0]:.0f} x {result.canvas_px[1]:.0f} px")@@ -132,6 +147,30 @@ def main() -> int: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)}")+ if result.diagnostics:+ print(+ f"Warning: {len(result.diagnostics)} source construct(s) were "+ "normalized, omitted, or replaced; see conversion-report.json.",+ file=sys.stderr,+ )+ for item in result.diagnostics[:20]:+ location = (+ f"slide {item.slide_index}"+ if item.slide_index+ else item.part_path+ )+ shape = item.shape_name or item.shape_id+ if shape:+ location = f"{location}, {shape}" if location else shape+ print(+ f" {location or 'package'}: {item.code}: {item.message}",+ file=sys.stderr,+ )+ if len(result.diagnostics) > 20:+ print(+ f" ... and {len(result.diagnostics) - 20} more",+ file=sys.stderr,+ )reconstruction_only = _reconstruction_only_graphics(result)if reconstruction_only:print(@@ -149,6 +188,7 @@ def main() -> int:file=sys.stderr,)print(f"Output: {output_dir}")+ print(f"Conversion report: {output_dir / 'conversion-report.json'}")return 0diff --git a/skills/ppt-master/scripts/pptx_to_svg/color_resolver.py b/skills/ppt-master/scripts/pptx_to_svg/color_resolver.pyindex 0ca9f32a..4785377c 100644--- a/skills/ppt-master/scripts/pptx_to_svg/color_resolver.py+++ b/skills/ppt-master/scripts/pptx_to_svg/color_resolver.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport colorsysimport re+from collections.abc import Callablefrom xml.etree import ElementTree as ETfrom .emu_units import NS@@ -223,13 +224,80 @@ class ColorPalette:names (lt1/dk1) — this is rarely overridden but must be honored."""- def __init__(self, master: PartRef | None, theme: PartRef | None) -> None:+ def __init__(+ self,+ master: PartRef | None,+ theme: PartRef | None,+ *,+ strict: bool = True,+ diagnostic_sink: Callable[[str, str, str], None] | None = None,+ ) -> None:self.scheme: dict[str, str] = {}self.clr_map: dict[str, str] = {}+ self.strict = strict+ self.diagnostic_sink = diagnostic_sinkif theme is not None:- self._load_scheme(theme)+ try:+ self._load_scheme(theme)+ except ValueError as exc:+ if strict:+ raise+ self.scheme.clear()+ self._diagnose(+ "theme-color-scheme-normalized",+ str(exc),+ "read recognized theme color slots",+ )+ self._load_scheme_compatible(theme)if master is not None:- self._load_clr_map(master)+ try:+ self._load_clr_map(master)+ except ValueError as exc:+ if strict:+ raise+ self.clr_map.clear()+ self._diagnose(+ "theme-color-map-normalized",+ str(exc),+ "read recognized color-map entries",+ )+ self._load_clr_map_compatible(master)++ def _diagnose(self, code: str, message: str, fallback: str) -> None:+ if self.diagnostic_sink is not None:+ self.diagnostic_sink(code, message, fallback)++ def _load_scheme_compatible(self, theme: PartRef) -> None:+ """Read recognizable theme slots without requiring canonical wrapper XML."""+ clr_scheme = theme.xml.find(".//a:clrScheme", NS)+ if clr_scheme is None:+ return+ for slot in clr_scheme:+ if not isinstance(slot.tag, str):+ continue+ name = slot.tag.rsplit("}", 1)[-1]+ color = next(+ (+ child+ for child in slot+ if isinstance(child.tag, str)+ and child.tag.rsplit("}", 1)[-1] in COLOR_TAGS+ ),+ None,+ )+ hex_, _alpha = resolve_color(color, None, strict=False)+ if hex_ is not None:+ self.scheme[name] = hex_[1:]++ def _load_clr_map_compatible(self, master: PartRef) -> None:+ """Read valid known clrMap entries and ignore unrelated extensions."""+ clr_map = master.xml.find("p:clrMap", NS)+ if clr_map is None:+ return+ for source in _COLOR_MAP_SOURCES:+ target = clr_map.attrib.get(source)+ if target in _THEME_SCHEME_SLOTS:+ self.clr_map[source] = targetdef _load_scheme(self, theme: PartRef) -> None:theme_root = theme.xml@@ -395,6 +463,7 @@ def resolve_color(palette: ColorPalette | None,*,placeholder_hex: str | None = None,+ strict: bool | None = None,) -> tuple[str | None, float]:"""Resolve a color element to (#RRGGBB, alpha).@@ -410,6 +479,45 @@ def resolve_color(if color_elem is None:return None, 1.0+ effective_strict = palette.strict if strict is None and palette is not None else strict+ if effective_strict is None:+ effective_strict = True+ try:+ return _resolve_color_closed(+ color_elem,+ palette,+ placeholder_hex=placeholder_hex,+ )+ except ValueError as exc:+ if effective_strict:+ raise+ if palette is not None:+ palette._diagnose(+ "color-structure-normalized",+ str(exc),+ "retain recognized color attributes and modifiers",+ )+ compatible = _compatible_color_element(color_elem)+ if compatible is None:+ return None, 1.0+ try:+ return _resolve_color_closed(+ compatible,+ palette,+ placeholder_hex=placeholder_hex,+ )+ except (KeyError, TypeError, ValueError):+ return None, 1.0+++def _resolve_color_closed(+ color_elem: ET.Element,+ palette: ColorPalette | None,+ *,+ placeholder_hex: str | None = None,+) -> tuple[str | None, float]:+ """Resolve the registered closed DrawingML color grammar."""+tag = color_elem.tag.split("}", 1)[-1]base_hex: str | None = Nonealpha: float = 1.0@@ -439,6 +547,48 @@ def resolve_color(return f"#{base_hex}", alpha+def _compatible_color_element(color_elem: ET.Element) -> ET.Element | None:+ """Return a canonical clone containing only recognized color semantics."""+ if not isinstance(color_elem.tag, str):+ return None+ tag = color_elem.tag.rsplit("}", 1)[-1]+ base_attributes = {+ "srgbClr": ("val",),+ "schemeClr": ("val",),+ "sysClr": ("val", "lastClr"),+ "prstClr": ("val",),+ "hslClr": ("hue", "sat", "lum"),+ "scrgbClr": ("r", "g", "b"),+ }.get(tag)+ if base_attributes is None or color_elem.tag != f"{{{NS['a']}}}{tag}":+ return None++ clone = ET.Element(color_elem.tag)+ for attr in base_attributes:+ value = color_elem.attrib.get(attr)+ if value is not None:+ clone.set(attr, value)++ for child in color_elem:+ if not isinstance(child.tag, str):+ continue+ name = child.tag.rsplit("}", 1)[-1]+ if child.tag != f"{{{NS['a']}}}{name}":+ continue+ if name in _COLOR_MODIFIER_FLAG_NAMES:+ clone.append(ET.Element(child.tag))+ continue+ if name not in _COLOR_MODIFIER_PERCENT_RANGES and name != "hueOff":+ continue+ value = child.attrib.get("val")+ if value is None:+ continue+ modifier = ET.Element(child.tag)+ modifier.set("val", value)+ clone.append(modifier)+ return clone++def _srgb_hex_value(color_elem: ET.Element) -> str:"""Parse the closed six-digit DrawingML sRGB base token."""children = list(color_elem)diff --git a/skills/ppt-master/scripts/pptx_to_svg/converter.py b/skills/ppt-master/scripts/pptx_to_svg/converter.pyindex 0b7950e6..8e92a8e4 100644--- a/skills/ppt-master/scripts/pptx_to_svg/converter.py+++ b/skills/ppt-master/scripts/pptx_to_svg/converter.py@@ -15,11 +15,13 @@ from __future__ import annotationsimport jsonimport re+from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPathfrom .color_resolver import ColorPalettefrom .emu_units import NS+from .import_diagnostics import ImportDiagnostic, append_diagnosticfrom .ooxml_loader import (OoxmlPackage,PartRef,@@ -44,8 +46,18 @@ def _extract_theme_info(if not isinstance(child.tag, str):continuename = child.tag.split("}", 1)[-1]- color_elem = find_color_elem(child)- hex_, _ = resolve_color(color_elem, palette)+ try:+ color_elem = find_color_elem(child)+ hex_, _ = resolve_color(color_elem, palette)+ except ValueError as exc:+ if palette.strict:+ raise+ palette._diagnose(+ "theme-summary-color-omitted",+ str(exc),+ "omit only this malformed theme-summary color",+ )+ continueif hex_:colors[name] = hex_@@ -90,6 +102,8 @@ class ConvertOptions:- "flat": inline the inherited shapes visible under the source``showMasterSp`` flags. Used by svg_to_pptx round-trip and any callerthat wants self-contained slides (preview pages, screenshot pipelines).+ strict: stop on the first unsupported or malformed source construct.+ Default False keeps usable content and records structured diagnostics."""media_subdir: str = "assets"@@ -97,6 +111,7 @@ class ConvertOptions:keep_hidden: bool = Falseinheritance_mode: str = "both"asset_name_map: dict[str, str] = field(default_factory=dict)+ strict: bool = False@dataclass@@ -143,6 +158,53 @@ class ConvertResult:masters: list[PartArtifact] = field(default_factory=list)flat_slides: list[SlideArtifact] = field(default_factory=list)master_themes: dict[str, dict[str, object]] = field(default_factory=dict)+ diagnostics: list[ImportDiagnostic] = field(default_factory=list)+ source_file: str = ""+ strict: bool = False+++def _palette_diagnostic_sink(+ result: ConvertResult,+ *,+ part_path: str,+ slide_index: int | None = None,+) -> Callable[[str, str, str], None]:+ """Build a package-level diagnostic sink for palette initialization."""+ def _record(code: str, message: str, fallback: str) -> None:+ append_diagnostic(+ result.diagnostics,+ ImportDiagnostic(+ code=code,+ message=message,+ fallback=fallback,+ part_path=part_path,+ slide_index=slide_index,+ ),+ )++ return _record+++def _make_palette(+ master: PartRef | None,+ theme: PartRef | None,+ options: ConvertOptions,+ result: ConvertResult,+ *,+ part_path: str,+ slide_index: int | None = None,+) -> ColorPalette:+ """Create one strict or tolerant palette with structured diagnostics."""+ return ColorPalette(+ master,+ theme,+ strict=options.strict,+ diagnostic_sink=_palette_diagnostic_sink(+ result,+ part_path=part_path,+ slide_index=slide_index,+ ),+ )# ---------------------------------------------------------------------------@@ -173,7 +235,10 @@ def convert_pptx_to_svg()emit_layered = options.inheritance_mode in {"layered", "both"}emit_flat = options.inheritance_mode in {"flat", "both"}- result = ConvertResult()+ result = ConvertResult(+ source_file=pptx_path.name,+ strict=options.strict,+ )with OoxmlPackage(pptx_path) as pkg:result.canvas_px = pkg.slide_size_px@@ -183,13 +248,25 @@ def convert_pptx_to_svg(first_slide = pkg.get_slide(1)default_master = first_slide.master if first_slide else Nonedefault_theme = pkg.resolve_theme(default_master)- palette = ColorPalette(default_master, default_theme)+ palette = _make_palette(+ default_master,+ default_theme,+ options,+ result,+ part_path=default_theme.path if default_theme is not None else "",+ )if default_theme is not None:result.theme_colors, result.theme_fonts = _extract_theme_info(default_theme, palette)for master in pkg.iter_all_masters():theme = pkg.resolve_theme(master) or default_theme- pal = ColorPalette(master, theme)+ pal = _make_palette(+ master,+ theme,+ options,+ result,+ part_path=master.path,+ )colors, fonts = _extract_theme_info(theme, pal) if theme is not None else ({}, {})result.master_themes[master.path] = {"themePath": theme.path if theme is not None else None,@@ -203,20 +280,44 @@ def convert_pptx_to_svg(primary_mode = "layered" if emit_layered else "flat"for slide in pkg.iter_slides():slide_theme = pkg.resolve_theme(slide.master) or default_theme- slide_palette = ColorPalette(slide.master, slide_theme)+ slide_palette = _make_palette(+ slide.master,+ slide_theme,+ options,+ result,+ part_path=slide.part.path,+ slide_index=slide.index,+ )_colors, slide_fonts = _extract_theme_info(slide_theme, slide_palette) if slide_theme is not None else ({}, result.theme_fonts)artifact = _convert_slide(- pkg, slide, slide_palette, options, slide_fonts,+ pkg,+ slide,+ slide_palette,+ options,+ result.diagnostics,+ slide_fonts,inheritance_mode=primary_mode,)result.slides.append(artifact)if emit_layered and emit_flat:for slide in pkg.iter_slides():slide_theme = pkg.resolve_theme(slide.master) or default_theme- slide_palette = ColorPalette(slide.master, slide_theme)+ slide_palette = _make_palette(+ slide.master,+ slide_theme,+ options,+ result,+ part_path=slide.part.path,+ slide_index=slide.index,+ )_colors, slide_fonts = _extract_theme_info(slide_theme, slide_palette) if slide_theme is not None else ({}, result.theme_fonts)artifact = _convert_slide(- pkg, slide, slide_palette, options, slide_fonts,+ pkg,+ slide,+ slide_palette,+ options,+ result.diagnostics,+ slide_fonts,inheritance_mode="flat",)result.flat_slides.append(artifact)@@ -236,6 +337,7 @@ def _convert_slide(slide: SlideRef,palette: ColorPalette,options: ConvertOptions,+ diagnostics: list[ImportDiagnostic],theme_fonts: dict[str, str] | None = None,*,inheritance_mode: str | None = None,@@ -260,6 +362,8 @@ def _convert_slide(keep_hidden=options.keep_hidden,inheritance_mode=mode,asset_name_map=options.asset_name_map,+ strict=options.strict,+ diagnostics=diagnostics,)return SlideArtifact(index=slide.index,@@ -301,18 +405,30 @@ def _convert_inheritance_parts(for seq, part in enumerate(seen_masters.values(), start=1):theme = pkg.resolve_theme(part) or default_theme- palette = ColorPalette(part, theme)+ palette = _make_palette(+ part,+ theme,+ options,+ result,+ part_path=part.path,+ )_colors, fonts = _extract_theme_info(theme, palette) if theme is not None else ({}, result.theme_fonts)result.masters.append(_render_part(- pkg, part, palette, options, fonts,+ pkg, part, palette, options, result.diagnostics, fonts,role="master", seq=seq, theme_part=theme,))for seq, (layout, parent_master) in enumerate(layouts_with_parent, start=1):theme = pkg.resolve_theme(parent_master) or default_theme- palette = ColorPalette(parent_master, theme)+ palette = _make_palette(+ parent_master,+ theme,+ options,+ result,+ part_path=layout.path,+ )_colors, fonts = _extract_theme_info(theme, palette) if theme is not None else ({}, result.theme_fonts)result.layouts.append(_render_part(- pkg, layout, palette, options, fonts,+ pkg, layout, palette, options, result.diagnostics, fonts,role="layout", seq=seq, parent_master=parent_master,theme_part=theme,))@@ -323,6 +439,7 @@ def _render_part(part: PartRef,palette: ColorPalette,options: ConvertOptions,+ diagnostics: list[ImportDiagnostic],theme_fonts: dict[str, str],*,role: str,@@ -340,6 +457,8 @@ def _render_part(embed_images=options.embed_images,keep_hidden=options.keep_hidden,asset_name_map=options.asset_name_map,+ strict=options.strict,+ diagnostics=diagnostics,)stem = PurePosixPath(part.path).stem # e.g. "slideLayout3"safe_stem = re.sub(r"[^A-Za-z0-9_-]+", "_", stem).strip("_") or role@@ -414,6 +533,26 @@ def _write_artifacts(output_dir: Path, result: ConvertResult,target.write_text(art.svg, encoding="utf-8")_write_media(art.media_files)+ _write_conversion_report(output_dir, result)+++def _write_conversion_report(output_dir: Path, result: ConvertResult) -> None:+ """Write the user-visible tolerant-import report."""+ report = {+ "schemaVersion": 1,+ "source": result.source_file,+ "mode": "strict" if result.strict else "tolerant",+ "summary": {+ "slides": len(result.slides),+ "warnings": len(result.diagnostics),+ },+ "diagnostics": [item.to_dict() for item in result.diagnostics],+ }+ (output_dir / "conversion-report.json").write_text(+ json.dumps(report, ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )+def _write_inheritance_json(svg_dir: Path, result: ConvertResult) -> None:"""Record layered parentage plus source-owned shape-visibility booleans."""diff --git a/skills/ppt-master/scripts/pptx_to_svg/import_diagnostics.py b/skills/ppt-master/scripts/pptx_to_svg/import_diagnostics.pynew file mode 100644index 00000000..a6f10b97--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/import_diagnostics.py@@ -0,0 +1,37 @@+"""Structured diagnostics for tolerant PPTX-to-SVG import."""++from __future__ import annotations++from dataclasses import asdict, dataclass+++@dataclass(frozen=True)+class ImportDiagnostic:+ """Describe one source-owned construct that required import recovery."""++ code: str+ message: str+ fallback: str+ part_path: str = ""+ slide_index: int | None = None+ shape_id: str = ""+ shape_name: str = ""+ shape_kind: str = ""+ severity: str = "warning"++ def to_dict(self) -> dict[str, object]:+ """Return the stable JSON representation."""+ return {+ key: value+ for key, value in asdict(self).items()+ if value not in {"", None}+ }+++def append_diagnostic(+ diagnostics: list[ImportDiagnostic],+ diagnostic: ImportDiagnostic,+) -> None:+ """Append one diagnostic while suppressing duplicate layered/flat reports."""+ if diagnostic not in diagnostics:+ diagnostics.append(diagnostic)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.pyindex d876dd89..f9234c0c 100644--- a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py@@ -45,10 +45,18 @@ from pptx_effects import (from .color_resolver import ColorPalette, find_color_elem, resolve_colorfrom .chart_to_svg import CHART_URI, CHARTEX_URI, extract_native_chart_payloadfrom .custgeom_to_svg import convert_custom_geom-from .effect_to_svg import convert_effects, unsupported_target_effect_metadata+from .effect_to_svg import (+ EffectResult,+ convert_effects,+ unsupported_target_effect_metadata,+)from .emu_units import NS, Xfrm, fmt_num, format_canvas_px_from_emu-from .fill_to_svg import resolve_fill-from .ln_to_svg import resolve_stroke+from .fill_to_svg import FillResult, resolve_fill+from .import_diagnostics import (+ ImportDiagnostic,+ append_diagnostic,+)+from .ln_to_svg import StrokeResult, resolve_strokefrom .ooxml_loader import (OoxmlPackage,PartRef,@@ -88,9 +96,13 @@ class AssemblyContext:media_subdir: str = "assets"embed_images: bool = Falsekeep_hidden: bool = False+ strict: bool = Falsegroup_id_prefix: str = ""render_graphic_previews: bool = Trueasset_name_map: dict[str, str] = field(default_factory=dict)+ diagnostics: list[ImportDiagnostic] = field(default_factory=list)+ source_slide_index: int | None = None+ current_node: ShapeNode | None = None# Sequence counters (single-element lists so handlers can mutate)grad_seq: list[int] = field(default_factory=lambda: [0])@@ -103,6 +115,40 @@ class AssemblyContext:defs: list[str] = field(default_factory=list)media: dict[str, bytes] = field(default_factory=dict)+ def bind_palette(self) -> None:+ """Route tolerant color diagnostics through the current object context."""+ if self.palette is None:+ return+ self.palette.strict = self.strict+ self.palette.diagnostic_sink = self._diagnose_color++ def diagnose(+ self,+ code: str,+ message: str,+ fallback: str,+ *,+ node: ShapeNode | None = None,+ ) -> None:+ """Record one recoverable source-contract violation."""+ source_node = node or self.current_node+ append_diagnostic(+ self.diagnostics,+ ImportDiagnostic(+ code=code,+ message=message,+ fallback=fallback,+ part_path=self.slide_part.path,+ slide_index=self.source_slide_index,+ shape_id=source_node.spid if source_node is not None else "",+ shape_name=source_node.name if source_node is not None else "",+ shape_kind=source_node.kind if source_node is not None else "",+ ),+ )++ def _diagnose_color(self, code: str, message: str, fallback: str) -> None:+ self.diagnose(code, message, fallback)+# ---------------------------------------------------------------------------# Public entry@@ -119,6 +165,8 @@ def assemble_slide(keep_hidden: bool = False,inheritance_mode: str = "flat",asset_name_map: dict[str, str] | None = None,+ strict: bool = False,+ diagnostics: list[ImportDiagnostic] | None = None,) -> tuple[str, dict[str, bytes]]:"""Convert one slide to a complete SVG string + media files map.@@ -141,9 +189,13 @@ def assemble_slide(media_subdir=media_subdir,embed_images=embed_images,keep_hidden=keep_hidden,+ strict=strict,render_graphic_previews=(inheritance_mode == "flat"),asset_name_map=asset_name_map or {},+ diagnostics=diagnostics if diagnostics is not None else [],+ source_slide_index=slide.index,)+ ctx.bind_palette()canvas_w, canvas_h = pkg.slide_size_pxcanvas_w_token, canvas_h_token = (@@ -152,14 +204,24 @@ def assemble_slide(# Background (cSld/bg) — emit as the first body element.body_parts: list[str] = []- bg_xml = (- _emit_background(slide, ctx, canvas_w, canvas_h)- if inheritance_mode == "flat"- else _emit_part_background(- SlideRef(index=slide.index, part=slide.part, layout=None, master=slide.master),- ctx, canvas_w, canvas_h,+ try:+ bg_xml = (+ _emit_background(slide, ctx, canvas_w, canvas_h)+ if inheritance_mode == "flat"+ else _emit_part_background(+ SlideRef(index=slide.index, part=slide.part, layout=None, master=slide.master),+ ctx, canvas_w, canvas_h,+ ))- )+ except ValueError as exc:+ if strict:+ raise+ ctx.diagnose(+ "background-omitted",+ str(exc),+ "omit the unsupported background and continue the slide",+ )+ bg_xml = ""if bg_xml:body_parts.append(bg_xml)@@ -212,6 +274,8 @@ def assemble_part_solo(embed_images: bool = False,keep_hidden: bool = False,asset_name_map: dict[str, str] | None = None,+ strict: bool = False,+ diagnostics: list[ImportDiagnostic] | None = None,) -> tuple[str, dict[str, bytes]]:"""Render a single slideMaster or slideLayout part as a standalone SVG.@@ -241,10 +305,13 @@ def assemble_part_solo(media_subdir=media_subdir,embed_images=embed_images,keep_hidden=keep_hidden,+ strict=strict,group_id_prefix=f"{role}-",render_graphic_previews=False,asset_name_map=asset_name_map or {},+ diagnostics=diagnostics if diagnostics is not None else [],)+ ctx.bind_palette()canvas_w, canvas_h = pkg.slide_size_pxcanvas_w_token, canvas_h_token = (@@ -270,7 +337,17 @@ def assemble_part_solo(layout=None,master=master_for_theme,)- bg_xml = _emit_part_background(fake_slide, ctx, canvas_w, canvas_h)+ try:+ bg_xml = _emit_part_background(fake_slide, ctx, canvas_w, canvas_h)+ except ValueError as exc:+ if strict:+ raise+ ctx.diagnose(+ "background-omitted",+ str(exc),+ "omit the unsupported background and continue the part",+ )+ bg_xml = ""if bg_xml:body_parts.append(bg_xml)@@ -304,19 +381,59 @@ def assemble_part_solo(# ---------------------------------------------------------------------------def _convert_node(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:- if node.hidden and not ctx.keep_hidden:+ previous_node = ctx.current_node+ ctx.current_node = node+ try:+ 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 ""- 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 ""+ except ValueError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "object-replaced",+ str(exc),+ "replace only this object with a visible placeholder",+ node=node,+ )+ return _fallback_node_svg(node, ctx, top_level=top_level)+ finally:+ ctx.current_node = previous_node+++def _fallback_node_svg(+ node: ShapeNode,+ ctx: AssemblyContext,+ *,+ top_level: bool,+) -> str:+ """Keep one unsupported source object visible without aborting its deck."""+ if node.xfrm.w <= 0 or node.xfrm.h <= 0:+ return ""+ x = fmt_num(node.xfrm.x)+ y = fmt_num(node.xfrm.y)+ width = fmt_num(node.xfrm.w)+ height = fmt_num(node.xfrm.h)+ label = _xml_escape(node.name or f"Unsupported {node.kind}")+ inner = (+ f'<rect x="{x}" y="{y}" width="{width}" height="{height}" '+ 'fill="#F8FAFC" fill-opacity="0.72" stroke="#DC2626" '+ 'stroke-width="1" stroke-dasharray="6 4"/>'+ f'<text x="{fmt_num(node.xfrm.x + 8)}" '+ f'y="{fmt_num(node.xfrm.y + min(18, node.xfrm.h / 2))}" '+ f'font-size="12" fill="#991B1B">{label}</text>'+ )+ return _wrap_shape_group(inner, node, ctx, top_level=top_level)# ---------------------------------------------------------------------------@@ -333,15 +450,25 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->blip_fill_elem = sp_pr.find("a:blipFill", NS) if sp_pr is not None else Noneblip_image = ""if blip_fill_elem is not None:- blip_result = convert_blip_fill(- blip_fill_elem, node.xfrm, ctx.slide_part, ctx.pkg,- media_subdir=ctx.media_subdir,- embed_inline=ctx.embed_images,- asset_name_map=ctx.asset_name_map,- )- if blip_result.svg:- blip_image = _clip_blip_image(blip_result.svg, geom, ctx)- ctx.media.update(blip_result.media)+ try:+ blip_result = convert_blip_fill(+ blip_fill_elem, node.xfrm, ctx.slide_part, ctx.pkg,+ media_subdir=ctx.media_subdir,+ embed_inline=ctx.embed_images,+ asset_name_map=ctx.asset_name_map,+ )+ except ValueError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "image-fill-omitted",+ str(exc),+ "omit the image fill and retain shape geometry/text",+ )+ else:+ if blip_result.svg:+ blip_image = _clip_blip_image(blip_result.svg, geom, ctx)+ ctx.media.update(blip_result.media)# Text body (a:txBody)tx_body = node.xml.find("p:txBody", NS)@@ -368,29 +495,39 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -># Geometry (fill is "none" when blipFill is present, so only stroke draws)geom_xml = _build_geometry_xml(node, sp_pr, ctx, geom=geom)- text_default_fill = _resolve_text_style_default(node, ctx)- if tx_body is not None and is_vertical:- text_result = convert_vertical_txbody(- tx_body, node.xfrm, ctx.palette,- theme_fonts=ctx.theme_fonts,- slide_number=ctx.slide_number,- default_fill=text_default_fill,- default_font_size_px=DEFAULT_FONT_SIZE_PX,- fallback_lst_styles=node.inherited_lst_styles,- id_prefix=f"{ctx.group_id_prefix}txt",- id_seq=ctx.grad_seq,+ try:+ text_default_fill = _resolve_text_style_default(node, ctx)+ if tx_body is not None and is_vertical:+ text_result = convert_vertical_txbody(+ tx_body, node.xfrm, ctx.palette,+ theme_fonts=ctx.theme_fonts,+ slide_number=ctx.slide_number,+ default_fill=text_default_fill,+ default_font_size_px=DEFAULT_FONT_SIZE_PX,+ fallback_lst_styles=node.inherited_lst_styles,+ id_prefix=f"{ctx.group_id_prefix}txt",+ id_seq=ctx.grad_seq,+ )+ else:+ text_result = convert_txbody(+ tx_body, node.xfrm, ctx.palette,+ theme_fonts=ctx.theme_fonts,+ slide_number=ctx.slide_number,+ default_fill=text_default_fill,+ default_font_size_px=DEFAULT_FONT_SIZE_PX,+ fallback_lst_styles=node.inherited_lst_styles,+ id_prefix=f"{ctx.group_id_prefix}txt",+ id_seq=ctx.grad_seq,+ ) if tx_body is not None else TextResult()+ except ValueError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "text-omitted",+ str(exc),+ "omit this text body and retain the object's other visuals",)- else:- text_result = convert_txbody(- tx_body, node.xfrm, ctx.palette,- theme_fonts=ctx.theme_fonts,- slide_number=ctx.slide_number,- default_fill=text_default_fill,- default_font_size_px=DEFAULT_FONT_SIZE_PX,- fallback_lst_styles=node.inherited_lst_styles,- id_prefix=f"{ctx.group_id_prefix}txt",- id_seq=ctx.grad_seq,- ) if tx_body is not None else TextResult()+ text_result = TextResult()if text_result.defs:ctx.defs.extend(text_result.defs)@@ -513,22 +650,68 @@ def _build_geometry_xml(node: ShapeNode, sp_pr: ET.Element | None,# Resolve style defaults early so markers can adopt the theme stroke color# when <a:ln> doesn't carry an explicit solidFill.- style_defaults = _resolve_shape_style_defaults(node, ctx)+ try:+ style_defaults = _resolve_shape_style_defaults(node, ctx)+ except ValueError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "shape-style-omitted",+ str(exc),+ "omit unresolved theme style defaults",+ )+ style_defaults = {}# 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,- style_stroke_default=style_defaults.get("stroke"),- )- effect = convert_effects(- sp_pr,- ctx.palette,- id_prefix="fx",- id_seq=ctx.filter_seq,- )+ try:+ fill = resolve_fill(+ sp_pr,+ ctx.palette,+ id_prefix="g",+ id_seq=ctx.grad_seq,+ )+ except ValueError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "fill-omitted",+ str(exc),+ "omit only the unsupported fill",+ )+ fill = FillResult.none_fill()+ try:+ stroke = resolve_stroke(+ sp_pr,+ ctx.palette,+ id_prefix="m",+ id_seq=ctx.marker_seq,+ style_stroke_default=style_defaults.get("stroke"),+ )+ except ValueError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "stroke-omitted",+ str(exc),+ "omit only the unsupported outline",+ )+ stroke = StrokeResult(attrs={"stroke": "none"})+ try:+ effect = convert_effects(+ sp_pr,+ ctx.palette,+ id_prefix="fx",+ id_seq=ctx.filter_seq,+ )+ except ValueError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "effect-omitted",+ str(exc),+ "omit only the unsupported visual effect",+ )+ effect = EffectResult()ctx.defs.extend(fill.defs)ctx.defs.extend(stroke.defs)@@ -542,6 +725,7 @@ def _build_geometry_xml(node: ShapeNode, sp_pr: ET.Element | None,effect_reason,))geom.attrs.update(effect_attrs)+ _diagnose_unsupported_effect(ctx, geom.attrs)attrs = {**fill.attrs, **stroke.attrs}for key, value in style_defaults.items():@@ -698,6 +882,7 @@ def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool)node.xml.find("p:spPr", NS),"picture",)+ _diagnose_unsupported_effect(ctx, effect_metadata)picture_svg = _inject_root_svg_attrs(result.svg,{**_object_metadata(node, ctx), **effect_metadata},@@ -756,6 +941,7 @@ def _convert_group(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->node.xml.find("p:grpSpPr", NS),"group",)+ _diagnose_unsupported_effect(ctx, effect_metadata)return _wrap_shape_group(inner,node,@@ -919,9 +1105,9 @@ def _render_graphic_table(f'{_xml_escape(result.native_status)}"')if result.effect_reason:- replacement_attrs.extend(_metadata_group_attrs(- unsupported_effect_metadata(result.effect_reason)- ))+ effect_metadata = unsupported_effect_metadata(result.effect_reason)+ _diagnose_unsupported_effect(ctx, effect_metadata)+ replacement_attrs.extend(_metadata_group_attrs(effect_metadata))return result.svg, replacement_attrs, payload_metadata@@ -1277,6 +1463,21 @@ def _metadata_group_attrs(attrs: dict[str, str]) -> list[str]:]+def _diagnose_unsupported_effect(+ ctx: AssemblyContext,+ metadata: dict[str, str],+) -> None:+ """Copy an import-only blocking effect marker into the conversion report."""+ reason = metadata.get(EFFECT_REASON_ATTR)+ if reason is None:+ return+ ctx.diagnose(+ "effect-unsupported",+ reason,+ "retain the base object and record blocking effect metadata",+ )++def _geometry_group_attrs(geom: GeomResult | None) -> list[str]:"""Mirror native geometry semantics onto the logical shape container."""if geom is None: