Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(workflows): harden export and validation failure boundaries

hugohe340d04bdbe1d7
diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.py
index ffc88d45..7156a5bc 100644
--- a/skills/ppt-master/scripts/finalize_svg.py
+++ b/skills/ppt-master/scripts/finalize_svg.py
@@ -35,9 +35,12 @@ Processing options:
flatten-text - Convert <tspan> to independent <text> (for special renderers)
"""
-import sys
-import shutil
import argparse
+import os
+import shutil
+import sys
+import tempfile
+from enum import Enum
from pathlib import Path
from typing import TextIO
from xml.etree import ElementTree as ET
@@ -64,6 +67,14 @@ from svg_to_pptx.use_expander import (
)
+class FlattenTextResult(Enum):
+ """Describe whether flattening changed a file, skipped it, or failed."""
+
+ CHANGED = "changed"
+ UNCHANGED = "unchanged"
+ ERROR = "error"
+
+
def safe_print(text: str, *, file: TextIO | None = None) -> None:
"""Print text while tolerating Windows terminal encoding limits."""
stream = file or sys.stdout
@@ -84,11 +95,13 @@ def safe_print(text: str, *, file: TextIO | None = None) -> None:
print(text, file=stream)
-def process_flatten_text(svg_file: Path, verbose: bool = False) -> bool:
- """Flatten text in a single SVG file (in-place modification)"""
+def process_flatten_text(
+ svg_file: Path,
+ verbose: bool = False,
+) -> FlattenTextResult:
+ """Flatten text in one SVG and report changed, unchanged, or error."""
try:
from svg_finalize.flatten_tspan import flatten_text_with_tspans
- from xml.etree import ElementTree as ET
tree = ET.parse(str(svg_file))
changed = flatten_text_with_tspans(tree)
@@ -97,69 +110,84 @@ def process_flatten_text(svg_file: Path, verbose: bool = False) -> bool:
tree.write(str(svg_file), encoding='unicode', xml_declaration=False)
if verbose:
safe_print(f" [OK] {svg_file.name}: text flattened")
- return changed
- except Exception as e:
- if verbose:
- safe_print(f" [ERROR] {svg_file.name}: {e}")
- return False
-
-
-def finalize_project(
- project_dir: Path,
- options: dict[str, bool],
- dry_run: bool = False,
- quiet: bool = False,
- compress: bool = True,
- max_dimension: int | None = 2560,
- image_scale: float = 2.0,
-) -> bool:
- """
- Finalize SVG files in the project
-
- Args:
- project_dir: Project directory path
- options: Processing options dictionary
- dry_run: Preview only, do not execute
- quiet: Quiet mode, reduce output
- compress: Compress images before embedding
- max_dimension: Downscale images exceeding this dimension
- image_scale: Target image pixels per SVG display pixel
- """
- svg_output = project_dir / 'svg_output'
- svg_final = project_dir / 'svg_final'
- icons_dir, icons_fallback_dir = icon_search_dirs_for_project(project_dir)
+ return FlattenTextResult.CHANGED
+ return FlattenTextResult.UNCHANGED
+ except Exception as exc:
+ safe_print(
+ f" [ERROR] {svg_file.name}: text flattening failed: {exc}",
+ file=sys.stderr,
+ )
+ return FlattenTextResult.ERROR
- # Check if svg_output exists
- if not svg_output.exists():
- safe_print(f"[ERROR] svg_output directory not found: {svg_output}")
- return False
- # Get list of SVG files
- svg_files = list(svg_output.glob('*.svg'))
- if not svg_files:
- safe_print(f"[ERROR] No SVG files in svg_output")
- return False
-
- if not quiet:
- print()
- safe_print(f"[DIR] Project: {project_dir.name}")
- safe_print(f"[FILE] {len(svg_files)} SVG file(s)")
+def _path_lexists(path: Path) -> bool:
+ """Return whether a path or dangling symlink occupies the target name."""
+ return os.path.lexists(path)
- if dry_run:
- safe_print("[PREVIEW] Preview mode, no operations will be performed")
- return True
- # Step 1: Copy directory
- if svg_final.exists():
- shutil.rmtree(svg_final)
- shutil.copytree(svg_output, svg_final)
+def _publish_candidate_directory(candidate_dir: Path, output_dir: Path) -> None:
+ """Publish one staged directory and restore the previous output on failure."""
+ if output_dir.is_symlink() or (
+ _path_lexists(output_dir) and not output_dir.is_dir()
+ ):
+ raise RuntimeError(f"Output path must be a real directory: {output_dir}")
- if not quiet:
- print()
+ transaction_dir = Path(
+ tempfile.mkdtemp(
+ prefix=f".{output_dir.name}.publish-",
+ dir=output_dir.parent,
+ )
+ )
+ backup_dir = transaction_dir / "previous"
+ preserve_backup = False
+ try:
+ if output_dir.is_dir():
+ try:
+ os.replace(output_dir, backup_dir)
+ os.replace(candidate_dir, output_dir)
+ except BaseException as publish_error:
+ try:
+ if _path_lexists(backup_dir):
+ if _path_lexists(output_dir):
+ failed_output = transaction_dir / "failed-publish"
+ os.replace(output_dir, failed_output)
+ os.replace(backup_dir, output_dir)
+ except BaseException as restore_error:
+ if (
+ not _path_lexists(backup_dir)
+ and _path_lexists(output_dir)
+ ):
+ raise publish_error
+ preserve_backup = _path_lexists(backup_dir)
+ raise RuntimeError(
+ "Failed to publish svg_final and restore the previous "
+ "directory; recovery directory: "
+ f"{transaction_dir}"
+ ) from restore_error
+ raise
+ else:
+ os.replace(candidate_dir, output_dir)
+ finally:
+ if not preserve_backup:
+ shutil.rmtree(transaction_dir, ignore_errors=True)
+
+
+def _process_candidate_directory(
+ candidate_dir: Path,
+ *,
+ options: dict[str, bool],
+ quiet: bool,
+ compress: bool,
+ max_dimension: int | None,
+ image_scale: float,
+ icons_dir: Path,
+ icons_fallback_dir: Path | None,
+) -> bool:
+ """Run every selected finalization pass against one unpublished candidate."""
# Core normalization: downstream image/rect processors read XML geometry.
geometry_count = 0
- for svg_file in svg_final.glob('*.svg'):
+ for svg_file in candidate_dir.glob('*.svg'):
try:
geometry_count += materialize_inline_geometry_in_file(svg_file)
except (OSError, ET.ParseError, GeometryStyleError) as exc:
@@ -167,12 +195,13 @@ def finalize_project(
f"[ERROR] {svg_file.name}: inline geometry materialization failed: {exc}"
)
return False
- # Step 2: Expand project icons, then standard same-document use references.
+
+ # Step 1: Expand project icons, then standard same-document use references.
if options.get('embed_icons'):
if not quiet:
safe_print("[1/3] Expanding icons + local use references...")
icons_count = 0
- for svg_file in svg_final.glob('*.svg'):
+ for svg_file in candidate_dir.glob('*.svg'):
count = embed_icons_in_file(
svg_file,
icons_dir,
@@ -181,7 +210,7 @@ def finalize_project(
fallback_dir=icons_fallback_dir,
)
icons_count += count
- for svg_file in svg_final.glob('*.svg'):
+ for svg_file in candidate_dir.glob('*.svg'):
try:
geometry_count += materialize_inline_geometry_in_file(svg_file)
except (OSError, ET.ParseError, GeometryStyleError) as exc:
@@ -191,7 +220,7 @@ def finalize_project(
)
return False
local_use_count = 0
- for svg_file in svg_final.glob('*.svg'):
+ for svg_file in candidate_dir.glob('*.svg'):
try:
local_use_count += expand_local_use_references_in_file(svg_file)
except (OSError, ET.ParseError, UseExpansionError) as exc:
@@ -214,7 +243,7 @@ def finalize_project(
f"[PREP] {geometry_count} inline geometry declaration(s) materialized"
)
- # Step 3: Align (slice/meet) and Base64-embed all <image> in one pass.
+ # Step 2: Align (slice/meet) and Base64-embed all <image> in one pass.
# Replaces the former crop-images / fix-aspect / embed-images trio: the
# spatial transform (slice → crop, meet → fit-box) and the asset embed
# are mutually exclusive branches per image, sequenced together so each
@@ -226,7 +255,7 @@ def finalize_project(
img_count = 0
img_errors = 0
office_vector_count = 0
- for svg_file in svg_final.glob('*.svg'):
+ for svg_file in candidate_dir.glob('*.svg'):
office_vector_count += count_office_vector_refs_in_svg(svg_file)
count, errs = align_and_embed_images_in_svg(
svg_file,
@@ -244,7 +273,6 @@ def finalize_project(
f"{img_errors} image(s); svg_final was not published",
file=sys.stderr,
)
- shutil.rmtree(svg_final, ignore_errors=True)
return False
if not quiet:
if img_count > 0:
@@ -263,20 +291,119 @@ def finalize_project(
else:
safe_print(" No images")
- # Step 4: Flatten text
+ # Step 3: Flatten text.
if options.get('flatten_text'):
if not quiet:
safe_print("[3/3] Flattening text...")
flatten_count = 0
- for svg_file in svg_final.glob('*.svg'):
- if process_flatten_text(svg_file, verbose=False):
+ flatten_errors = 0
+ for svg_file in candidate_dir.glob('*.svg'):
+ result = process_flatten_text(svg_file, verbose=False)
+ if result is FlattenTextResult.CHANGED:
flatten_count += 1
+ elif result is FlattenTextResult.ERROR:
+ flatten_errors += 1
+ if flatten_errors:
+ safe_print(
+ f"[ERROR] Text flattening failed for {flatten_errors} file(s); "
+ "svg_final was not published",
+ file=sys.stderr,
+ )
+ return False
if not quiet:
if flatten_count > 0:
safe_print(f" {flatten_count} file(s) processed")
else:
safe_print(" No processing needed")
+ return True
+
+
+def finalize_project(
+ project_dir: Path,
+ options: dict[str, bool],
+ dry_run: bool = False,
+ quiet: bool = False,
+ compress: bool = True,
+ max_dimension: int | None = 2560,
+ image_scale: float = 2.0,
+) -> bool:
+ """
+ Finalize SVG files in the project
+
+ Args:
+ project_dir: Project directory path
+ options: Processing options dictionary
+ dry_run: Preview only, do not execute
+ quiet: Quiet mode, reduce output
+ compress: Compress images before embedding
+ max_dimension: Downscale images exceeding this dimension
+ image_scale: Target image pixels per SVG display pixel
+ """
+ svg_output = project_dir / 'svg_output'
+ svg_final = project_dir / 'svg_final'
+ icons_dir, icons_fallback_dir = icon_search_dirs_for_project(project_dir)
+
+ # Check if svg_output exists
+ if not svg_output.exists():
+ safe_print(f"[ERROR] svg_output directory not found: {svg_output}")
+ return False
+
+ # Get list of SVG files
+ svg_files = list(svg_output.glob('*.svg'))
+ if not svg_files:
+ safe_print(f"[ERROR] No SVG files in svg_output")
+ return False
+
+ if not quiet:
+ print()
+ safe_print(f"[DIR] Project: {project_dir.name}")
+ safe_print(f"[FILE] {len(svg_files)} SVG file(s)")
+
+ if dry_run:
+ safe_print("[PREVIEW] Preview mode, no operations will be performed")
+ return True
+
+ candidate_dir = Path(
+ tempfile.mkdtemp(
+ prefix=f".{svg_final.name}.candidate-",
+ dir=svg_final.parent,
+ )
+ )
+ try:
+ try:
+ shutil.copytree(svg_output, candidate_dir, dirs_exist_ok=True)
+ candidate_ready = _process_candidate_directory(
+ candidate_dir,
+ options=options,
+ quiet=quiet,
+ compress=compress,
+ max_dimension=max_dimension,
+ image_scale=image_scale,
+ icons_dir=icons_dir,
+ icons_fallback_dir=icons_fallback_dir,
+ )
+ except Exception as exc:
+ safe_print(
+ f"[ERROR] SVG finalization failed before publish: {exc}",
+ file=sys.stderr,
+ )
+ return False
+
+ if not candidate_ready:
+ return False
+
+ try:
+ _publish_candidate_directory(candidate_dir, svg_final)
+ except (OSError, RuntimeError) as exc:
+ safe_print(
+ f"[ERROR] svg_final publish failed: {exc}",
+ file=sys.stderr,
+ )
+ return False
+ finally:
+ shutil.rmtree(candidate_dir, ignore_errors=True)
+
# Done
if not quiet:
print()
diff --git a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py
index a1d370f7..04f14b54 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py
@@ -37,6 +37,7 @@ from __future__ import annotations
import base64
import hashlib
import io
+import math
import mimetypes
import shutil
import subprocess
@@ -55,6 +56,15 @@ from .emu_units import NS, Xfrm, emu_to_px, fmt_num, format_ooxml_alpha
from .ooxml_loader import OoxmlPackage, PartRef, blip_embed_relationship_ids
+@dataclass(frozen=True)
+class PictureDiagnostic:
+ """Recoverable loss while converting one DrawingML picture."""
+
+ code: str
+ message: str
+ fallback: str
+
+
@dataclass
class PictureResult:
"""Resolved picture: SVG element string + extracted media bytes."""
@@ -63,6 +73,7 @@ class PictureResult:
# 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)
+ diagnostics: tuple[PictureDiagnostic, ...] = ()
class MediaResolutionError(RuntimeError):
@@ -78,6 +89,7 @@ def convert_blip_fill(
media_subdir: str = "assets",
embed_inline: bool = False,
asset_name_map: dict[str, str] | None = None,
+ strict: bool = False,
) -> PictureResult:
"""Convert an <a:blipFill> element to SVG <image>.
@@ -125,9 +137,19 @@ def convert_blip_fill(
filename = (asset_name_map or {}).get(target, pkg.media_filename(target))
filename, img_bytes = _normalize_office_media(filename, img_bytes)
tile_source_bytes = img_bytes
- filename, img_bytes = _apply_blip_image_effects(filename, img_bytes, blip)
+ diagnostics = list(_unsupported_blip_effect_diagnostics(blip))
+ filename, img_bytes, effect_diagnostics = _apply_blip_image_effects(
+ filename,
+ img_bytes,
+ blip,
+ )
+ diagnostics.extend(effect_diagnostics)
+ opacity_attr, opacity_diagnostics = _blip_opacity_attr(blip)
+ diagnostics.extend(opacity_diagnostics)
+ if strict and diagnostics:
+ details = "; ".join(item.message for item in diagnostics)
+ raise ValueError(f"Cannot reproduce DrawingML picture effects: {details}")
href = _build_href(filename, img_bytes, media_subdir, embed_inline)
- opacity_attr = _blip_opacity_attr(blip)
# srcRect: l/t/r/b in 1/100000ths (so 50000 = 50%).
src_rect = blip_fill_elem.find("a:srcRect", NS)
@@ -170,7 +192,11 @@ def convert_blip_fill(
media: dict[str, bytes] = {}
if not embed_inline:
media[filename] = img_bytes
- return PictureResult(svg=svg, media=media)
+ return PictureResult(
+ svg=svg,
+ media=media,
+ diagnostics=tuple(diagnostics),
+ )
def convert_picture(
@@ -182,6 +208,7 @@ def convert_picture(
media_subdir: str = "assets",
embed_inline: bool = False,
asset_name_map: dict[str, str] | None = None,
+ strict: bool = False,
) -> PictureResult:
"""Translate <p:pic> to SVG <image> (or nested <svg>+<image> for cropping)."""
blip_fill = pic_elem.find("p:blipFill", NS)
@@ -193,6 +220,7 @@ def convert_picture(
media_subdir=media_subdir,
embed_inline=embed_inline,
asset_name_map=asset_name_map,
+ strict=strict,
)
@@ -201,18 +229,78 @@ def convert_picture(
# ---------------------------------------------------------------------------
-def _blip_opacity_attr(blip: ET.Element) -> str:
+def _blip_opacity_attr(
+ blip: ET.Element,
+) -> tuple[str, tuple[PictureDiagnostic, ...]]:
"""Translate DrawingML fixed image alpha to an SVG opacity attribute."""
- alpha = blip.find("a:alphaModFix", NS)
- if alpha is None:
- return ""
+ alpha_effects = blip.findall("a:alphaModFix", NS)
+ if not alpha_effects:
+ return "", ()
+ if len(alpha_effects) > 1:
+ return "", (
+ _effect_diagnostic(
+ "duplicate a:alphaModFix effects cannot be reproduced safely"
+ ),
+ )
+ alpha = alpha_effects[0]
try:
- opacity = max(0.0, min(1.0, float(alpha.attrib.get("amt", "100000")) / 100000.0))
+ opacity = float(alpha.attrib.get("amt", "100000")) / 100000.0
except ValueError:
- return ""
+ return "", (
+ _effect_diagnostic(
+ f"invalid a:alphaModFix amt={alpha.attrib.get('amt')!r}"
+ ),
+ )
+ if not math.isfinite(opacity) or not 0.0 <= opacity <= 1.0:
+ return "", (
+ _effect_diagnostic(
+ f"out-of-range a:alphaModFix amt={alpha.attrib.get('amt')!r}"
+ ),
+ )
if opacity >= 1.0:
- return ""
- return f' opacity="{format_ooxml_alpha(opacity)}"'
+ return "", ()
+ return f' opacity="{format_ooxml_alpha(opacity)}"', ()
+
+
+def _effect_diagnostic(message: str) -> PictureDiagnostic:
+ return PictureDiagnostic(
+ code="image-effect-omitted",
+ message=message,
+ fallback="retain the source image and omit only this image effect",
+ )
+
+
+def _unsupported_blip_effect_diagnostics(
+ blip: ET.Element,
+) -> tuple[PictureDiagnostic, ...]:
+ """Report direct a:blip effects outside the implemented subset."""
+ supported_tags = {
+ f"{{{NS['a']}}}lum",
+ f"{{{NS['a']}}}alphaModFix",
+ f"{{{NS['a']}}}extLst",
+ }
+ unsupported = sorted({
+ child.tag.rsplit("}", 1)[-1]
+ for child in blip
+ if child.tag not in supported_tags
+ })
+ diagnostics = (
+ [
+ _effect_diagnostic(
+ "unsupported direct a:blip effect(s): "
+ + ", ".join(f"a:{name}" for name in unsupported)
+ )
+ ]
+ if unsupported
+ else []
+ )
+ if len(blip.findall("a:lum", NS)) > 1:
+ diagnostics.append(
+ _effect_diagnostic(
+ "duplicate a:lum effects cannot be reproduced safely"
+ )
+ )
+ return tuple(diagnostics)
_OFFICE_VECTOR_EXTS = {".emf", ".wmf"}
@@ -419,26 +507,61 @@ def _apply_blip_image_effects(
filename: str,
img_bytes: bytes,
blip: ET.Element,
-) -> tuple[str, bytes]:
+) -> tuple[str, bytes, tuple[PictureDiagnostic, ...]]:
"""Bake supported DrawingML blip effects into extracted image bytes.
Keeping the SVG as a plain <image> avoids introducing CSS filters that the
downstream native PPTX converter cannot reliably map back to DrawingML.
"""
- lum = blip.find("a:lum", NS)
- if lum is None:
- return filename, img_bytes
-
- bright = _signed_pct_attr(lum, "bright")
- contrast = _signed_pct_attr(lum, "contrast")
+ lum_effects = blip.findall("a:lum", NS)
+ if not lum_effects:
+ return filename, img_bytes, ()
+ if len(lum_effects) > 1:
+ return filename, img_bytes, ()
+ lum = lum_effects[0]
+
+ values: dict[str, float | None] = {}
+ for name in ("bright", "contrast"):
+ raw_value = lum.attrib.get(name)
+ if raw_value is None:
+ values[name] = None
+ continue
+ try:
+ value = float(raw_value) / 100000.0
+ except ValueError:
+ return filename, img_bytes, (
+ _effect_diagnostic(f"invalid a:lum {name}={raw_value!r}"),
+ )
+ if not math.isfinite(value) or not -1.0 <= value <= 1.0:
+ return filename, img_bytes, (
+ _effect_diagnostic(
+ f"out-of-range a:lum {name}={raw_value!r}"
+ ),
+ )
+ values[name] = value
+ bright = values["bright"]
+ contrast = values["contrast"]
if bright is None and contrast is None:
- return filename, img_bytes
+ return filename, img_bytes, ()
if Image is None or ImageEnhance is None:
- return filename, img_bytes
+ return filename, img_bytes, (
+ _effect_diagnostic(
+ "a:lum requires Pillow, but Pillow is unavailable"
+ ),
+ )
try:
- image = Image.open(io.BytesIO(img_bytes))
- output_format = image.format or _pil_format_from_filename(filename)
+ with Image.open(io.BytesIO(img_bytes)) as source_image:
+ if getattr(source_image, "is_animated", False):
+ return filename, img_bytes, (
+ _effect_diagnostic(
+ "a:lum on an animated image would flatten its frames"
+ ),
+ )
+ output_format = (
+ source_image.format or _pil_format_from_filename(filename)
+ )
+ image = source_image.copy()
if image.mode not in ("RGB", "RGBA"):
image = image.convert("RGBA" if "A" in image.getbands() else "RGB")
if bright is not None:
@@ -452,19 +575,15 @@ def _apply_blip_image_effects(
image.save(out, format=save_format, **save_kwargs)
effect_key = f"lum-{bright}-{contrast}".encode("ascii")
digest = hashlib.sha1(effect_key).hexdigest()[:8]
- return _effect_filename(filename, digest, save_format), out.getvalue()
- except Exception:
- return filename, img_bytes
-
-
-def _signed_pct_attr(elem: ET.Element, name: str) -> float | None:
- val = elem.attrib.get(name)
- if val is None:
- return None
- try:
- return float(val) / 100000.0
- except ValueError:
- return None
+ return (
+ _effect_filename(filename, digest, save_format),
+ out.getvalue(),
+ (),
+ )
+ except (KeyError, OSError, ValueError) as exc:
+ return filename, img_bytes, (
+ _effect_diagnostic(f"a:lum could not be rendered: {exc}"),
+ )
def _pil_format_from_filename(filename: str) -> str | None:
diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
index ca462992..04e23192 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
@@ -64,7 +64,12 @@ from .ooxml_loader import (
SlideRef,
inherited_shape_visibility,
)
-from .pic_to_svg import MediaResolutionError, convert_blip_fill, convert_picture
+from .pic_to_svg import (
+ MediaResolutionError,
+ PictureResult,
+ convert_blip_fill,
+ convert_picture,
+)
from .prstgeom_to_svg import GeomResult, convert_prst_geom
from .preset_svg_markup import serialize_preset_layers
from .shape_walker import (
@@ -151,6 +156,19 @@ class AssemblyContext:
self.diagnose(code, message, fallback)
+def _diagnose_picture_result(
+ ctx: AssemblyContext,
+ result: PictureResult,
+) -> None:
+ """Project recoverable picture losses into the import report."""
+ for diagnostic in result.diagnostics:
+ ctx.diagnose(
+ diagnostic.code,
+ diagnostic.message,
+ diagnostic.fallback,
+ )
+
+
# ---------------------------------------------------------------------------
# Public entry
# ---------------------------------------------------------------------------
@@ -457,6 +475,7 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->
media_subdir=ctx.media_subdir,
embed_inline=ctx.embed_images,
asset_name_map=ctx.asset_name_map,
+ strict=ctx.strict,
)
except (ValueError, MediaResolutionError) as exc:
if ctx.strict:
@@ -467,6 +486,7 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->
"omit the image fill and retain shape geometry/text",
)
else:
+ _diagnose_picture_result(ctx, blip_result)
if blip_result.svg:
blip_image = _clip_blip_image(blip_result.svg, geom, ctx)
ctx.media.update(blip_result.media)
@@ -929,6 +949,7 @@ def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool)
media_subdir=ctx.media_subdir,
embed_inline=ctx.embed_images,
asset_name_map=ctx.asset_name_map,
+ strict=ctx.strict,
)
except MediaResolutionError as exc:
if ctx.strict:
@@ -941,6 +962,7 @@ def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool)
return _fallback_node_svg(node, ctx, top_level=top_level)
if not result.svg:
return ""
+ _diagnose_picture_result(ctx, result)
ctx.media.update(result.media)
effect_metadata = unsupported_target_effect_metadata(
sp_pr,
@@ -1280,9 +1302,11 @@ def _render_graphic_preview(node: ShapeNode, ctx: AssemblyContext) -> str:
media_subdir=ctx.media_subdir,
embed_inline=ctx.embed_images,
asset_name_map=ctx.asset_name_map,
+ strict=ctx.strict,
)
if not result.svg:
return ""
+ _diagnose_picture_result(ctx, result)
ctx.media.update(result.media)
return result.svg
@@ -1392,7 +1416,9 @@ def _emit_background_image(
media_subdir=ctx.media_subdir,
embed_inline=ctx.embed_images,
asset_name_map=ctx.asset_name_map,
+ strict=ctx.strict,
)
+ _diagnose_picture_result(ctx, result)
if result.media:
ctx.media.update(result.media)
return result.svg
diff --git a/skills/ppt-master/scripts/resource_paths.py b/skills/ppt-master/scripts/resource_paths.py
index fa81c898..ff7f3d3d 100644
--- a/skills/ppt-master/scripts/resource_paths.py
+++ b/skills/ppt-master/scripts/resource_paths.py
@@ -27,6 +27,7 @@ from xml.etree import ElementTree as ET
SVG_WORK_DIR_NAMES = frozenset({'svg_output', 'svg_final', 'svg-flat', 'svg_flat'})
+SVG_FINAL_CANDIDATE_PREFIX = '.svg_final.candidate-'
TEMPLATE_SOURCE_DIR_NAME = 'templates'
TEMPLATE_SPEC_FILENAME = 'design_spec.md'
_SVG_NAMESPACE = 'http://www.w3.org/2000/svg'
@@ -63,7 +64,10 @@ def project_root_for_svg_path(svg_path: Path) -> Path:
"""Infer the project root from an SVG file path or SVG directory path."""
path = Path(svg_path)
base = path if path.is_dir() else path.parent
- if base.name in SVG_WORK_DIR_NAMES:
+ if (
+ base.name in SVG_WORK_DIR_NAMES
+ or base.name.startswith(SVG_FINAL_CANDIDATE_PREFIX)
+ ):
return base.parent
if (
base.name == TEMPLATE_SOURCE_DIR_NAME
diff --git a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py b/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
index b1931aa2..9e2a8d85 100644
--- a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
+++ b/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
@@ -76,6 +76,8 @@ IMAGE_EXT_BY_CONTENT_TYPE = {
"image/x-wmf": "wmf",
}
LEGACY_GENERATED_IMAGE_RE = re.compile(r"^slide_\d{2}_image_\d{2}\.[A-Za-z0-9]+$")
+_READBACK_SLIDE_HEADING_RE = re.compile(r"^## Slide\s+\d+\s*$")
+_READBACK_NOTES_HEADING_RE = re.compile(r"^### Speaker Notes\s*$")
# Hyperlink schemes dropped during extraction (a blacklist of known-dangerous
# schemes). PowerPoint also rejects unrecognized schemes at open time, so the
@@ -119,6 +121,20 @@ def normalize_text(value: str) -> str:
return "\n".join(lines)
+def _escape_readback_control_lines(value: str) -> str:
+ """Escape ordinary text lines that collide with converter section markers."""
+ lines = value.split("\n")
+ return "\n".join(
+ f"\\{line}"
+ if (
+ _READBACK_SLIDE_HEADING_RE.fullmatch(line)
+ or _READBACK_NOTES_HEADING_RE.fullmatch(line)
+ )
+ else line
+ for line in lines
+ )
+
+
def normalize_ext(ext: str | None, content_type: str | None = None) -> str:
"""Return a lowercase extension without a leading dot."""
if ext:
@@ -345,7 +361,9 @@ def text_frame_to_markdown(text_frame: object, shape: object = None) -> str:
paragraphs = []
for paragraph in visible_paragraphs:
- text = _paragraph_to_markdown(paragraph, shape)
+ text = _escape_readback_control_lines(
+ _paragraph_to_markdown(paragraph, shape)
+ )
if not text:
continue
if list_like:
diff --git a/skills/ppt-master/scripts/svg_finalize/align_embed_images.py b/skills/ppt-master/scripts/svg_finalize/align_embed_images.py
index 5c7bd466..624d104a 100644
--- a/skills/ppt-master/scripts/svg_finalize/align_embed_images.py
+++ b/skills/ppt-master/scripts/svg_finalize/align_embed_images.py
@@ -252,12 +252,23 @@ def _encode_pil_to_data_uri(
) -> tuple[str, int] | None:
"""Serialize *img* to a base64 data URI.
- If the image hasn't been transformed (slice crop or meet fit), prefer
- re-encoding the original file bytes so we don't risk mutating an
- already-optimized asset. *fallback_bytes* carries the raw on-disk
- bytes for that path.
+ If the image has not been transformed, ``--no-compress`` preserves a
+ supported PNG/JPEG/GIF/WebP payload byte-for-byte. Compression mode may
+ still retain a smaller original payload. *fallback_bytes* carries those
+ raw on-disk bytes.
"""
original_mime_type = get_mime_type(src_path.name, fallback_bytes)
+ if (
+ not compress
+ and fallback_bytes is not None
+ and original_mime_type in _PIL_FORMAT_BY_MIME
+ ):
+ encoded = base64.b64encode(fallback_bytes).decode('ascii')
+ return (
+ f'data:{original_mime_type};base64,{encoded}',
+ len(fallback_bytes),
+ )
+
# Match native export: only original JPEG assets stay lossy. PNG remains
# PNG, while BMP/TIFF and other static raster formats become lossless PNG.
mime_type = (
diff --git a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
index 8f4a8d49..6c5f1556 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
@@ -36,6 +36,15 @@ from .semantic_markers import is_static_page_frame
_NON_VISUAL_TAGS = frozenset(('defs', 'title', 'desc', 'metadata', 'style'))
+_INHERITANCE_SENSITIVE_ANIMATION_FIELDS = frozenset({
+ 'effect',
+ 'effect_options',
+ 'repeat_count',
+ 'repeat_duration',
+ 'accelerate',
+ 'decelerate',
+ 'bounce_end',
+})
_CHROME_ID_TOKENS = frozenset({
'background', 'bg',
'decoration', 'decorations', 'decor',
@@ -227,6 +236,18 @@ def _animation_effect_error(effect: object, label: str) -> str | None:
return None
+def resolve_slide_animation_config(
+ default_animation: dict[str, Any],
+ slide_animation: dict[str, Any],
+) -> dict[str, Any]:
+ """Merge one slide animation over defaults using writer inheritance rules."""
+ resolved = dict(default_animation)
+ if 'effect' in slide_animation and 'effect_options' not in slide_animation:
+ resolved.pop('effect_options', None)
+ resolved.update(slide_animation)
+ return resolved
+
+
def _animation_parameter_errors(
value: dict[str, Any],
label: str,
@@ -759,7 +780,7 @@ def validate_animation_config_errors(config: dict[str, Any]) -> list[str]:
_animation_scope_errors(slide_cfg, f'slide "{slide_name}"')
)
errors.extend(_animation_group_errors(slide_name, slide_cfg))
- errors.extend(_resolved_bounce_support_errors(config))
+ errors.extend(_resolved_animation_parameter_errors(config))
return list(dict.fromkeys(errors))
@@ -935,14 +956,17 @@ def _bounce_support_error(
)
-def _resolved_bounce_support_errors(config: dict[str, Any]) -> list[str]:
- """Validate effective bounce/effect pairs after sidecar inheritance."""
+def _resolved_animation_parameter_errors(config: dict[str, Any]) -> list[str]:
+ """Validate effective animation parameters after sidecar inheritance."""
defaults = config.get('defaults', {})
default_animation: dict[str, Any] = {'effect': 'auto'}
if isinstance(defaults, dict):
value = defaults.get('animation', {})
if isinstance(value, dict):
- default_animation.update(value)
+ default_animation = resolve_slide_animation_config(
+ default_animation,
+ value,
+ )
errors: list[str] = []
default_error = _bounce_support_error(default_animation, 'defaults animation')
@@ -952,21 +976,30 @@ def _resolved_bounce_support_errors(config: dict[str, Any]) -> list[str]:
slides = config.get('slides', {})
if not isinstance(slides, dict):
return errors
- relevant_fields = frozenset({'effect', 'effect_options', 'bounce_end'})
for slide_name, slide_cfg in slides.items():
if not isinstance(slide_cfg, dict):
continue
- slide_animation = dict(default_animation)
slide_value = slide_cfg.get('animation', {})
- if isinstance(slide_value, dict):
- slide_animation.update(slide_value)
- if relevant_fields & set(slide_value):
- error = _bounce_support_error(
+ if not isinstance(slide_value, dict):
+ continue
+ slide_animation = resolve_slide_animation_config(
+ default_animation,
+ slide_value,
+ )
+ if _INHERITANCE_SENSITIVE_ANIMATION_FIELDS & set(slide_value):
+ errors.extend(
+ _animation_parameter_errors(
slide_animation,
f'slide "{slide_name}" animation',
+ inherited_effect='auto',
)
- if error:
- errors.append(error)
+ )
+ error = _bounce_support_error(
+ slide_animation,
+ f'slide "{slide_name}" animation',
+ )
+ if error:
+ errors.append(error)
groups = slide_cfg.get('groups', {})
if not isinstance(groups, dict):
@@ -974,18 +1007,32 @@ def _resolved_bounce_support_errors(config: dict[str, Any]) -> list[str]:
for group_id, group_cfg in groups.items():
if (
not isinstance(group_cfg, dict)
- or not relevant_fields & set(group_cfg)
+ or not _INHERITANCE_SENSITIVE_ANIMATION_FIELDS & set(group_cfg)
):
continue
- group_animation = dict(slide_animation)
- if 'effect' in group_cfg:
- group_animation['effect'] = group_cfg['effect']
- if 'effect_options' in group_cfg:
- group_animation['effect_options'] = group_cfg['effect_options']
- else:
- group_animation.pop('effect_options', None)
- if 'bounce_end' in group_cfg:
- group_animation['bounce_end'] = group_cfg['bounce_end']
+ inherited_group_animation = {
+ field: slide_animation[field]
+ for field in (
+ 'effect',
+ 'effect_options',
+ 'duration',
+ *ANIMATION_TIMING_OPTION_FIELDS,
+ 'after_effect',
+ 'sound',
+ )
+ if field in slide_animation
+ }
+ group_animation = resolve_slide_animation_config(
+ inherited_group_animation,
+ group_cfg,
+ )
+ errors.extend(
+ _animation_parameter_errors(
+ group_animation,
+ f'group "{slide_name}/{group_id}"',
+ inherited_effect='auto',
+ )
+ )
error = _bounce_support_error(
group_animation,
f'group "{slide_name}/{group_id}"',
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
index decef3c9..bdffb4e8 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
@@ -55,7 +55,11 @@ from pptx_opc_validation import (
verify_internal_relationships,
)
-from ..animation_config import MorphPair, resolve_morph_pairs
+from ..animation_config import (
+ MorphPair,
+ resolve_morph_pairs,
+ resolve_slide_animation_config,
+)
from ..drawingml.converter import convert_svg_to_slide_shapes
from ..drawingml.theme_colors import (
ThemeColorSpec,
@@ -4044,8 +4048,10 @@ def _slide_animation_settings(
if not isinstance(anim_value, dict):
raise ValueError('animations.json slide animation must be an object')
anim_cfg = anim_value
- resolved_cfg = dict(default_animation_cfg)
- resolved_cfg.update(anim_cfg)
+ resolved_cfg = resolve_slide_animation_config(
+ default_animation_cfg,
+ anim_cfg,
+ )
if cli_overrides.get('animation'):
effect, effect_options = normalize_animation_effect_request(
animation,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
index 1c07a6fa..41a7fe46 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
@@ -45,7 +45,7 @@ if __package__ in {None, ''}:
__package__ = 'svg_to_pptx'
from .dimensions import CANVAS_FORMATS, get_project_info
-from .discovery import find_svg_files, find_notes_files
+from .discovery import NotesFileReadError, find_notes_files, find_svg_files
from .builder import create_pptx_with_native_svg
from ..native_objects import (
native_fallback_kind,
@@ -1258,7 +1258,11 @@ Recorded narration:
enable_notes = not args.no_notes
notes: dict[str, str] = {}
if enable_notes:
- notes = find_notes_files(project_path, ref_files)
+ try:
+ notes = find_notes_files(project_path, ref_files)
+ except NotesFileReadError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
narration_audio: dict[str, Path] = {}
narration_audio_dir_arg = args.recorded_narration or args.narration_audio_dir
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/discovery.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/discovery.py
index 7b7196fe..fd590de6 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/discovery.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/discovery.py
@@ -6,6 +6,10 @@ import re
from pathlib import Path
+class NotesFileReadError(RuntimeError):
+ """Report a matched notes file that cannot be decoded or read."""
+
+
def find_svg_files(
project_path: Path,
source: str = 'output',
@@ -76,26 +80,33 @@ def find_notes_files(
svg_index_mapping[i] = svg_path.stem
for notes_file in notes_dir.glob('*.md'):
+ stem = notes_file.stem
+
+ # Try index-based matching (backward compat with slide01.md format).
+ match = re.search(r'slide[_]?(\d+)', stem)
+ mapped_stem = (
+ svg_index_mapping.get(int(match.group(1)))
+ if match
+ else None
+ )
+ filename_match = stem in svg_stems_mapping
+ if mapped_stem is None and not filename_match:
+ continue
+
try:
- with open(notes_file, 'r', encoding='utf-8') as f:
- content = f.read().strip()
- if not content:
- continue
-
- stem = notes_file.stem
-
- # Try index-based matching (backward compat with slide01.md format)
- match = re.search(r'slide[_]?(\d+)', stem)
- if match:
- index = int(match.group(1))
- mapped_stem = svg_index_mapping.get(index)
- if mapped_stem:
- notes[mapped_stem] = content
-
- # Filename-based matching (overrides index-based)
- if stem in svg_stems_mapping:
- notes[stem] = content
- except Exception:
- pass
+ content = notes_file.read_text(encoding='utf-8').strip()
+ except (OSError, UnicodeError) as exc:
+ raise NotesFileReadError(
+ f"Cannot read matched notes file {notes_file}: {exc}"
+ ) from exc
+ if not content:
+ continue
+
+ if mapped_stem:
+ notes[mapped_stem] = content
+
+ # Filename-based matching overrides index-based matching.
+ if filename_match:
+ notes[stem] = content
return notes
diff --git a/skills/ppt-master/scripts/template_fill_pptx/validator.py b/skills/ppt-master/scripts/template_fill_pptx/validator.py
index 0a4d933b..492593e0 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/validator.py
+++ b/skills/ppt-master/scripts/template_fill_pptx/validator.py
@@ -6,14 +6,29 @@ import re
import subprocess
import sys
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
+from .checker import _chart_lookup, _slot_lookup, _table_lookup
from .ooxml import _load_json, _write_json
+from .selectors import (
+ _chart_selectors,
+ _replacement_selectors,
+ _replacement_text,
+ _table_cell_text,
+ _table_selectors,
+)
_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
-_SLIDE_HEADING_RE = re.compile(r"^## Slide\s+\d+\s*$", re.MULTILINE)
-_TOTAL_SLIDES_RE = re.compile(r"^- Total slides:\s*(\d+)\s*$", re.MULTILINE)
+_SLIDE_HEADING_RE = re.compile(r"^## Slide\s+(\d+)\s*$", re.MULTILINE)
+_SPEAKER_NOTES_RE = re.compile(r"^### Speaker Notes\s*$", re.MULTILINE)
+_MARKDOWN_LINK_RE = re.compile(r"(?<!!)\[([^\]]+)\]\([^)]+\)")
+_LIST_PREFIX_RE = re.compile(r"^\s*(?:[-+*]|\d+[.)])\s+")
+_TABLE_BREAK_RE = re.compile(r"<br\s*/?>", re.IGNORECASE)
+_TABLE_SEPARATOR_RE = re.compile(r"^:?-{3,}:?$")
+_ESCAPED_READBACK_CONTROL_RE = re.compile(
+ r"^\\(## Slide\s+\d+|### Speaker Notes)$"
+)
def _latest_export(project_path: Path) -> Path:
@@ -25,21 +40,122 @@ def _latest_export(project_path: Path) -> Path:
def _readback_slide_count(markdown: str) -> int:
- match = _TOTAL_SLIDES_RE.search(markdown)
- if match:
- return int(match.group(1))
return len(_SLIDE_HEADING_RE.findall(markdown))
-def _normalize_text(value: object) -> str:
- return re.sub(r"\s+", "", str(value or "")).strip()
+def _slide_sections(markdown: str) -> dict[int, str]:
+ matches = list(_SLIDE_HEADING_RE.finditer(markdown))
+ sections: dict[int, str] = {}
+ for index, match in enumerate(matches):
+ end = (
+ matches[index + 1].start()
+ if index + 1 < len(matches)
+ else len(markdown)
+ )
+ sections[int(match.group(1))] = markdown[match.end():end].strip()
+ return sections
+
+
+def _split_notes(section: str) -> tuple[str, str]:
+ match = _SPEAKER_NOTES_RE.search(section)
+ if match is None:
+ return section, ""
+ return section[:match.start()].strip(), section[match.end():].strip()
+
+
+def _normalize_line(value: str) -> str:
+ return re.sub(r"\s+", " ", value).strip()
+
+
+def _unescape_readback_control_line(value: str) -> str:
+ """Restore the display text of an escaped read-back section marker."""
+ match = _ESCAPED_READBACK_CONTROL_RE.fullmatch(value)
+ return match.group(1) if match else value
+
+
+def _paragraph_lines(value: object) -> list[str]:
+ text = str(value or "").replace("\r\n", "\n").replace("\r", "\n")
+ return [
+ normalized
+ for line in text.split("\n")
+ if (normalized := _normalize_line(line))
+ ]
+
+
+def _markdown_line_variants(markdown: str) -> list[set[str] | None]:
+ variants: list[set[str] | None] = []
+ for raw_line in markdown.splitlines():
+ stripped = raw_line.strip()
+ if (
+ not stripped
+ or stripped.startswith("|")
+ or stripped.startswith("![")
+ or stripped.startswith("> [Chart")
+ or stripped == "_No extractable text content._"
+ ):
+ variants.append(None)
+ continue
+ display = _MARKDOWN_LINK_RE.sub(r"\1", stripped)
+ without_prefix = _LIST_PREFIX_RE.sub("", display, count=1)
+ line_variants = {
+ _unescape_readback_control_line(_normalize_line(candidate))
+ for candidate in (stripped, display, without_prefix)
+ }
+ line_variants.discard("")
+ variants.append(line_variants)
+ return variants
+
+
+def _contains_paragraphs(markdown: str, value: str) -> bool:
+ expected = _paragraph_lines(value)
+ if not expected:
+ return True
+ actual = _markdown_line_variants(markdown)
+ if len(expected) > len(actual):
+ return False
+ for start in range(len(actual) - len(expected) + 1):
+ if all(
+ actual[start + offset] is not None
+ and expected[offset] in actual[start + offset]
+ for offset in range(len(expected))
+ ):
+ return True
+ return False
+
+
+def _table_cells(markdown: str) -> list[list[str]]:
+ cells: list[list[str]] = []
+ for raw_line in markdown.splitlines():
+ stripped = raw_line.strip()
+ if not (stripped.startswith("|") and stripped.endswith("|")):
+ continue
+ values = re.split(r"(?<!\\)\|", stripped[1:-1])
+ normalized_values = [
+ value.strip().replace(r"\|", "|")
+ for value in values
+ ]
+ if normalized_values and all(
+ _TABLE_SEPARATOR_RE.fullmatch(value) is not None
+ for value in normalized_values
+ ):
+ continue
+ for value in normalized_values:
+ cells.append(_paragraph_lines(_TABLE_BREAK_RE.sub("\n", value)))
+ return cells
-def _contains_text(markdown: str, value: object) -> bool:
- normalized = _normalize_text(value)
- if not normalized:
+def _contains_table_cell(markdown: str, value: str) -> bool:
+ expected = _paragraph_lines(value)
+ if not expected:
return True
- return normalized in _normalize_text(markdown)
+ return expected in _table_cells(markdown)
+
+
+def _contains_chart_text(markdown: str, value: str) -> bool:
+ return (
+ _contains_paragraphs(markdown, value)
+ or _contains_table_cell(markdown, value)
+ )
def _first_library(project_path: Path) -> dict[str, Any] | None:
@@ -49,61 +165,137 @@ def _first_library(project_path: Path) -> dict[str, Any] | None:
return _load_json(libraries[0])
-def _slot_role_lookup(library: dict[str, Any] | None) -> dict[tuple[int, str], str]:
- if library is None:
- return {}
- lookup: dict[tuple[int, str], str] = {}
- for slide in library.get("slides", []):
- slide_index = int(slide.get("slide_index", 0))
- for slot in slide.get("slots", []):
- slot_id = slot.get("slot_id")
- if isinstance(slot_id, str):
- lookup[(slide_index, slot_id)] = str(slot.get("role") or "")
- return lookup
+def _matched_library_target(
+ lookup: dict[tuple[int, str], dict[str, Any]] | None,
+ source_slide: int,
+ selectors: list[str],
+) -> dict[str, Any] | None:
+ """Return the first library target matched by the runtime selector order."""
+ if lookup is None:
+ return None
+ return next(
+ (
+ target
+ for selector in selectors
+ if (target := lookup.get((source_slide, selector))) is not None
+ ),
+ None,
+ )
-def _title_texts(plan: dict[str, Any], role_lookup: dict[tuple[int, str], str]) -> list[tuple[int, str]]:
- titles: list[tuple[int, str]] = []
+def _replacement_tokens(
+ plan: dict[str, Any],
+ library: dict[str, Any] | None,
+) -> list[tuple[int, str, str, str]]:
+ tokens: list[tuple[int, str, str, str]] = []
+ slot_lookup = _slot_lookup(library) if library is not None else None
for plan_slide, slide in enumerate(plan.get("slides", []), start=1):
source_slide = int(slide.get("source_slide", 0))
replacements = slide.get("replacements", [])
if not isinstance(replacements, list):
continue
- first_text = ""
- found_title = False
+ slide_tokens: list[tuple[str, bool]] = []
for replacement in replacements:
if not isinstance(replacement, dict):
continue
- text = str(replacement.get("text") or "").strip()
- if not text:
+ text = _replacement_text(replacement)
+ if not _paragraph_lines(text):
+ continue
+ slot = _matched_library_target(
+ slot_lookup,
+ source_slide,
+ _replacement_selectors(replacement),
+ )
+ if (
+ library is not None
+ and replacement.get("optional")
+ and slot is None
+ ):
continue
- if not first_text:
- first_text = text
- slot_id = replacement.get("slot_id")
- if isinstance(slot_id, str) and role_lookup.get((source_slide, slot_id)) == "title_candidate":
- titles.append((plan_slide, text))
- found_title = True
- break
- if not found_title and first_text:
- titles.append((plan_slide, first_text))
- return titles
-
-
-def _table_tokens(plan: dict[str, Any]) -> list[tuple[int, str]]:
+ is_title = (
+ slot is not None
+ and str(slot.get("role") or "") == "title_candidate"
+ )
+ slide_tokens.append((text, is_title))
+ if (
+ library is None
+ and slide_tokens
+ and not any(is_title for _, is_title in slide_tokens)
+ ):
+ first_text, _ = slide_tokens[0]
+ slide_tokens[0] = (first_text, True)
+ for text, is_title in slide_tokens:
+ tokens.append(
+ (
+ plan_slide,
+ text,
+ (
+ "title_missing_in_readback"
+ if is_title
+ else "body_text_missing_in_readback"
+ ),
+ "title" if is_title else "replacement text",
+ )
+ )
+ return tokens
+
+
+def _table_tokens(
+ plan: dict[str, Any],
+ library: dict[str, Any] | None,
+) -> list[tuple[int, str]]:
tokens: list[tuple[int, str]] = []
+ table_lookup = _table_lookup(library) if library is not None else None
for plan_slide, slide in enumerate(plan.get("slides", []), start=1):
+ source_slide = int(slide.get("source_slide", 0))
for table_edit in slide.get("table_edits", []) or []:
+ table = _matched_library_target(
+ table_lookup,
+ source_slide,
+ _table_selectors(table_edit),
+ )
+ if (
+ library is not None
+ and table_edit.get("optional")
+ and table is None
+ ):
+ continue
for cell in table_edit.get("cells", []) or []:
- text = str(cell.get("text") or "").strip()
- if text:
+ text = _table_cell_text(cell)
+ if _paragraph_lines(text):
tokens.append((plan_slide, text))
return tokens
-def _chart_tokens(plan: dict[str, Any]) -> list[tuple[int, str]]:
+def _format_chart_series_value(value: object) -> str:
+ """Match ppt_to_md's display formatting for chart series values."""
+ if value is None:
+ return ""
+ if isinstance(value, float) and value.is_integer():
+ return str(int(value))
+ return str(value)
+
+
+def _chart_tokens(
+ plan: dict[str, Any],
+ library: dict[str, Any] | None,
+) -> list[tuple[int, str]]:
tokens: list[tuple[int, str]] = []
+ chart_lookup = _chart_lookup(library) if library is not None else None
for plan_slide, slide in enumerate(plan.get("slides", []), start=1):
+ source_slide = int(slide.get("source_slide", 0))
for chart_edit in slide.get("chart_edits", []) or []:
+ chart = _matched_library_target(
+ chart_lookup,
+ source_slide,
+ _chart_selectors(chart_edit),
+ )
+ if (
+ library is not None
+ and chart_edit.get("optional")
+ and chart is None
+ ):
+ continue
for category in chart_edit.get("categories", []) or []:
if str(category).strip():
tokens.append((plan_slide, str(category)))
@@ -112,35 +304,34 @@ def _chart_tokens(plan: dict[str, Any]) -> list[tuple[int, str]]:
if name:
tokens.append((plan_slide, name))
for value in series.get("values", []) or []:
- tokens.append((plan_slide, str(value)))
+ text = _format_chart_series_value(value)
+ if text:
+ tokens.append((plan_slide, text))
return tokens
-def _append_token_checks(
+def _append_page_token_checks(
*,
results: list[dict[str, Any]],
summary: dict[str, int],
- markdown: str,
- tokens: list[tuple[int, str]],
- code: str,
- label: str,
+ sections: dict[int, str],
+ tokens: list[tuple[int, str, str, str]],
+ status: str,
+ matcher: Callable[[str, str], bool],
) -> None:
- seen: set[tuple[int, str]] = set()
- for plan_slide, text in tokens:
- key = (plan_slide, text)
- if key in seen:
- continue
- seen.add(key)
- if _contains_text(markdown, text):
+ summary_key = status.lower()
+ for plan_slide, text, code, label in tokens:
+ body, _ = _split_notes(sections.get(plan_slide, ""))
+ if matcher(body, text):
summary["ok"] += 1
continue
- summary["warn"] += 1
+ summary[summary_key] += 1
results.append(
{
- "status": "WARN",
+ "status": status,
"code": code,
"plan_slide": plan_slide,
- "message": f"{label} not found in read-back Markdown",
+ "message": f"{label} not found on the corresponding read-back slide",
"text": text,
}
)
@@ -179,6 +370,7 @@ def validate_project(project_path: Path) -> dict[str, Any]:
markdown = readback_path.read_text(encoding="utf-8", errors="replace")
results: list[dict[str, Any]] = []
summary = {"ok": 0, "warn": 0, "error": 0}
+ sections = _slide_sections(markdown)
expected_slides = len(plan.get("slides", []) or [])
actual_slides = _readback_slide_count(markdown)
@@ -196,63 +388,84 @@ def validate_project(project_path: Path) -> dict[str, Any]:
}
)
+ for plan_slide in range(1, expected_slides + 1):
+ if plan_slide in sections:
+ continue
+ summary["error"] += 1
+ results.append(
+ {
+ "status": "ERROR",
+ "code": "slide_missing_in_readback",
+ "plan_slide": plan_slide,
+ "message": "planned slide section is missing from read-back Markdown",
+ }
+ )
+
library = _first_library(project_path)
- role_lookup = _slot_role_lookup(library)
- _append_token_checks(
+ _append_page_token_checks(
results=results,
summary=summary,
- markdown=markdown,
- tokens=_title_texts(plan, role_lookup),
- code="title_missing_in_readback",
- label="key title",
+ sections=sections,
+ tokens=_replacement_tokens(plan, library),
+ status="ERROR",
+ matcher=_contains_paragraphs,
)
- _append_token_checks(
+ _append_page_token_checks(
results=results,
summary=summary,
- markdown=markdown,
- tokens=_table_tokens(plan),
- code="table_text_missing_in_readback",
- label="table text",
+ sections=sections,
+ tokens=[
+ (plan_slide, text, "table_text_missing_in_readback", "table cell text")
+ for plan_slide, text in _table_tokens(plan, library)
+ ],
+ status="ERROR",
+ matcher=_contains_table_cell,
)
- _append_token_checks(
+ _append_page_token_checks(
results=results,
summary=summary,
- markdown=markdown,
- tokens=_chart_tokens(plan),
- code="chart_text_missing_in_readback",
- label="chart text",
+ sections=sections,
+ tokens=[
+ (plan_slide, text, "chart_text_missing_in_readback", "chart text")
+ for plan_slide, text in _chart_tokens(plan, library)
+ ],
+ status="WARN",
+ matcher=_contains_chart_text,
)
- planned_notes = [
- slide
- for slide in plan.get("slides", []) or []
- if str(slide.get("notes") or slide.get("speaker_notes") or "").strip()
- ]
- note_sections = markdown.count("### Speaker Notes")
- if len(planned_notes) == note_sections:
- summary["ok"] += 1
- elif planned_notes:
- summary["warn"] += 1
- results.append(
- {
- "status": "WARN",
- "code": "notes_count_mismatch",
- "expected": len(planned_notes),
- "actual": note_sections,
- "message": "read-back speaker notes count does not match planned notes",
- }
- )
- elif note_sections:
- summary["warn"] += 1
- results.append(
- {
- "status": "WARN",
- "code": "unexpected_notes_in_readback",
- "expected": 0,
- "actual": note_sections,
- "message": "read-back contains speaker notes although the plan has no notes fields",
- }
- )
+ for plan_slide, slide in enumerate(plan.get("slides", []) or [], start=1):
+ _, notes = _split_notes(sections.get(plan_slide, ""))
+ planned_notes = str(slide.get("notes") or slide.get("speaker_notes") or "")
+ if _paragraph_lines(planned_notes):
+ if _contains_paragraphs(notes, planned_notes):
+ summary["ok"] += 1
+ continue
+ summary["error"] += 1
+ results.append(
+ {
+ "status": "ERROR",
+ "code": "notes_missing_in_readback",
+ "plan_slide": plan_slide,
+ "message": (
+ "planned speaker notes not found on the corresponding "
+ "read-back slide"
+ ),
+ "text": planned_notes,
+ }
+ )
+ elif notes.strip():
+ summary["warn"] += 1
+ results.append(
+ {
+ "status": "WARN",
+ "code": "unexpected_notes_in_readback",
+ "plan_slide": plan_slide,
+ "message": (
+ "read-back slide contains speaker notes although the "
+ "plan slide has no notes field"
+ ),
+ }
+ )
report = {
"schema": "template_fill_pptx_validate.v1",
diff --git a/skills/ppt-master/scripts/update_spec.py b/skills/ppt-master/scripts/update_spec.py
index ce4c1813..440a6893 100755
--- a/skills/ppt-master/scripts/update_spec.py
+++ b/skills/ppt-master/scripts/update_spec.py
@@ -25,8 +25,11 @@ per-role family changes, edit spec_lock.md and re-author the affected pages.
from __future__ import annotations
import argparse
+import os
import re
+import shutil
import sys
+import tempfile
from pathlib import Path
from console_encoding import configure_utf8_stdio
@@ -76,6 +79,119 @@ def plan_lock_values(
return "".join(lines)
+def _plan_color_updates(
+ svg_dir: Path,
+ old_hex: str,
+ new_hex: str,
+) -> list[tuple[Path, str, int]]:
+ """Return planned color rewrites without touching the SVG files."""
+ if not HEX_RE.match(old_hex) or not HEX_RE.match(new_hex):
+ raise ValueError(f"not a HEX color: old={old_hex!r} new={new_hex!r}")
+ pattern = re.compile(
+ rf"{re.escape(old_hex)}(?![0-9A-Fa-f])",
+ re.IGNORECASE,
+ )
+ planned: list[tuple[Path, str, int]] = []
+ for svg in sorted(svg_dir.glob("*.svg")):
+ text = svg.read_text(encoding="utf-8")
+ new_text, count = pattern.subn(new_hex, text)
+ if count > 0:
+ planned.append((svg, new_text, count))
+ return planned
+
+
+def _plan_font_family_updates(
+ svg_dir: Path,
+ new_value: str,
+) -> list[tuple[Path, str, int]]:
+ """Return planned font-family rewrites without touching the SVG files."""
+
+ def replace_value(match: re.Match[str]) -> str:
+ prefix, quote, _inner = match.group(1), match.group(2), match.group(3)
+ outer = quote
+ if outer in new_value:
+ outer = "'" if quote == '"' else '"'
+ if outer in new_value:
+ raise ValueError(
+ f"new font_family value contains both ' and \" — cannot embed: "
+ f"{new_value!r}"
+ )
+ return f"{prefix}{outer}{new_value}{outer}"
+
+ planned: list[tuple[Path, str, int]] = []
+ for svg in sorted(svg_dir.glob("*.svg")):
+ text = svg.read_text(encoding="utf-8")
+ new_text, count = FONT_FAMILY_RE.subn(replace_value, text)
+ if count > 0 and new_text != text:
+ planned.append((svg, new_text, count))
+ return planned
+
+
+def _publish_text_updates(updates: list[tuple[Path, str]]) -> None:
+ """Publish existing text files as one rollback unit."""
+ if not updates:
+ return
+ targets = [path for path, _text in updates]
+ if len(targets) != len(set(targets)):
+ raise ValueError("transaction contains duplicate output paths")
+ for target in targets:
+ if not target.is_file() or target.is_symlink():
+ raise OSError(f"transaction target must be a regular file: {target}")
+
+ transaction_dir = Path(
+ tempfile.mkdtemp(
+ prefix=".update-spec-",
+ dir=targets[0].parent,
+ )
+ )
+ staged_dir = transaction_dir / "staged"
+ backup_dir = transaction_dir / "previous"
+ preserve_transaction = False
+ published: list[tuple[Path, Path]] = []
+ try:
+ staged_dir.mkdir()
+ backup_dir.mkdir()
+ staged: list[tuple[Path, Path, Path]] = []
+ transaction_device = transaction_dir.stat().st_dev
+ for index, (target, text) in enumerate(updates):
+ if target.parent.stat().st_dev != transaction_device:
+ raise OSError(
+ f"cannot atomically publish across filesystems: {target}"
+ )
+ staged_path = staged_dir / f"{index:06d}.new"
+ backup_path = backup_dir / f"{index:06d}.bak"
+ staged_path.write_text(text, encoding="utf-8")
+ shutil.copymode(target, staged_path)
+ shutil.copy2(target, backup_path, follow_symlinks=False)
+ staged.append((target, staged_path, backup_path))
+
+ try:
+ for target, staged_path, backup_path in staged:
+ os.replace(staged_path, target)
+ published.append((target, backup_path))
+ except BaseException as publish_error:
+ rollback_errors: list[str] = []
+ for target, backup_path in reversed(published):
+ try:
+ os.replace(backup_path, target)
+ except BaseException as rollback_error:
+ rollback_errors.append(
+ f"could not restore {target}: "
+ f"{type(rollback_error).__name__}: {rollback_error}"
+ )
+ if rollback_errors:
+ preserve_transaction = True
+ raise RuntimeError(
+ f"update_spec publish failed ({publish_error}); rollback was "
+ f"incomplete: {'; '.join(rollback_errors)}; recovery directory: "
+ f"{transaction_dir}"
+ ) from publish_error
+ raise
+ finally:
+ if not preserve_transaction:
+ shutil.rmtree(transaction_dir, ignore_errors=True)
+
+
def replace_color_in_svgs(
svg_dir: Path, old_hex: str, new_hex: str, *, dry_run: bool = False
) -> list[tuple[Path, int]]:
@@ -86,31 +202,20 @@ def replace_color_in_svgs(
e.g. one file with 50 hits when the rest have 4-8 is likely a stray
HEX literal inside <text> content rather than a styling attribute.
- Two-phase: plan all file updates in memory, then write to disk. If any
- exception is raised during planning (e.g. bad HEX, read failure), no files
- are touched. This keeps svg_output/ and the caller's spec_lock.md write
- in a consistent pair: either everything is applied or nothing is.
+ Two-phase: plan all file updates in memory, then publish them with rollback.
+ If planning or publishing fails, the original files are retained.
When dry_run=True, the planning phase still runs (so bad HEX still raises
and callers see which files would change), but no disk writes happen. The
returned list describes the would-change files.
"""
- if not HEX_RE.match(old_hex) or not HEX_RE.match(new_hex):
- raise ValueError(f"not a HEX color: old={old_hex!r} new={new_hex!r}")
- pattern = re.compile(
- rf"{re.escape(old_hex)}(?![0-9A-Fa-f])",
- re.IGNORECASE,
- )
- planned: list[tuple[Path, str, int]] = []
- for svg in sorted(svg_dir.glob("*.svg")):
- text = svg.read_text(encoding="utf-8")
- new_text, n = pattern.subn(new_hex, text)
- if n > 0:
- planned.append((svg, new_text, n))
+ planned = _plan_color_updates(svg_dir, old_hex, new_hex)
if not dry_run:
- for svg, new_text, _ in planned:
- svg.write_text(new_text, encoding="utf-8")
- return [(p, n) for p, _, n in planned]
+ _publish_text_updates([
+ (svg, new_text)
+ for svg, new_text, _count in planned
+ ])
+ return [(path, count) for path, _text, count in planned]
def replace_font_family_in_svgs(
@@ -124,35 +229,20 @@ def replace_font_family_in_svgs(
Preserves the outer quote character when possible; if the new value contains
that same quote type, switches the outer quote to the other kind.
- Two-phase: plan all file updates in memory, then write to disk. The inner
- `_sub` may raise ValueError when the new value contains both quote kinds —
- when that happens in the planning phase, no files have been touched yet.
+ Two-phase: plan all file updates in memory, then publish them with rollback.
+ A conflicting quote style fails during planning, before files are touched.
When dry_run=True, the planning phase still runs (so the ValueError still
fires and callers see which files would change), but no disk writes happen.
The returned list describes the would-change files.
"""
- def _sub(m: re.Match[str]) -> str:
- prefix, quote, _inner = m.group(1), m.group(2), m.group(3)
- outer = quote
- if outer in new_value:
- outer = "'" if quote == '"' else '"'
- if outer in new_value:
- raise ValueError(
- f"new font_family value contains both ' and \" — cannot embed: {new_value!r}"
- )
- return f"{prefix}{outer}{new_value}{outer}"
-
- planned: list[tuple[Path, str, int]] = []
- for svg in sorted(svg_dir.glob("*.svg")):
- text = svg.read_text(encoding="utf-8")
- new_text, n = FONT_FAMILY_RE.subn(_sub, text)
- if n > 0 and new_text != text:
- planned.append((svg, new_text, n))
+ planned = _plan_font_family_updates(svg_dir, new_value)
if not dry_run:
- for svg, new_text, _ in planned:
- svg.write_text(new_text, encoding="utf-8")
- return [(p, n) for p, _, n in planned]
+ _publish_text_updates([
+ (svg, new_text)
+ for svg, new_text, _count in planned
+ ])
+ return [(path, count) for path, _text, count in planned]
def main() -> int:
@@ -219,19 +309,29 @@ def main() -> int:
if old_value == new_value:
print(f"no change: colors.{key} already = {new_value}")
return 0
- # SVGs first (may raise on bad HEX), then lock. Writing lock last
- # avoids a state where lock claims new_value but SVGs still hold
- # old_value — that state silences re-runs (parse_lock would then
- # see new_value == old_value and exit early).
try:
planned_lock = plan_lock_values(lock, "colors", {key: new_value})
except (KeyError, ValueError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
- changed = replace_color_in_svgs(svg_dir, old_value, new_value, dry_run=args.dry_run)
+ planned_svg = _plan_color_updates(svg_dir, old_value, new_value)
+ changed = [
+ (path, count)
+ for path, _text, count in planned_svg
+ ]
lock_changes = [(key, old_value, new_value)]
if not args.dry_run:
- lock.write_text(planned_lock, encoding="utf-8")
+ try:
+ _publish_text_updates([
+ *(
+ (path, new_text)
+ for path, new_text, _count in planned_svg
+ ),
+ (lock, planned_lock),
+ ])
+ except (OSError, RuntimeError, ValueError) as exc:
+ print(f"error: update was not published: {exc}", file=sys.stderr)
+ return 2
elif section == "typography" and key == "font_family":
family_keys = [
name
@@ -252,12 +352,26 @@ def main() -> int:
"typography",
{name: new_value for name in family_keys},
)
- changed = replace_font_family_in_svgs(svg_dir, new_value, dry_run=args.dry_run)
+ planned_svg = _plan_font_family_updates(svg_dir, new_value)
+ changed = [
+ (path, count)
+ for path, _text, count in planned_svg
+ ]
except (KeyError, ValueError) as e:
print(f"error: {e}", file=sys.stderr)
return 2
if not args.dry_run:
- lock.write_text(planned_lock, encoding="utf-8")
+ try:
+ _publish_text_updates([
+ *(
+ (path, new_text)
+ for path, new_text, _count in planned_svg
+ ),
+ (lock, planned_lock),
+ ])
+ except (OSError, RuntimeError, ValueError) as exc:
+ print(f"error: update was not published: {exc}", file=sys.stderr)
+ return 2
else:
print(
f"error: {section}.{key} is not supported by update_spec.py.\n"