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

feat(native-enhance): add scoped transitions and delivery safeguards

hugohe312be3e669519
diff --git a/skills/ppt-master/scripts/native_enhance_pptx_core.py b/skills/ppt-master/scripts/native_enhance_pptx_core.py
index c23d5d39..0c8ef1fd 100644
--- a/skills/ppt-master/scripts/native_enhance_pptx_core.py
+++ b/skills/ppt-master/scripts/native_enhance_pptx_core.py
@@ -6,8 +6,8 @@ Implementation core for the public native enhancement CLI and its legacy
narration compatibility entrypoint. It enhances an existing PPTX without
entering the SVG generation pipeline or modifying the original file.
-V1 enhancement modules: speaker notes, narration audio, slide auto-advance
-timings, and optional page transitions.
+Enhancement modules: read-only delivery checks, speaker notes, narration audio,
+slide auto-advance timings, and optional global or per-slide page transitions.
Usage:
python3 scripts/native_enhance_pptx.py init <source.pptx> [--name project_name]
@@ -20,12 +20,13 @@ Examples:
python3 scripts/native_enhance_pptx.py validate projects/fire_station_native_enhance_20260626
Dependencies:
- ffprobe for audio-duration-based auto-advance timings.
+ ffprobe for narration decodability and audio-duration validation.
"""
from __future__ import annotations
import argparse
+import hashlib
import json
import posixpath
import re
@@ -34,6 +35,7 @@ import subprocess
import sys
import tempfile
import zipfile
+from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
@@ -44,6 +46,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from pptx_delivery_check import audit_pptx_delivery # noqa: E402
from pptx_animations import ( # noqa: E402
object_animation_fingerprint,
validate_pptx_animation_package,
@@ -85,7 +88,10 @@ configure_utf8_stdio()
PROJECT_SCHEMA = "native_pptx_enhancement_project.v1"
+PLAN_SCHEMA = "native_pptx_enhancement_plan.v1"
+VALIDATION_SCHEMA = "native_pptx_enhancement_validation.v1"
LEGACY_PROJECT_SCHEMAS = {"native_narration_pptx_project.v1"}
+_WRITABLE_MODULES = ("notes", "audio", "timings", "transitions")
NOTES_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide"
PACKAGE_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
PRESENTATION_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"
@@ -100,8 +106,26 @@ CONTENT_TYPE_THEME = "application/vnd.openxmlformats-officedocument.theme+xml"
_NOTES_SLIDE_PART_RE = re.compile(
r"^ppt/notesSlides/notesSlide([1-9]\d*)\.xml$"
)
-
-
+_LEGACY_MISSING_NOTES_MASTER_RE = re.compile(
+ r"^ppt/notesSlides/_rels/notesSlide[1-9]\d*\.xml\.rels"
+ r" -> ppt/notesmasters/notesmaster[1-9]\d*\.xml$",
+ re.IGNORECASE,
+)
+_TRANSITION_MODULE_FIELDS = frozenset(
+ {
+ "enabled",
+ "requires_confirmation",
+ "status",
+ "effect",
+ "duration",
+ "effect_options",
+ "apply_without_audio",
+ "slides",
+ }
+)
+_TRANSITION_OVERRIDE_FIELDS = frozenset(
+ {"effect", "duration", "effect_options"}
+)
@dataclass(frozen=True)
class SlidePart:
index: int
@@ -109,6 +133,37 @@ class SlidePart:
slide_number: int
+@dataclass
+class MaterialReadiness:
+ note_paths: dict[int, Path]
+ audio_paths: dict[int, Path]
+ audio_durations: dict[int, float]
+ notes_count: int
+ audio_count: int
+ missing_notes: list[int]
+ invalid_notes: dict[int, str]
+ missing_audio: list[int]
+ invalid_audio: dict[int, str]
+ module_errors: list[str]
+
+ @property
+ def ready(self) -> bool:
+ return not (
+ self.missing_notes
+ or self.invalid_notes
+ or self.missing_audio
+ or self.invalid_audio
+ or self.module_errors
+ )
+
+
+@dataclass(frozen=True)
+class ResolvedTransitionPlan:
+ global_enter: EnterUpdate
+ slide_enters: Mapping[int, EnterUpdate]
+ apply_without_audio: bool
+
+
def _sanitize_slug(value: str) -> str:
slug = re.sub(r"[^0-9A-Za-z_-]+", "_", value).strip("_")
return slug or "native_enhance"
@@ -129,7 +184,10 @@ def _non_negative_seconds_arg(value: str) -> float:
def _read_json(path: Path) -> dict:
- return json.loads(path.read_text(encoding="utf-8"))
+ data = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(data, dict):
+ raise ValueError(f"JSON root must be an object: {path}")
+ return data
def _write_json(path: Path, data: dict) -> None:
@@ -139,6 +197,105 @@ def _write_json(path: Path, data: dict) -> None:
)
+def _write_preflight_report(
+ project_path: Path,
+ plan: dict,
+ modules: set[str],
+ *,
+ status: str,
+ **details: object,
+) -> dict:
+ report = {
+ "schema": VALIDATION_SCHEMA,
+ "status": status,
+ "phase": "preflight",
+ "plan_status": plan.get("status") or "missing",
+ "enabled_modules": sorted(modules),
+ **details,
+ }
+ validation_dir = project_path / "validation"
+ validation_dir.mkdir(exist_ok=True)
+ _write_json(validation_dir / "report.json", report)
+ return report
+
+
+def _delivery_issues(report: dict, field: str) -> list[dict]:
+ issues = report.get(field)
+ if not isinstance(issues, list):
+ return []
+ return [issue for issue in issues if isinstance(issue, dict)]
+
+
+def _fatal_source_delivery_messages(report: dict) -> list[str]:
+ fatal = [
+ issue
+ for issue in _delivery_issues(report, "errors")
+ if not (
+ issue.get("code") == "dangling_internal_relationship"
+ and isinstance(issue.get("message"), str)
+ and _LEGACY_MISSING_NOTES_MASTER_RE.fullmatch(
+ issue["message"]
+ )
+ is not None
+ )
+ ]
+ if fatal:
+ return [
+ str(issue.get("message") or issue)
+ for issue in fatal
+ ]
+ if report.get("status") == "failed" and not _delivery_issues(
+ report,
+ "errors",
+ ):
+ return ["delivery check failed without structured error details"]
+ return []
+
+
+def _new_delivery_errors(source: dict, candidate: dict) -> list[dict]:
+ source_keys = {
+ json.dumps(issue, ensure_ascii=False, sort_keys=True)
+ for issue in _delivery_issues(source, "errors")
+ }
+ return [
+ issue
+ for issue in _delivery_issues(candidate, "errors")
+ if json.dumps(issue, ensure_ascii=False, sort_keys=True)
+ not in source_keys
+ ]
+
+
+def _delivery_has_findings(report: dict) -> bool:
+ return bool(
+ _delivery_issues(report, "errors")
+ or _delivery_issues(report, "advisories")
+ )
+
+
+def _delivery_hidden_slide_indices(
+ report: dict,
+) -> tuple[int, ...] | None:
+ slides = report.get("slides")
+ hidden = slides.get("hidden") if isinstance(slides, dict) else None
+ if not isinstance(hidden, list):
+ return None
+ indices: list[int] = []
+ for item in hidden:
+ index = item.get("index") if isinstance(item, dict) else None
+ if isinstance(index, bool) or not isinstance(index, int):
+ return None
+ indices.append(index)
+ return tuple(indices)
+
+
+def _file_sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
def _is_relative_to(path: Path, parent: Path) -> bool:
try:
path.resolve().relative_to(parent.resolve())
@@ -337,6 +494,98 @@ def read_slide_parts(extract_dir: Path) -> list[SlidePart]:
return slide_parts
+def _source_state_errors(
+ project_path: Path,
+ project: dict,
+ source_pptx: Path,
+ slides: list[SlidePart],
+) -> list[str]:
+ """Return source-drift and slide-index consistency errors."""
+ errors: list[str] = []
+ actual_count = len(slides)
+ actual_roster = [slide.part_name for slide in slides]
+
+ expected_sha256 = project.get("source_sha256")
+ if expected_sha256 is not None:
+ if (
+ not isinstance(expected_sha256, str)
+ or re.fullmatch(r"[0-9a-f]{64}", expected_sha256) is None
+ ):
+ errors.append("project.json source_sha256 is not a lowercase SHA-256 digest")
+ elif _file_sha256(source_pptx) != expected_sha256:
+ errors.append("archived source PPTX SHA-256 no longer matches project.json")
+
+ expected_project_count = project.get("slide_count")
+ if isinstance(expected_project_count, bool) or not isinstance(
+ expected_project_count,
+ int,
+ ):
+ errors.append("project.json slide_count is not an integer")
+ elif expected_project_count != actual_count:
+ errors.append(
+ "archived source slide count no longer matches project.json: "
+ f"{actual_count} != {expected_project_count}"
+ )
+
+ expected_project_roster = project.get("slide_part_roster")
+ if expected_project_roster is not None:
+ if (
+ not isinstance(expected_project_roster, list)
+ or any(
+ not isinstance(part_name, str) or not part_name
+ for part_name in expected_project_roster
+ )
+ ):
+ errors.append("project.json slide_part_roster is not an array of part names")
+ elif expected_project_roster != actual_roster:
+ errors.append(
+ "archived source ordered slide-part roster no longer matches "
+ "project.json"
+ )
+
+ slide_index_path = project_path / "analysis" / "slide_index.json"
+ if not slide_index_path.is_file():
+ errors.append(f"slide index is missing: {slide_index_path}")
+ return errors
+ try:
+ slide_index = _read_json(slide_index_path)
+ except (OSError, json.JSONDecodeError) as exc:
+ errors.append(f"unable to read slide index: {exc}")
+ return errors
+
+ expected_index_count = slide_index.get("slide_count")
+ if isinstance(expected_index_count, bool) or not isinstance(
+ expected_index_count,
+ int,
+ ):
+ errors.append("slide_index.json slide_count is not an integer")
+ elif expected_index_count != actual_count:
+ errors.append(
+ "archived source slide count no longer matches slide_index.json: "
+ f"{actual_count} != {expected_index_count}"
+ )
+
+ indexed_slides = slide_index.get("slides")
+ if not isinstance(indexed_slides, list):
+ errors.append("slide_index.json slides is not an array")
+ return errors
+ expected_roster: list[str] = []
+ for index, item in enumerate(indexed_slides, 1):
+ part_name = item.get("part_name") if isinstance(item, dict) else None
+ if not isinstance(part_name, str) or not part_name:
+ errors.append(
+ f"slide_index.json slides[{index - 1}].part_name is invalid"
+ )
+ continue
+ expected_roster.append(part_name)
+ if len(expected_roster) == len(indexed_slides) and expected_roster != actual_roster:
+ errors.append(
+ "archived source ordered slide-part roster no longer matches "
+ "slide_index.json"
+ )
+ return errors
+
+
def _zip_dir(source_dir: Path, output_path: Path) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zf:
@@ -382,6 +631,131 @@ def _audio_path(audio_dir: Path, index: int) -> Path | None:
return None
+def _collect_material_readiness(
+ slides: list[SlidePart],
+ notes_dir: Path,
+ audio_dir: Path,
+ modules: set[str],
+) -> MaterialReadiness:
+ """Inspect enabled-module inputs once for both validation and application."""
+ notes_required = "notes" in modules
+ audio_required = "audio" in modules or "timings" in modules
+ timings_enabled = "timings" in modules
+ note_paths: dict[int, Path] = {}
+ audio_paths: dict[int, Path] = {}
+ audio_durations: dict[int, float] = {}
+ missing_notes: list[int] = []
+ invalid_notes: dict[int, str] = {}
+ missing_audio: list[int] = []
+ invalid_audio: dict[int, str] = {}
+
+ for slide in slides:
+ note = _note_path(notes_dir, slide.index)
+ if note is None:
+ if notes_required:
+ missing_notes.append(slide.index)
+ else:
+ try:
+ note_text = markdown_to_plain_text(
+ note.read_text(encoding="utf-8")
+ )
+ except (OSError, UnicodeError) as exc:
+ if notes_required:
+ invalid_notes[slide.index] = f"unable to read {note.name}: {exc}"
+ else:
+ if note_text:
+ note_paths[slide.index] = note
+ elif notes_required:
+ invalid_notes[slide.index] = f"{note.name} has no spoken text"
+
+ audio = _audio_path(audio_dir, slide.index)
+ if audio is None:
+ if audio_required:
+ missing_audio.append(slide.index)
+ continue
+ try:
+ if not audio.is_file() or audio.stat().st_size <= 0:
+ raise ValueError(f"{audio.name} is not a non-empty file")
+ except (OSError, ValueError) as exc:
+ if audio_required:
+ invalid_audio[slide.index] = str(exc)
+ continue
+
+ if audio_required:
+ duration = probe_audio_duration(audio)
+ if duration is None:
+ invalid_audio[slide.index] = (
+ f"unable to decode {audio.name} with ffprobe"
+ )
+ continue
+ if timings_enabled:
+ audio_durations[slide.index] = duration
+ audio_paths[slide.index] = audio
+
+ module_errors: list[str] = []
+ if timings_enabled and "audio" not in modules:
+ module_errors.append("timings requires the audio module")
+ return MaterialReadiness(
+ note_paths=note_paths,
+ audio_paths=audio_paths,
+ audio_durations=audio_durations,
+ notes_count=len(note_paths),
+ audio_count=len(audio_paths),
+ missing_notes=missing_notes,
+ invalid_notes=invalid_notes,
+ missing_audio=missing_audio,
+ invalid_audio=invalid_audio,
+ module_errors=module_errors,
+ )
+
+
+def _material_readiness_messages(readiness: MaterialReadiness) -> list[str]:
+ messages = list(readiness.module_errors)
+ if readiness.missing_notes:
+ messages.append(
+ "missing notes for slide(s): "
+ + ", ".join(str(index) for index in readiness.missing_notes)
+ )
+ if readiness.invalid_notes:
+ messages.append(
+ "invalid notes: "
+ + "; ".join(
+ f"slide {index}: {reason}"
+ for index, reason in sorted(readiness.invalid_notes.items())
+ )
+ )
+ if readiness.missing_audio:
+ messages.append(
+ "missing audio for slide(s): "
+ + ", ".join(str(index) for index in readiness.missing_audio)
+ )
+ if readiness.invalid_audio:
+ messages.append(
+ "invalid audio: "
+ + "; ".join(
+ f"slide {index}: {reason}"
+ for index, reason in sorted(readiness.invalid_audio.items())
+ )
+ )
+ return messages
+
+
+def _material_readiness_report_fields(
+ readiness: MaterialReadiness,
+) -> dict[str, object]:
+ return {
+ "notes_count": readiness.notes_count,
+ "audio_count": readiness.audio_count,
+ "missing_notes": readiness.missing_notes,
+ "invalid_notes": sorted(readiness.invalid_notes),
+ "invalid_note_reasons": readiness.invalid_notes,
+ "missing_audio": readiness.missing_audio,
+ "invalid_audio": sorted(readiness.invalid_audio),
+ "invalid_audio_reasons": readiness.invalid_audio,
+ "module_errors": readiness.module_errors,
+ }
+
+
def _add_override(content_types: str, part_name: str, content_type: str) -> str:
if re.search(
rf'<Override\b[^>]*\bPartName="/{re.escape(part_name)}"[^>]*/>',
@@ -445,6 +819,61 @@ def _apply_notes(
return notes_part
+def _native_audio_carriers(
+ extract_dir: Path,
+ slides: list[SlidePart],
+) -> dict[int, list[str]]:
+ """Return existing tool-owned narration carrier names by public slide."""
+ carriers: dict[int, list[str]] = {}
+ for slide in slides:
+ slide_root = ET.parse(extract_dir / slide.part_name).getroot()
+ names = sorted(
+ {
+ name
+ for element in slide_root.iter(
+ f"{{{PRESENTATION_NS}}}cNvPr"
+ )
+ if (name := element.attrib.get("name", "")).startswith(
+ "native_enhance_audio_"
+ )
+ }
+ )
+ if names:
+ carriers[slide.index] = names
+ return carriers
+
+
+def _allocate_media_name(media_dir: Path, preferred_name: str) -> str:
+ preferred_path = media_dir / preferred_name
+ if not preferred_path.exists():
+ return preferred_name
+ stem = preferred_path.stem
+ suffix = preferred_path.suffix
+ index = 2
+ while True:
+ candidate_name = f"{stem}_{index}{suffix}"
+ if not (media_dir / candidate_name).exists():
+ return candidate_name
+ index += 1
+
+
+def _ensure_audio_poster(media_dir: Path) -> str:
+ preferred_name = "native_enhance_audio_poster.png"
+ for candidate in sorted(
+ media_dir.glob("native_enhance_audio_poster*.png")
+ ):
+ if not candidate.is_file():
+ continue
+ try:
+ if candidate.read_bytes() == AUDIO_MARKER_PNG_BYTES:
+ return candidate.name
+ except OSError:
+ continue
+ poster_name = _allocate_media_name(media_dir, preferred_name)
+ (media_dir / poster_name).write_bytes(AUDIO_MARKER_PNG_BYTES)
+ return poster_name
+
+
def _apply_audio(
extract_dir: Path,
slide: SlidePart,
@@ -453,18 +882,19 @@ def _apply_audio(
enter: EnterUpdate,
timings_enabled: bool,
narration_padding: float,
+ audio_duration: float | None = None,
) -> bool:
media_dir = extract_dir / "ppt" / "media"
media_dir.mkdir(parents=True, exist_ok=True)
ext = audio_path.suffix.lower()
- media_name = f"native_enhance_audio_{slide.index:03d}{ext}"
+ media_name = _allocate_media_name(
+ media_dir,
+ f"native_enhance_audio_{slide.index:03d}{ext}",
+ )
shutil.copy2(audio_path, media_dir / media_name)
- poster_name = "native_enhance_audio_poster.png"
- poster_path = media_dir / poster_name
- if not poster_path.exists():
- poster_path.write_bytes(AUDIO_MARKER_PNG_BYTES)
+ poster_name = _ensure_audio_poster(media_dir)
slide_rels = _relationship_file_for_part(extract_dir, slide.part_name)
_ensure_rels_file(slide_rels)
@@ -487,7 +917,9 @@ def _apply_audio(
advance = AdvanceUpdate(mode="preserve")
if timings_enabled:
- duration = probe_audio_duration(audio_path)
+ duration = audio_duration
+ if duration is None:
+ duration = probe_audio_duration(audio_path)
if duration is None:
raise RuntimeError(f"Unable to read narration duration with ffprobe: {audio_path}")
advance = AdvanceUpdate(
@@ -537,6 +969,44 @@ def _project_paths(project_path: Path) -> tuple[Path, Path, Path, Path]:
return source_pptx, notes_dir, audio_dir, exports_dir
+def _output_path_error(
+ project_path: Path,
+ project: dict,
+ source_pptx: Path,
+ output_path: Path,
+) -> str | None:
+ if output_path.suffix.lower() != ".pptx":
+ return f"output must use a .pptx extension: {output_path}"
+ if output_path == source_pptx.resolve():
+ return "output must not overwrite the archived source PPTX"
+
+ source_import = project.get("source_import")
+ if isinstance(source_import, dict):
+ original_path = source_import.get("original_path")
+ if isinstance(original_path, str) and original_path:
+ try:
+ original = Path(original_path).expanduser().resolve()
+ except OSError:
+ original = None
+ if original is not None and output_path == original:
+ return "output must not overwrite the original source PPTX"
+
+ protected = (
+ project_path / "sources",
+ project_path / "analysis",
+ project_path / "notes",
+ project_path / "audio",
+ project_path / "validation",
+ )
+ for directory in protected:
+ if _is_relative_to(output_path, directory):
+ return (
+ "output must not be written inside native-enhance control "
+ f"directory: {directory}"
+ )
+ return None
+
+
def _plan_path(project_path: Path) -> Path:
return project_path / "analysis" / "enhancement_plan.json"
@@ -551,11 +1021,12 @@ def _load_enhancement_plan(project_path: Path) -> dict:
def _enabled_modules(plan: dict) -> set[str]:
modules = plan.get("modules")
if not isinstance(modules, dict):
- return {"notes", "audio", "timings", "transitions"}
+ return set(_WRITABLE_MODULES)
enabled: set[str] = set()
- for name, config in modules.items():
+ for name in _WRITABLE_MODULES:
+ config = modules.get(name)
if isinstance(config, dict) and config.get("enabled") is True:
- enabled.add(str(name))
+ enabled.add(name)
return enabled
@@ -604,11 +1075,14 @@ def _plan_confirmed(plan: dict) -> bool:
def _native_transition_config(
transition: str,
duration: float,
+ effect_options: object = None,
) -> dict[str, object]:
if transition == "none":
+ normalize_transition_effect_request(transition, effect_options)
return {"effect": "none", "duration": duration}
effect, effect_options = normalize_transition_effect_request(
transition,
+ effect_options,
allow_none=False,
)
config: dict[str, object] = {
@@ -620,52 +1094,203 @@ def _native_transition_config(
return config
+def _module_config(plan: dict, name: str) -> dict:
+ modules = plan.get("modules")
+ if not isinstance(modules, dict):
+ return {}
+ config = modules.get(name)
+ return config if isinstance(config, dict) else {}
+
+
+def _preserved_enabled(plan: dict, name: str, default: bool) -> bool:
+ config = _module_config(plan, name)
+ if "enabled" not in config:
+ return default
+ value = config["enabled"]
+ if not isinstance(value, bool):
+ raise ValueError(
+ f"enhancement plan module {name}.enabled must be a boolean"
+ )
+ return value
+
+
+def _resolved_draft_transition_config(
+ project: dict,
+ existing_plan: dict,
+ *,
+ transition: str | None,
+ transition_duration: float | None,
+ apply_transition_without_audio: bool | None,
+) -> tuple[bool, dict[str, object]]:
+ existing = _module_config(existing_plan, "transitions")
+ project_default = (
+ project.get("transition")
+ if isinstance(project.get("transition"), dict)
+ else {}
+ )
+
+ if transition is not None:
+ raw_effect: object = transition
+ raw_options: object = None
+ elif "effect" in existing:
+ raw_effect = existing["effect"]
+ raw_options = existing.get("effect_options")
+ elif "effect" in project_default:
+ raw_effect = project_default["effect"]
+ raw_options = project_default.get("effect_options")
+ else:
+ raw_effect = "fade"
+ raw_options = None
+
+ if not isinstance(raw_effect, str):
+ raise ValueError("transition effect must be a string")
+ if transition_duration is not None:
+ raw_duration: object = transition_duration
+ elif "duration" in existing:
+ raw_duration = existing["duration"]
+ elif "duration" in project_default:
+ raw_duration = project_default["duration"]
+ else:
+ raw_duration = 0.5
+ duration = validate_seconds(
+ raw_duration,
+ "transition duration",
+ allow_zero=False,
+ )
+ config = _native_transition_config(
+ raw_effect,
+ duration,
+ raw_options,
+ )
+
+ if apply_transition_without_audio is None:
+ raw_apply_without_audio = existing.get(
+ "apply_without_audio",
+ False,
+ )
+ else:
+ raw_apply_without_audio = apply_transition_without_audio
+ if not isinstance(raw_apply_without_audio, bool):
+ raise ValueError("transition apply_without_audio must be a boolean")
+ config["apply_without_audio"] = raw_apply_without_audio
+
+ if "slides" in existing:
+ slides = existing["slides"]
+ if not isinstance(slides, dict):
+ raise ValueError("transition slides must be an object")
+ config["slides"] = {
+ str(key): dict(value) if isinstance(value, dict) else value
+ for key, value in slides.items()
+ }
+
+ if transition is not None:
+ enabled = transition != "none"
+ else:
+ enabled = _preserved_enabled(
+ existing_plan,
+ "transitions",
+ raw_effect != "none",
+ )
+ return enabled, config
+
+
def _build_enhancement_plan(
project: dict,
*,
slide_count: int,
notes_count: int,
audio_count: int,
- transition: str,
- transition_duration: float,
- narration_padding: float,
- apply_transition_without_audio: bool,
+ transition: str | None,
+ transition_duration: float | None,
+ narration_padding: float | None,
+ apply_transition_without_audio: bool | None,
+ existing_plan: dict | None = None,
) -> dict:
- transition_config = _native_transition_config(
- transition,
- transition_duration,
+ previous = existing_plan or {}
+ notes_enabled = _preserved_enabled(previous, "notes", True)
+ audio_enabled = _preserved_enabled(previous, "audio", True)
+ timings_enabled = _preserved_enabled(previous, "timings", True)
+ previous_timings = _module_config(previous, "timings")
+ raw_padding: object
+ if narration_padding is not None:
+ raw_padding = narration_padding
+ else:
+ raw_padding = previous_timings.get("narration_padding", 0.4)
+ resolved_padding = validate_seconds(
+ raw_padding,
+ "narration padding",
+ allow_zero=True,
+ )
+ transitions_enabled, transition_config = _resolved_draft_transition_config(
+ project,
+ previous,
+ transition=transition,
+ transition_duration=transition_duration,
+ apply_transition_without_audio=apply_transition_without_audio,
)
return {
- "schema": "native_pptx_enhancement_plan.v1",
+ "schema": PLAN_SCHEMA,
"status": "draft",
"source_pptx": project.get("source_pptx"),
"slide_count": slide_count,
"modules": {
"notes": {
- "enabled": True,
+ "enabled": notes_enabled,
"requires_confirmation": True,
- "status": "ready" if notes_count == slide_count else "needs_notes",
- "coverage": {"ready": notes_count, "total": slide_count},
+ "status": (
+ "disabled"
+ if not notes_enabled
+ else (
+ "coverage_complete"
+ if notes_count == slide_count
+ else "needs_notes"
+ )
+ ),
+ "coverage": {"present": notes_count, "total": slide_count},
},
"audio": {
- "enabled": True,
+ "enabled": audio_enabled,
"requires_confirmation": True,
- "status": "ready" if audio_count == slide_count else "needs_audio",
- "coverage": {"ready": audio_count, "total": slide_count},
+ "status": (
+ "disabled"
+ if not audio_enabled
+ else (
+ "coverage_complete"
+ if audio_count == slide_count
+ else "needs_audio"
+ )
+ ),
+ "coverage": {"present": audio_count, "total": slide_count},
+ "decodability": "unchecked",
},
"timings": {
- "enabled": True,
+ "enabled": timings_enabled,
"requires_confirmation": True,
- "status": "ready" if audio_count == slide_count else "blocked_until_audio",
+ "status": (
+ "disabled"
+ if not timings_enabled
+ else (
+ "audio_coverage_complete"
+ if audio_enabled and audio_count == slide_count
+ else "blocked_until_audio"
+ )
+ ),
"source": "audio_duration",
- "narration_padding": narration_padding,
+ "narration_padding": resolved_padding,
},
"transitions": {
- "enabled": transition != "none",
+ "enabled": transitions_enabled,
"requires_confirmation": True,
- "status": "ready",
+ "status": (
+ "ready"
+ if (
+ transitions_enabled
+ or transition_config.get("effect") == "none"
+ or bool(transition_config.get("slides"))
+ )
+ else "disabled"
+ ),
**transition_config,
- "apply_without_audio": apply_transition_without_audio,
},
},
"not_in_v1": [
@@ -678,12 +1303,294 @@ def _build_enhancement_plan(
}
+def _resolve_slide_enter(
+ base: EnterUpdate,
+ override: dict,
+ *,
+ slide_index: int,
+) -> EnterUpdate:
+ unknown = sorted(set(override) - _TRANSITION_OVERRIDE_FIELDS)
+ if unknown:
+ raise ValueError(
+ f"transition slides.{slide_index} has unknown field(s): "
+ + ", ".join(unknown)
+ )
+
+ raw_duration = override.get("duration", base.duration)
+ duration = validate_seconds(
+ raw_duration,
+ f"transition slides.{slide_index}.duration",
+ allow_zero=False,
+ )
+ effect = override.get("effect")
+ if effect == "preserve":
+ if "effect_options" in override:
+ raise ValueError(
+ f"transition slides.{slide_index} preserve cannot have "
+ "effect_options"
+ )
+ return EnterUpdate(policy="preserve", duration=duration)
+
+ if effect is None:
+ if base.policy == "preserve":
+ if "effect_options" in override:
+ raise ValueError(
+ f"transition slides.{slide_index} effect_options requires "
+ "a native effect"
+ )
+ return EnterUpdate(policy="preserve", duration=duration)
+ if base.policy == "none":
+ if "effect_options" in override:
+ raise ValueError(
+ f"transition slides.{slide_index} none cannot have "
+ "effect_options"
+ )
+ return EnterUpdate(policy="none", effect=None, duration=duration)
+ effect = base.effect
+ effect_options = override.get(
+ "effect_options",
+ base.effect_options,
+ )
+ else:
+ if not isinstance(effect, str):
+ raise ValueError(
+ f"transition slides.{slide_index}.effect must be a string"
+ )
+ effect_options = override.get("effect_options")
+
+ return _resolve_enter_update(
+ cli_effect=None,
+ configured_effect=effect,
+ configured_effect_options=effect_options,
+ transitions_enabled=True,
+ duration=duration,
+ )
+
+
+def _validate_plan_modules(plan: dict) -> None:
+ if plan and plan.get("schema") != PLAN_SCHEMA:
+ raise ValueError(
+ f"unsupported enhancement plan schema: {plan.get('schema')!r}"
+ )
+ modules_cfg = plan.get("modules")
+ if modules_cfg is None:
+ return
+ if not isinstance(modules_cfg, dict):
+ raise ValueError("enhancement plan modules must be an object")
+
+ unknown_modules = sorted(set(modules_cfg) - set(_WRITABLE_MODULES))
+ if unknown_modules:
+ raise ValueError(
+ "enhancement plan has unknown module(s): "
+ + ", ".join(unknown_modules)
+ )
+ if plan.get("schema") == PLAN_SCHEMA:
+ missing_modules = [
+ name
+ for name in _WRITABLE_MODULES
+ if name not in modules_cfg
+ ]
+ if missing_modules:
+ raise ValueError(
+ "enhancement plan is missing module(s): "
+ + ", ".join(missing_modules)
+ )
+ for name in _WRITABLE_MODULES:
+ config = modules_cfg.get(name)
+ if config is not None and not isinstance(config, dict):
+ raise ValueError(
+ f"enhancement plan module {name} must be an object"
+ )
+ if (
+ isinstance(config, dict)
+ and (
+ "enabled" not in config
+ or not isinstance(config["enabled"], bool)
+ )
+ ):
+ raise ValueError(
+ f"enhancement plan module {name}.enabled must be a boolean"
+ )
+
+
+def _resolve_transition_plan(
+ project: dict,
+ plan: dict,
+ slides: list[SlidePart],
+ *,
+ cli_effect: str | None = None,
+ cli_duration: float | None = None,
+ cli_apply_without_audio: bool = False,
+) -> ResolvedTransitionPlan:
+ _validate_plan_modules(plan)
+ plan_slide_count = plan.get("slide_count")
+ if plan_slide_count is not None and plan_slide_count != len(slides):
+ raise ValueError(
+ "enhancement plan slide_count no longer matches the archived "
+ f"source: {plan_slide_count!r} != {len(slides)}"
+ )
+
+ modules = _enabled_modules(plan)
+ transitions_cfg = _module_config(plan, "transitions")
+ unknown = sorted(set(transitions_cfg) - _TRANSITION_MODULE_FIELDS)
+ if unknown:
+ raise ValueError(
+ "transition module has unknown field(s): " + ", ".join(unknown)
+ )
+
+ project_transition = (
+ project.get("transition")
+ if isinstance(project.get("transition"), dict)
+ else {}
+ )
+ if (
+ cli_effect is None
+ and "effect_options" in transitions_cfg
+ and "effect" not in transitions_cfg
+ ):
+ raise ValueError("transition effect_options requires an explicit effect")
+ if (
+ cli_effect is None
+ and "effect_options" in project_transition
+ and "effect" not in project_transition
+ and "effect" not in transitions_cfg
+ ):
+ raise ValueError("transition effect_options requires an explicit effect")
+
+ if "effect" in transitions_cfg:
+ configured_effect = transitions_cfg["effect"]
+ configured_options = transitions_cfg.get("effect_options")
+ elif "effect" in project_transition:
+ configured_effect = project_transition["effect"]
+ configured_options = project_transition.get("effect_options")
+ else:
+ configured_effect = "fade"
+ configured_options = None
+
+ if cli_duration is not None:
+ raw_duration: object = cli_duration
+ elif "duration" in transitions_cfg:
+ raw_duration = transitions_cfg["duration"]
+ elif "duration" in project_transition:
+ raw_duration = project_transition["duration"]
+ else:
+ raw_duration = 0.5
+ duration = validate_seconds(
+ raw_duration,
+ "transition duration",
+ allow_zero=False,
+ )
+
+ selected_base = _resolve_enter_update(
+ cli_effect=cli_effect,
+ configured_effect=configured_effect,
+ configured_effect_options=configured_options,
+ transitions_enabled=True,
+ duration=duration,
+ )
+ global_enter = _resolve_enter_update(
+ cli_effect=cli_effect,
+ configured_effect=configured_effect,
+ configured_effect_options=configured_options,
+ transitions_enabled="transitions" in modules,
+ duration=duration,
+ )
+
+ raw_apply_without_audio = transitions_cfg.get(
+ "apply_without_audio",
+ False,
+ )
+ if not isinstance(raw_apply_without_audio, bool):
+ raise ValueError("transition apply_without_audio must be a boolean")
+ apply_without_audio = (
+ cli_apply_without_audio or raw_apply_without_audio
+ )
+
+ raw_slides = transitions_cfg.get("slides", {})
+ if not isinstance(raw_slides, dict):
+ raise ValueError("transition slides must be an object")
+ valid_indices = {slide.index for slide in slides}
+ slide_enters: dict[int, EnterUpdate] = {}
+ for raw_index, override in raw_slides.items():
+ if (
+ not isinstance(raw_index, str)
+ or re.fullmatch(r"[1-9]\d*", raw_index) is None
+ ):
+ raise ValueError(
+ f"transition slide key must be a canonical 1-based index: "
+ f"{raw_index!r}"
+ )
+ slide_index = int(raw_index)
+ if slide_index not in valid_indices:
+ raise ValueError(
+ f"transition slide index is outside the source roster: "
+ f"{slide_index}"
+ )
+ if not isinstance(override, dict):
+ raise ValueError(
+ f"transition slides.{slide_index} must be an object"
+ )
+ slide_enters[slide_index] = _resolve_slide_enter(
+ selected_base,
+ override,
+ slide_index=slide_index,
+ )
+
+ if (
+ ("transitions" in modules or cli_effect is not None)
+ and "audio" not in modules
+ and not apply_without_audio
+ and not slide_enters
+ ):
+ raise ValueError(
+ "transitions is enabled, but no slides are reachable: enable audio, "
+ "set apply_without_audio=true, or add transitions.slides entries"
+ )
+
+ return ResolvedTransitionPlan(
+ global_enter=global_enter,
+ slide_enters=slide_enters,
+ apply_without_audio=apply_without_audio,
+ )
+
+
+def _apply_transition_only(
+ extract_dir: Path,
+ slide: SlidePart,
+ enter: EnterUpdate,
+) -> bool:
+ if enter.policy == "preserve":
+ return False
+ slide_xml_path = extract_dir / slide.part_name
+ slide_xml = slide_xml_path.read_text(encoding="utf-8")
+ source_animation_fingerprint = object_animation_fingerprint(slide_xml)
+ slide_xml, _uses_timings = apply_slide_motion_xml(
+ slide_xml,
+ enter=enter,
+ advance=AdvanceUpdate(mode="preserve"),
+ )
+ if object_animation_fingerprint(slide_xml) != source_animation_fingerprint:
+ raise RuntimeError(
+ f"Slide {slide.index} object animations changed while updating "
+ "the transition"
+ )
+ slide_xml_path.write_text(slide_xml, encoding="utf-8")
+ return True
+
+
def init_project(args: argparse.Namespace) -> int:
source_pptx = Path(args.source_pptx).expanduser().resolve()
if not source_pptx.exists() or source_pptx.suffix.lower() != ".pptx":
print(f"error: expected an existing .pptx file: {source_pptx}", file=sys.stderr)
return 1
+ source_delivery = audit_pptx_delivery(source_pptx)
+ fatal_delivery_messages = _fatal_source_delivery_messages(source_delivery)
+ if fatal_delivery_messages:
+ for message in fatal_delivery_messages:
+ print(f"error: {message}", file=sys.stderr)
+ return 1
+
stem = _sanitize_slug(args.name or source_pptx.stem)
date = datetime.now().strftime("%Y%m%d")
project_path = (
@@ -718,6 +1625,7 @@ def init_project(args: argparse.Namespace) -> int:
extract_dir = Path(tmp) / "pptx"
_extract_pptx(archived_pptx, extract_dir)
slide_parts = read_slide_parts(extract_dir)
+ source_sha256 = _file_sha256(archived_pptx)
slide_index = {
"schema": "native_pptx_enhancement_slide_index.v1",
@@ -739,14 +1647,22 @@ def init_project(args: argparse.Namespace) -> int:
project = {
"schema": PROJECT_SCHEMA,
"kind": "native_pptx_enhancement",
- "modules": ["notes", "audio", "timings", "transitions"],
+ "modules": [
+ "notes",
+ "audio",
+ "timings",
+ "transitions",
+ "delivery.check",
+ ],
"source_pptx": f"sources/{source_pptx.name}",
"source_markdown": f"sources/{source_pptx.stem}.md",
"source_import": {
"mode": source_import_mode,
"original_path": str(source_pptx),
},
+ "source_sha256": source_sha256,
"slide_count": len(slide_parts),
+ "slide_part_roster": [slide.part_name for slide in slide_parts],
"notes_dir": "notes",
"audio_dir": "audio",
"exports_dir": "exports",
@@ -772,6 +1688,23 @@ def init_project(args: argparse.Namespace) -> int:
apply_transition_without_audio=args.apply_transition_without_audio,
)
_write_json(_plan_path(project_path), plan)
+ source_delivery_file = source_delivery.get("file")
+ if isinstance(source_delivery_file, dict):
+ source_delivery_file["path"] = str(archived_pptx.resolve())
+ _write_json(
+ project_path / "validation" / "report.json",
+ {
+ "schema": VALIDATION_SCHEMA,
+ "status": (
+ "passed-with-advisories"
+ if _delivery_has_findings(source_delivery)
+ else "passed"
+ ),
+ "phase": "intake",
+ "source_delivery_policy": "preserve-baseline",
+ "delivery_check": source_delivery,
+ },
+ )
print(f"Project: {project_path}", file=sys.stderr)
print(f"Slides: {len(slide_parts)}", file=sys.stderr)
@@ -793,23 +1726,53 @@ def plan_project(args: argparse.Namespace) -> int:
return 1
source_pptx, notes_dir, audio_dir, _exports_dir = _project_paths(project_path)
+ source_delivery = audit_pptx_delivery(source_pptx)
+ fatal_delivery_messages = _fatal_source_delivery_messages(source_delivery)
+ if fatal_delivery_messages:
+ for message in fatal_delivery_messages:
+ print(f"error: {message}", file=sys.stderr)
+ return 1
+
with tempfile.TemporaryDirectory(prefix="native-enhance-plan-") as tmp:
extract_dir = Path(tmp) / "pptx"
_extract_pptx(source_pptx, extract_dir)
slides = read_slide_parts(extract_dir)
- notes_count = sum(1 for slide in slides if _note_path(notes_dir, slide.index) is not None)
- audio_count = sum(1 for slide in slides if _audio_path(audio_dir, slide.index) is not None)
- plan = _build_enhancement_plan(
+ source_errors = _source_state_errors(
+ project_path,
project,
- slide_count=len(slides),
- notes_count=notes_count,
- audio_count=audio_count,
- transition=args.transition,
- transition_duration=args.transition_duration,
- narration_padding=args.narration_padding,
- apply_transition_without_audio=args.apply_transition_without_audio,
+ source_pptx,
+ slides,
)
+ if source_errors:
+ for error in source_errors:
+ print(f"error: {error}", file=sys.stderr)
+ return 1
+
+ existing_plan = _load_enhancement_plan(project_path)
+ try:
+ _validate_plan_modules(existing_plan)
+ readiness = _collect_material_readiness(
+ slides,
+ notes_dir,
+ audio_dir,
+ set(),
+ )
+ plan = _build_enhancement_plan(
+ project,
+ slide_count=len(slides),
+ notes_count=readiness.notes_count,
+ audio_count=readiness.audio_count,
+ transition=args.transition,
+ transition_duration=args.transition_duration,
+ narration_padding=args.narration_padding,
+ apply_transition_without_audio=args.apply_transition_without_audio,
+ existing_plan=existing_plan,
+ )
+ _resolve_transition_plan(project, plan, slides)
+ except ValueError as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
_write_json(_plan_path(project_path), plan)
print(json.dumps(plan, ensure_ascii=False, indent=2))
print(f"Plan written: {_plan_path(project_path)}", file=sys.stderr)
@@ -828,54 +1791,63 @@ def apply_project(args: argparse.Namespace) -> int:
return 1
source_pptx, notes_dir, audio_dir, exports_dir = _project_paths(project_path)
- transition_cfg = project.get("transition", {}) if isinstance(project.get("transition"), dict) else {}
plan = _load_enhancement_plan(project_path)
- if not _plan_confirmed(plan) and not args.force:
- print(
- f"error: enhancement plan is not confirmed: {_plan_path(project_path)} "
- "(run plan, get user confirmation, set status to \"confirmed\", or pass --force)",
- file=sys.stderr,
+ modules = _enabled_modules(plan)
+
+ def fail_preflight(
+ messages: list[str],
+ *,
+ status: str = "failed",
+ **details: object,
+ ) -> int:
+ _write_preflight_report(
+ project_path,
+ plan,
+ modules,
+ status=status,
+ errors=messages,
+ **details,
)
+ for message in messages:
+ print(f"error: {message}", file=sys.stderr)
return 1
- modules = _enabled_modules(plan)
- modules_cfg = plan.get("modules") if isinstance(plan.get("modules"), dict) else {}
- transitions_cfg = modules_cfg.get("transitions", {})
- if not isinstance(transitions_cfg, dict):
- transitions_cfg = {}
- timings_cfg = modules_cfg.get("timings", {})
- if not isinstance(timings_cfg, dict):
- timings_cfg = {}
+ _write_preflight_report(
+ project_path,
+ plan,
+ modules,
+ status="running",
+ )
+ if not _plan_confirmed(plan) and not args.force:
+ return fail_preflight(
+ [
+ f"enhancement plan is not confirmed: {_plan_path(project_path)} "
+ "(run plan, get user confirmation, set status to "
+ "\"confirmed\", or pass --force)"
+ ]
+ )
- transition_options_without_effect = (
- (
- "effect_options" in transitions_cfg
- and "effect" not in transitions_cfg
+ try:
+ _validate_plan_modules(plan)
+ except ValueError as exc:
+ return fail_preflight(
+ [str(exc)],
+ plan_errors=[str(exc)],
)
- or (
- "effect_options" in transition_cfg
- and "effect" not in transition_cfg
- and "effect" not in transitions_cfg
+
+ source_delivery = audit_pptx_delivery(source_pptx)
+ fatal_delivery_messages = _fatal_source_delivery_messages(source_delivery)
+ if fatal_delivery_messages:
+ return fail_preflight(
+ fatal_delivery_messages,
+ fatal_delivery_errors=fatal_delivery_messages,
+ delivery_check=source_delivery,
)
- )
- if "effect" in transitions_cfg:
- configured_effect = transitions_cfg["effect"]
- configured_effect_options = transitions_cfg.get("effect_options")
- elif "effect" in transition_cfg:
- configured_effect = transition_cfg["effect"]
- configured_effect_options = transition_cfg.get("effect_options")
- else:
- configured_effect = "fade"
- configured_effect_options = None
- if args.transition_duration is not None:
- raw_transition_duration = args.transition_duration
- elif "duration" in transitions_cfg:
- raw_transition_duration = transitions_cfg["duration"]
- elif "duration" in transition_cfg:
- raw_transition_duration = transition_cfg["duration"]
- else:
- raw_transition_duration = 0.5
+ modules_cfg = plan.get("modules") if isinstance(plan.get("modules"), dict) else {}
+ timings_cfg = modules_cfg.get("timings", {})
+ if not isinstance(timings_cfg, dict):
+ timings_cfg = {}
if args.narration_padding is not None:
raw_narration_padding = args.narration_padding
@@ -885,18 +1857,6 @@ def apply_project(args: argparse.Namespace) -> int:
raw_narration_padding = 0.4
try:
- if args.transition is None and transition_options_without_effect:
- raise ValueError(
- "transition effect_options requires an explicit effect"
- )
- if args.transition is not None or "transitions" in modules:
- transition_duration = validate_seconds(
- raw_transition_duration,
- "transition duration",
- allow_zero=False,
- )
- else:
- transition_duration = 0.5
if "timings" in modules:
narration_padding = validate_seconds(
raw_narration_padding,
@@ -905,49 +1865,120 @@ def apply_project(args: argparse.Namespace) -> int:
)
else:
narration_padding = 0.4
- enter_update = _resolve_enter_update(
- cli_effect=args.transition,
- configured_effect=configured_effect,
- configured_effect_options=configured_effect_options,
- transitions_enabled="transitions" in modules,
- duration=transition_duration,
- )
except ValueError as exc:
- print(f"error: {exc}", file=sys.stderr)
- return 1
-
- apply_transition_without_audio = (
- args.apply_transition_without_audio
- or bool(transitions_cfg.get("apply_without_audio"))
- )
+ return fail_preflight([str(exc)])
output_path = (
Path(args.output).expanduser().resolve()
if args.output
else exports_dir / f"{source_pptx.stem}_enhanced.pptx"
)
+ output_error = _output_path_error(
+ project_path,
+ project,
+ source_pptx,
+ output_path,
+ )
+ if output_error:
+ return fail_preflight([output_error])
if output_path.exists() and not args.overwrite:
- print(f"error: output already exists, pass --overwrite: {output_path}", file=sys.stderr)
- return 1
+ return fail_preflight(
+ [f"output already exists, pass --overwrite: {output_path}"]
+ )
with tempfile.TemporaryDirectory(prefix="native-enhance-pptx-") as tmp:
extract_dir = Path(tmp) / "pptx"
_extract_pptx(source_pptx, extract_dir)
slides = read_slide_parts(extract_dir)
+ source_errors = _source_state_errors(
+ project_path,
+ project,
+ source_pptx,
+ slides,
+ )
+ if source_errors:
+ return fail_preflight(
+ source_errors,
+ source_errors=source_errors,
+ delivery_check=source_delivery,
+ )
+
+ try:
+ resolved_transitions = _resolve_transition_plan(
+ project,
+ plan,
+ slides,
+ cli_effect=args.transition,
+ cli_duration=args.transition_duration,
+ cli_apply_without_audio=args.apply_transition_without_audio,
+ )
+ except ValueError as exc:
+ return fail_preflight(
+ [str(exc)],
+ transition_errors=[str(exc)],
+ delivery_check=source_delivery,
+ )
+
+ readiness = _collect_material_readiness(
+ slides,
+ notes_dir,
+ audio_dir,
+ modules,
+ )
+ if not readiness.ready:
+ return fail_preflight(
+ _material_readiness_messages(readiness),
+ status=(
+ "failed"
+ if readiness.module_errors
+ else "needs-materials"
+ ),
+ notes_required="notes" in modules,
+ audio_required=(
+ "audio" in modules or "timings" in modules
+ ),
+ delivery_check=source_delivery,
+ **_material_readiness_report_fields(readiness),
+ )
+
+ if "audio" in modules:
+ existing_carriers = _native_audio_carriers(extract_dir, slides)
+ if existing_carriers:
+ details = "; ".join(
+ f"slide {index}: {', '.join(names)}"
+ for index, names in sorted(existing_carriers.items())
+ )
+ return fail_preflight(
+ [
+ "source PPTX already contains native-enhance narration "
+ "carrier(s); refusing to append duplicate audio: "
+ + details
+ ],
+ existing_native_audio_carriers=existing_carriers,
+ delivery_check=source_delivery,
+ )
+
note_parts: set[str] = set()
audio_exts: set[str] = set()
audio_count = 0
transition_only_count = 0
wrote_auto_advance = False
for slide in slides:
- note = _note_path(notes_dir, slide.index)
+ has_slide_transition = (
+ slide.index in resolved_transitions.slide_enters
+ )
+ enter_update = resolved_transitions.slide_enters.get(
+ slide.index,
+ resolved_transitions.global_enter,
+ )
+ note = readiness.note_paths.get(slide.index)
if "notes" in modules and note:
notes_part = _apply_notes(extract_dir, slide, note)
if notes_part is not None:
note_parts.add(notes_part)
- audio = _audio_path(audio_dir, slide.index)
+ audio = readiness.audio_paths.get(slide.index)
if "audio" in modules and audio:
wrote_auto_advance = _apply_audio(
extract_dir,
@@ -956,38 +1987,23 @@ def apply_project(args: argparse.Namespace) -> int:
enter=enter_update,
timings_enabled="timings" in modules,
narration_padding=narration_padding,
+ audio_duration=readiness.audio_durations.get(slide.index),
) or wrote_auto_advance
audio_exts.add(audio.suffix.lower())
audio_count += 1
continue
if (
- apply_transition_without_audio
- and enter_update.policy != "preserve"
+ has_slide_transition
+ or resolved_transitions.apply_without_audio
):
- slide_xml_path = extract_dir / slide.part_name
- slide_xml = slide_xml_path.read_text(encoding="utf-8")
- source_animation_fingerprint = object_animation_fingerprint(
- slide_xml
- )
- slide_xml, _uses_timings = apply_slide_motion_xml(
- slide_xml,
- enter=enter_update,
- advance=AdvanceUpdate(mode="preserve"),
- )
- if (
- object_animation_fingerprint(slide_xml)
- != source_animation_fingerprint
- ):
- raise RuntimeError(
- f"Slide {slide.index} object animations changed while "
- "updating the transition"
+ transition_only_count += int(
+ _apply_transition_only(
+ extract_dir,
+ slide,
+ enter_update,
)
- slide_xml_path.write_text(
- slide_xml,
- encoding="utf-8",
)
- transition_only_count += 1
_update_content_types(extract_dir, note_parts, audio_exts)
if wrote_auto_advance:
@@ -1017,8 +2033,94 @@ def apply_project(args: argparse.Namespace) -> int:
raise RuntimeError(
f"PPTX animation/timing package validation failed: {exc}"
) from exc
+ candidate_delivery = audit_pptx_delivery(candidate_path)
+ introduced_delivery_errors = _new_delivery_errors(
+ source_delivery,
+ candidate_delivery,
+ )
+ if introduced_delivery_errors:
+ raise RuntimeError(
+ "PPTX delivery postflight introduced structural error(s): "
+ + "; ".join(
+ str(issue.get("message") or issue)
+ for issue in introduced_delivery_errors
+ )
+ )
+ candidate_slides = candidate_delivery.get("slides")
+ candidate_slide_count = (
+ candidate_slides.get("count")
+ if isinstance(candidate_slides, dict)
+ else None
+ )
+ if candidate_slide_count != len(slides):
+ raise RuntimeError(
+ "PPTX delivery postflight slide count changed: "
+ f"{candidate_slide_count!r} != {len(slides)}"
+ )
+ source_hidden_slides = _delivery_hidden_slide_indices(
+ source_delivery
+ )
+ candidate_hidden_slides = _delivery_hidden_slide_indices(
+ candidate_delivery
+ )
+ if (
+ source_hidden_slides is None
+ or candidate_hidden_slides is None
+ or candidate_hidden_slides != source_hidden_slides
+ ):
+ raise RuntimeError(
+ "PPTX delivery postflight changed or could not verify "
+ "hidden-slide state"
+ )
candidate_path.replace(output_path)
+ candidate_file = candidate_delivery.get("file")
+ if isinstance(candidate_file, dict):
+ candidate_file["path"] = str(output_path.resolve())
+ report_status = (
+ "passed-with-advisories"
+ if (
+ _delivery_has_findings(source_delivery)
+ or _delivery_has_findings(candidate_delivery)
+ )
+ else "passed"
+ )
+ validation_dir = project_path / "validation"
+ validation_dir.mkdir(exist_ok=True)
+ _write_json(
+ validation_dir / "report.json",
+ {
+ "schema": VALIDATION_SCHEMA,
+ "status": report_status,
+ "phase": "postflight",
+ "plan_status": plan.get("status") or "missing",
+ "enabled_modules": sorted(modules),
+ "slide_count": len(slides),
+ "applied": {
+ "notes": len(note_parts),
+ "audio": audio_count,
+ "transition_only_slides": transition_only_count,
+ "automatic_advance": wrote_auto_advance,
+ },
+ "transition_scope": {
+ "global_enabled": "transitions" in modules,
+ "global_policy": (
+ resolved_transitions.global_enter.policy
+ ),
+ "apply_without_audio": (
+ resolved_transitions.apply_without_audio
+ ),
+ "selected_slides": sorted(
+ resolved_transitions.slide_enters
+ ),
+ },
+ "source_delivery_check": source_delivery,
+ "output_delivery_check": candidate_delivery,
+ "source_delivery_policy": "preserve-baseline",
+ "introduced_delivery_errors": introduced_delivery_errors,
+ },
+ )
+
print(f"Output: {output_path}", file=sys.stderr)
print(f"Notes applied: {len(note_parts)}", file=sys.stderr)
print(f"Audio embedded: {audio_count}", file=sys.stderr)
@@ -1035,42 +2137,124 @@ def validate_project(args: argparse.Namespace) -> int:
return 1
source_pptx, notes_dir, audio_dir, _exports_dir = _project_paths(project_path)
+ plan = _load_enhancement_plan(project_path)
+ modules = _enabled_modules(plan)
+ source_delivery = audit_pptx_delivery(source_pptx)
+ validation_dir = project_path / "validation"
+ validation_dir.mkdir(exist_ok=True)
+ fatal_delivery_messages = _fatal_source_delivery_messages(source_delivery)
+ if fatal_delivery_messages:
+ report = _write_preflight_report(
+ project_path,
+ plan,
+ modules,
+ status="failed",
+ fatal_delivery_errors=fatal_delivery_messages,
+ delivery_check=source_delivery,
+ )
+ print(json.dumps(report, ensure_ascii=False, indent=2))
+ return 1
+
with tempfile.TemporaryDirectory(prefix="native-enhance-validate-") as tmp:
extract_dir = Path(tmp) / "pptx"
_extract_pptx(source_pptx, extract_dir)
slides = read_slide_parts(extract_dir)
+ existing_carriers = (
+ _native_audio_carriers(extract_dir, slides)
+ if "audio" in modules
+ else {}
+ )
- plan = _load_enhancement_plan(project_path)
- modules = _enabled_modules(plan)
- notes_count = sum(1 for slide in slides if _note_path(notes_dir, slide.index) is not None)
- audio_count = sum(1 for slide in slides if _audio_path(audio_dir, slide.index) is not None)
- missing_notes = (
- [slide.index for slide in slides if _note_path(notes_dir, slide.index) is None]
- if "notes" in modules
- else []
+ source_errors = _source_state_errors(
+ project_path,
+ project,
+ source_pptx,
+ slides,
+ )
+ try:
+ _validate_plan_modules(plan)
+ except ValueError as exc:
+ plan_errors = [str(exc)]
+ else:
+ plan_errors = []
+ try:
+ resolved_transitions = (
+ _resolve_transition_plan(
+ project,
+ plan,
+ slides,
+ )
+ if not plan_errors
+ else None
+ )
+ except ValueError as exc:
+ transition_errors = [str(exc)]
+ transition_slide_count = 0
+ transition_scope = None
+ else:
+ transition_errors = []
+ if resolved_transitions is None:
+ transition_slide_count = 0
+ transition_scope = None
+ else:
+ transition_slide_count = len(
+ resolved_transitions.slide_enters
+ )
+ transition_scope = {
+ "global_enabled": "transitions" in modules,
+ "global_policy": resolved_transitions.global_enter.policy,
+ "apply_without_audio": (
+ resolved_transitions.apply_without_audio
+ ),
+ "selected_slides": sorted(
+ resolved_transitions.slide_enters
+ ),
+ }
+ readiness = _collect_material_readiness(
+ slides,
+ notes_dir,
+ audio_dir,
+ modules,
)
- missing_audio = (
- [slide.index for slide in slides if _audio_path(audio_dir, slide.index) is None]
- if "audio" in modules
- else []
+ hard_failure = bool(
+ source_errors
+ or readiness.module_errors
+ or plan_errors
+ or transition_errors
+ or existing_carriers
+ )
+ if hard_failure:
+ status = "failed"
+ elif not readiness.ready:
+ status = "needs-materials"
+ else:
+ status = (
+ "passed-with-advisories"
+ if _delivery_has_findings(source_delivery)
+ else "passed"
+ )
+ report = _write_preflight_report(
+ project_path,
+ plan,
+ modules,
+ status=status,
+ slide_count=len(slides),
+ notes_required="notes" in modules,
+ audio_required="audio" in modules or "timings" in modules,
+ plan_errors=plan_errors,
+ transition_errors=transition_errors,
+ transition_override_count=transition_slide_count,
+ transition_scope=transition_scope,
+ source_errors=source_errors,
+ existing_native_audio_carriers=existing_carriers,
+ source_delivery_policy="preserve-baseline",
+ delivery_check=source_delivery,
+ **_material_readiness_report_fields(readiness),
)
- report = {
- "schema": "native_pptx_enhancement_validation.v1",
- "slide_count": len(slides),
- "plan_status": plan.get("status") or "missing",
- "enabled_modules": sorted(modules),
- "notes_required": "notes" in modules,
- "audio_required": "audio" in modules,
- "notes_count": notes_count,
- "audio_count": audio_count,
- "missing_notes": missing_notes,
- "missing_audio": missing_audio,
- }
- validation_dir = project_path / "validation"
- validation_dir.mkdir(exist_ok=True)
- _write_json(validation_dir / "report.json", report)
print(json.dumps(report, ensure_ascii=False, indent=2))
- return 0 if not missing_notes and not missing_audio else 2
+ if hard_failure:
+ return 1
+ return 0 if readiness.ready else 2
def build_parser() -> argparse.ArgumentParser:
@@ -1104,20 +2288,35 @@ def build_parser() -> argparse.ArgumentParser:
plan.add_argument("project_path", help="native enhancement project directory")
plan.add_argument(
"--transition",
- default="fade",
+ default=None,
choices=[*NATIVE_TRANSITION_KEYS, *LEGACY_TRANSITION_KEYS, "none"],
- help="PowerPoint-native effect; old names are compatibility inputs",
+ help=(
+ "replace the saved global PowerPoint-native effect; omitted values "
+ "preserve the current plan"
+ ),
+ )
+ plan.add_argument(
+ "--transition-duration",
+ type=_positive_seconds_arg,
+ default=None,
+ )
+ plan.add_argument(
+ "--narration-padding",
+ type=_non_negative_seconds_arg,
+ default=None,
)
- plan.add_argument("--transition-duration", type=_positive_seconds_arg, default=0.5)
- plan.add_argument("--narration-padding", type=_non_negative_seconds_arg, default=0.4)
plan.add_argument(
"--apply-transition-without-audio",
action="store_true",
+ default=None,
help="include page transitions for slides without audio",
)
plan.set_defaults(func=plan_project)
- apply = subparsers.add_parser("apply", help="patch notes/audio/timings into a copied PPTX")
+ apply = subparsers.add_parser(
+ "apply",
+ help="patch confirmed notes/audio/timings/transitions into a copied PPTX",
+ )
apply.add_argument("project_path", help="native enhancement project directory")
apply.add_argument("-o", "--output", default=None, help="output .pptx path")
apply.add_argument("--overwrite", action="store_true", help="overwrite output if it exists")
@@ -1137,16 +2336,82 @@ def build_parser() -> argparse.ArgumentParser:
)
apply.set_defaults(func=apply_project)
- validate = subparsers.add_parser("validate", help="check notes/audio coverage")
+ validate = subparsers.add_parser(
+ "validate",
+ help="check source integrity, plan semantics, and material readiness",
+ )
validate.add_argument("project_path", help="native enhancement project directory")
validate.set_defaults(func=validate_project)
return parser
+def _record_preflight_exception(
+ args: argparse.Namespace,
+ exc: Exception,
+) -> None:
+ command = str(args.command)
+ try:
+ project_path = Path(args.project_path).expanduser().resolve()
+ project = _read_json(project_path / "project.json")
+ except (OSError, ValueError, KeyError, json.JSONDecodeError) as project_exc:
+ if (
+ project_path.is_dir()
+ and (project_path / "validation").is_dir()
+ ):
+ try:
+ _write_preflight_report(
+ project_path,
+ {},
+ set(),
+ status="failed",
+ errors=[f"{command} aborted: {exc}"],
+ project_errors=[
+ f"unable to read project.json: {project_exc}"
+ ],
+ )
+ except OSError:
+ pass
+ return
+ if project.get("schema") not in {
+ PROJECT_SCHEMA,
+ *LEGACY_PROJECT_SCHEMAS,
+ }:
+ return
+ plan_errors: list[str] = []
+ try:
+ plan = _load_enhancement_plan(project_path)
+ except (OSError, ValueError, json.JSONDecodeError) as plan_exc:
+ plan = {}
+ plan_errors.append(f"unable to read enhancement plan: {plan_exc}")
+ try:
+ _write_preflight_report(
+ project_path,
+ plan,
+ set() if plan_errors else _enabled_modules(plan),
+ status="failed",
+ errors=[f"{command} aborted: {exc}"],
+ plan_errors=plan_errors,
+ )
+ except OSError:
+ return
+
+
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
- return args.func(args)
+ try:
+ return args.func(args)
+ except (
+ OSError,
+ RuntimeError,
+ ValueError,
+ zipfile.BadZipFile,
+ ET.ParseError,
+ ) as exc:
+ if args.command in {"apply", "validate"}:
+ _record_preflight_exception(args, exc)
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
if __name__ == "__main__":
diff --git a/skills/ppt-master/scripts/pptx_delivery_check.py b/skills/ppt-master/scripts/pptx_delivery_check.py
new file mode 100644
index 00000000..d889c31c
--- /dev/null
+++ b/skills/ppt-master/scripts/pptx_delivery_check.py
@@ -0,0 +1,1133 @@
+#!/usr/bin/env python3
+"""
+PPT Master - PPTX Delivery Check
+
+Inspect a finished PPTX without modifying it and report package integrity,
+delivery portability, media footprint, hidden slides, and motion presence.
+
+Usage:
+ python3 scripts/pptx_delivery_check.py <presentation.pptx>
+
+Examples:
+ python3 scripts/pptx_delivery_check.py projects/demo/exports/demo.pptx
+
+Dependencies:
+ Same repository dependencies as beautify_identity.py and svg_to_pptx.py.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import mimetypes
+import re
+import sys
+import tempfile
+import unicodedata
+import zipfile
+from collections import Counter, defaultdict
+from pathlib import Path, PurePosixPath
+from xml.etree import ElementTree as ET
+
+_SCRIPTS_DIR = Path(__file__).resolve().parent
+if str(_SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS_DIR))
+
+from console_encoding import configure_utf8_stdio # noqa: E402
+
+configure_utf8_stdio()
+
+from beautify_identity import extract_identity # noqa: E402
+from pptx_opc_validation import ( # noqa: E402
+ canonical_opc_part_path,
+ resolve_internal_opc_target,
+ verify_internal_relationships,
+)
+from pptx_animations import ( # noqa: E402
+ object_animation_fingerprint,
+ read_slide_animation_sequence,
+ validate_pptx_animation_package,
+)
+from pptx_to_svg.ooxml_loader import ( # noqa: E402
+ OoxmlPackage,
+ parse_ooxml_boolean,
+)
+from pptx_transitions import ( # noqa: E402
+ read_slide_transition_xml,
+ validate_slide_transition_xml,
+)
+from svg_to_pptx.drawingml.utils import PPT_SAFE_FONTS # noqa: E402
+
+
+REPORT_SCHEMA = "ppt-master.pptx-delivery-check.v1"
+PACKAGE_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
+CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
+DRAWINGML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
+PRESENTATION_NS = (
+ "http://schemas.openxmlformats.org/presentationml/2006/main"
+)
+_SLIDE_PART_RE = re.compile(r"ppt/slides/slide[1-9]\d*\.xml")
+_NOTES_PART_RE = re.compile(r"ppt/notesSlides/notesSlide[1-9]\d*\.xml")
+_MASTER_PART_RE = re.compile(r"ppt/slideMasters/slideMaster[1-9]\d*\.xml")
+_LAYOUT_PART_RE = re.compile(r"ppt/slideLayouts/slideLayout[1-9]\d*\.xml")
+_MEDIA_REL_KINDS = frozenset({"audio", "image", "media", "video"})
+_PPT_SAFE_FONT_ALIASES = {
+ "等线": "DengXian",
+ "等线 light": "DengXian Light",
+ "宋体": "SimSun",
+ "新細明體": "PMingLiU",
+ "맑은 고딕": "Malgun Gothic",
+ "ms pゴシック": "MS PGothic",
+}
+_PPT_DELIVERY_SAFE_FONTS = PPT_SAFE_FONTS | frozenset(
+ {"dengxian light", "pmingliu"}
+)
+
+
+def _issue(code: str, message: str, **details: object) -> dict[str, object]:
+ issue: dict[str, object] = {"code": code, "message": message}
+ issue.update(details)
+ return issue
+
+
+def _empty_report(path: Path) -> dict[str, object]:
+ return {
+ "schema": REPORT_SCHEMA,
+ "status": "failed",
+ "file": {
+ "path": str(path),
+ "bytes": path.stat().st_size if path.is_file() else None,
+ },
+ "package": {
+ "zip_integrity": "not-checked",
+ "corrupt_member": None,
+ "duplicate_parts": [],
+ "canonical_part_collisions": [],
+ "parts": {},
+ "relationships": {"problems": []},
+ },
+ "slides": {
+ "count": 0,
+ "hidden_count": 0,
+ "hidden": [],
+ },
+ "fonts": {
+ "theme": {},
+ "declared": {},
+ "embedded_parts": [],
+ "portability_advisory_faces": [],
+ },
+ "media": {
+ "embedded_count": 0,
+ "external_count": 0,
+ "embedded": [],
+ "external": [],
+ "uncompressed_bytes": 0,
+ "archive_compressed_bytes": 0,
+ "share_of_archive": 0.0,
+ "share_of_uncompressed_parts": 0.0,
+ "top_contributors": [],
+ },
+ "motion": {
+ "transitions": {
+ "carrier_slide_count": 0,
+ "visual_effect_slide_count": 0,
+ "timed_advance_slide_count": 0,
+ "carrier_slides": [],
+ "visual_effect_slides": [],
+ "timed_advance_slides": [],
+ "effects": {},
+ },
+ "object_animations": {
+ "timing_slide_count": 0,
+ "object_animation_slide_count": 0,
+ "audio_timing_slide_count": 0,
+ "timing_slides": [],
+ "object_animation_slides": [],
+ "audio_timing_slides": [],
+ },
+ },
+ "errors": [],
+ "advisories": [],
+ }
+
+
+def _content_type_maps(
+ archive: zipfile.ZipFile,
+ errors: list[dict[str, object]],
+) -> tuple[dict[str, str], dict[str, str]]:
+ try:
+ root = ET.fromstring(archive.read("[Content_Types].xml"))
+ except KeyError:
+ errors.append(
+ _issue(
+ "missing_content_types",
+ "PPTX package is missing [Content_Types].xml.",
+ )
+ )
+ return {}, {}
+ except ET.ParseError as exc:
+ errors.append(
+ _issue(
+ "invalid_content_types",
+ f"PPTX content-types XML is invalid: {exc}.",
+ )
+ )
+ return {}, {}
+ expected_root = f"{{{CONTENT_TYPES_NS}}}Types"
+ if root.tag != expected_root:
+ errors.append(
+ _issue(
+ "invalid_content_types",
+ "PPTX content-types XML uses an invalid Types namespace.",
+ )
+ )
+ return {}, {}
+
+ defaults: dict[str, str] = {}
+ overrides: dict[str, str] = {}
+ default_tag = f"{{{CONTENT_TYPES_NS}}}Default"
+ override_tag = f"{{{CONTENT_TYPES_NS}}}Override"
+ for node in root:
+ if node.tag == default_tag:
+ raw_extension = (node.attrib.get("Extension") or "").strip()
+ content_type = (node.attrib.get("ContentType") or "").strip()
+ extension = raw_extension.lower()
+ if not extension or extension.startswith(".") or not content_type:
+ errors.append(
+ _issue(
+ "invalid_content_types",
+ "PPTX content-types Default entry is incomplete.",
+ )
+ )
+ continue
+ if extension in defaults:
+ errors.append(
+ _issue(
+ "invalid_content_types",
+ "PPTX content-types XML has a duplicate Default extension.",
+ extension=raw_extension,
+ )
+ )
+ continue
+ defaults[extension] = content_type
+ continue
+ if node.tag == override_tag:
+ raw_part_name = (node.attrib.get("PartName") or "").strip()
+ content_type = (node.attrib.get("ContentType") or "").strip()
+ part_name = raw_part_name.lstrip("/")
+ if (
+ not raw_part_name.startswith("/")
+ or not part_name
+ or ".." in PurePosixPath(part_name).parts
+ or not content_type
+ ):
+ errors.append(
+ _issue(
+ "invalid_content_types",
+ "PPTX content-types Override entry is incomplete or invalid.",
+ part=raw_part_name or None,
+ )
+ )
+ continue
+ if part_name in overrides:
+ errors.append(
+ _issue(
+ "invalid_content_types",
+ "PPTX content-types XML has a duplicate Override part.",
+ part=raw_part_name,
+ )
+ )
+ continue
+ overrides[part_name] = content_type
+ continue
+ errors.append(
+ _issue(
+ "invalid_content_types",
+ "PPTX content-types XML contains an unexpected child.",
+ child=node.tag,
+ )
+ )
+ return defaults, overrides
+
+
+def _content_type_for_part(
+ part_name: str,
+ defaults: dict[str, str],
+ overrides: dict[str, str],
+) -> str:
+ declared = _declared_content_type_for_part(
+ part_name,
+ defaults,
+ overrides,
+ )
+ if declared is not None:
+ return declared
+ guessed, _encoding = mimetypes.guess_type(part_name)
+ return guessed or "application/octet-stream"
+
+
+def _declared_content_type_for_part(
+ part_name: str,
+ defaults: dict[str, str],
+ overrides: dict[str, str],
+) -> str | None:
+ if part_name in overrides:
+ return overrides[part_name]
+ filename = PurePosixPath(part_name).name
+ extension = (
+ "rels"
+ if filename == ".rels" or filename.endswith(".rels")
+ else PurePosixPath(part_name).suffix.lstrip(".").lower()
+ )
+ return defaults.get(extension)
+
+
+def _xml_and_font_inventory(
+ archive: zipfile.ZipFile,
+ part_names: set[str],
+ errors: list[dict[str, object]],
+) -> dict[str, list[dict[str, object]]]:
+ font_counts: dict[str, Counter[str]] = {
+ "latin": Counter(),
+ "ea": Counter(),
+ "cs": Counter(),
+ }
+ for part_name in sorted(
+ name
+ for name in part_names
+ if name.endswith(".xml") and name != "[Content_Types].xml"
+ ):
+ try:
+ root = ET.fromstring(archive.read(part_name))
+ except (KeyError, ET.ParseError) as exc:
+ errors.append(
+ _issue(
+ "invalid_xml_part",
+ f"Cannot parse XML part {part_name}: {exc}.",
+ part=part_name,
+ )
+ )
+ continue
+ for role in font_counts:
+ for element in root.iter(
+ f"{{{DRAWINGML_NS}}}{role}"
+ ):
+ face = (element.attrib.get("typeface") or "").strip()
+ if face:
+ font_counts[role][face] += 1
+ return {
+ role: [
+ {"value": face, "count": count}
+ for face, count in sorted(
+ counts.items(),
+ key=lambda item: (-item[1], item[0].casefold()),
+ )
+ ]
+ for role, counts in font_counts.items()
+ }
+
+
+def _relationship_kind(relationship_type: str) -> str | None:
+ kind = relationship_type.rstrip("/").rsplit("/", 1)[-1].lower()
+ return kind if kind in _MEDIA_REL_KINDS else None
+
+
+def _relationship_inventory(
+ archive: zipfile.ZipFile,
+ part_names: set[str],
+ errors: list[dict[str, object]],
+) -> tuple[
+ Counter[str],
+ dict[str, set[str]],
+ list[dict[str, object]],
+]:
+ reference_counts: Counter[str] = Counter()
+ relationship_types: dict[str, set[str]] = defaultdict(set)
+ external_counts: Counter[tuple[str, str, str]] = Counter()
+
+ for rels_name in sorted(
+ name for name in part_names if name.endswith(".rels")
+ ):
+ try:
+ root = ET.fromstring(archive.read(rels_name))
+ except (KeyError, ET.ParseError) as exc:
+ errors.append(
+ _issue(
+ "invalid_relationship_part",
+ f"Cannot parse relationship part {rels_name}: {exc}.",
+ part=rels_name,
+ )
+ )
+ continue
+ for relationship in root.findall(
+ f"{{{PACKAGE_REL_NS}}}Relationship"
+ ):
+ relationship_type = (
+ relationship.attrib.get("Type") or ""
+ ).strip()
+ target = (relationship.attrib.get("Target") or "").strip()
+ target_mode = (
+ relationship.attrib.get("TargetMode") or ""
+ ).strip().lower()
+ kind = _relationship_kind(relationship_type)
+ if target_mode == "external":
+ if kind and target:
+ external_counts[(kind, target, relationship_type)] += 1
+ continue
+ resolved = resolve_internal_opc_target(rels_name, target)
+ if resolved is None:
+ continue
+ reference_counts[resolved] += 1
+ if relationship_type:
+ relationship_types[resolved].add(relationship_type)
+
+ external = [
+ {
+ "target": target,
+ "kind": kind,
+ "relationship_type": relationship_type,
+ "bytes": None,
+ "compressed_bytes": None,
+ "reference_count": count,
+ }
+ for (kind, target, relationship_type), count in sorted(
+ external_counts.items()
+ )
+ ]
+ return reference_counts, relationship_types, external
+
+
+def _embedded_part_record(
+ info: zipfile.ZipInfo,
+ *,
+ content_type: str,
+ reference_counts: Counter[str],
+ relationship_types: dict[str, set[str]],
+) -> dict[str, object]:
+ kind = content_type.split("/", 1)[0]
+ if kind not in {"audio", "image", "video"}:
+ kind = "media"
+ part_key = canonical_opc_part_path(info.filename)
+ return {
+ "part": info.filename,
+ "kind": kind,
+ "content_type": content_type,
+ "bytes": info.file_size,
+ "compressed_bytes": info.compress_size,
+ "reference_count": (
+ reference_counts.get(part_key, 0)
+ if part_key is not None
+ else 0
+ ),
+ "relationship_types": sorted(
+ relationship_types.get(part_key, set())
+ if part_key is not None
+ else set()
+ ),
+ }
+
+
+def _archive_member_problems(
+ infos: list[zipfile.ZipInfo],
+) -> list[str]:
+ problems: list[str] = []
+ for info in infos:
+ name = info.filename
+ path = PurePosixPath(name)
+ if (
+ name.startswith("/")
+ or "\\" in name
+ or ".." in path.parts
+ ):
+ problems.append(name)
+ return sorted(set(problems))
+
+
+def _relationship_problem_code(problem: str) -> str:
+ if "<invalid relationships XML:" in problem:
+ return "invalid_relationship_xml"
+ if " -> <" in problem:
+ return "invalid_internal_relationship"
+ return "dangling_internal_relationship"
+
+
+def _font_faces_for_advisory(
+ theme_fonts: object,
+ declared_fonts: object,
+) -> list[str]:
+ faces: set[str] = set()
+ if isinstance(theme_fonts, dict):
+ for role in ("title", "body"):
+ value = theme_fonts.get(role)
+ if not isinstance(value, dict):
+ continue
+ for field in ("latin", "ea", "cs"):
+ face = value.get(field)
+ if isinstance(face, str) and face.strip():
+ faces.add(face.strip())
+ scripts = value.get("scripts")
+ if isinstance(scripts, dict):
+ for face in scripts.values():
+ if isinstance(face, str) and face.strip():
+ faces.add(face.strip())
+ if isinstance(declared_fonts, dict):
+ for role in ("latin", "ea", "cs"):
+ values = declared_fonts.get(role)
+ if not isinstance(values, list):
+ continue
+ for value in values:
+ if not isinstance(value, dict):
+ continue
+ face = value.get("value")
+ if isinstance(face, str) and face.strip():
+ faces.add(face.strip())
+ return sorted(faces, key=str.casefold)
+
+
+def _unsafe_font_faces(faces: list[str]) -> list[str]:
+ unsafe: list[str] = []
+ for face in faces:
+ normalized = unicodedata.normalize("NFKC", face).strip().casefold()
+ canonical = _PPT_SAFE_FONT_ALIASES.get(normalized, normalized)
+ canonical = unicodedata.normalize(
+ "NFKC",
+ canonical,
+ ).strip().casefold()
+ if canonical.startswith("+") or canonical in _PPT_DELIVERY_SAFE_FONTS:
+ continue
+ unsafe.append(face)
+ return unsafe
+
+
+def _motion_and_hidden_summary(
+ path: Path,
+ errors: list[dict[str, object]],
+) -> tuple[int, list[dict[str, object]], dict[str, object]]:
+ hidden: list[dict[str, object]] = []
+ transition_carriers: list[int] = []
+ visual_transitions: list[int] = []
+ timed_advances: list[int] = []
+ transition_effects: Counter[str] = Counter()
+ timing_slides: list[int] = []
+ object_animation_slides: list[int] = []
+ audio_timing_slides: list[int] = []
+ slide_count = 0
+
+ try:
+ validate_pptx_animation_package(
+ path,
+ require_supported_effects=False,
+ )
+ except ValueError as exc:
+ errors.append(
+ _issue(
+ "invalid_animation_structure",
+ str(exc),
+ )
+ )
+
+ try:
+ with OoxmlPackage(path) as package:
+ if package.zip is None:
+ raise RuntimeError("PPTX package closed during slide audit")
+ if package.presentation is None:
+ raise RuntimeError("PPTX package has no presentation part")
+ slide_roster = package.presentation.xml.find(
+ f"{{{PRESENTATION_NS}}}sldIdLst"
+ )
+ roster_count = (
+ len(
+ slide_roster.findall(
+ f"{{{PRESENTATION_NS}}}sldId"
+ )
+ )
+ if slide_roster is not None
+ else 0
+ )
+ loaded_count = package.slide_count
+ inspected_count = 0
+ slide_count = roster_count
+ for slide in package.iter_slides():
+ inspected_count += 1
+ try:
+ visible = parse_ooxml_boolean(
+ slide.part.xml.attrib.get("show"),
+ default=True,
+ context=f"{slide.part.path} show",
+ )
+ except RuntimeError as exc:
+ errors.append(
+ _issue(
+ "invalid_slide_visibility",
+ str(exc),
+ slide_index=slide.index,
+ part=slide.part.path,
+ )
+ )
+ visible = True
+ if not visible:
+ hidden.append(
+ {
+ "index": slide.index,
+ "part": slide.part.path,
+ }
+ )
+
+ slide_xml = package.zip.read(slide.part.path)
+ transition_problems = validate_slide_transition_xml(slide_xml)
+ for problem in transition_problems:
+ errors.append(
+ _issue(
+ "invalid_transition_structure",
+ f"{slide.part.path}: {problem}",
+ slide_index=slide.index,
+ part=slide.part.path,
+ )
+ )
+ try:
+ transition = read_slide_transition_xml(slide_xml)
+ except (ET.ParseError, ValueError) as exc:
+ if not transition_problems:
+ errors.append(
+ _issue(
+ "transition_readback_failed",
+ f"{slide.part.path}: {exc}",
+ slide_index=slide.index,
+ part=slide.part.path,
+ )
+ )
+ else:
+ if transition.logical_count:
+ transition_carriers.append(slide.index)
+ effect = (
+ transition.canonical_effect
+ or transition.effect
+ or "timing-only"
+ )
+ transition_effects[effect] += 1
+ if transition.effect is not None:
+ visual_transitions.append(slide.index)
+ if transition.advance_after_ms is not None:
+ timed_advances.append(slide.index)
+
+ try:
+ animation = read_slide_animation_sequence(
+ slide_xml,
+ require_supported_effects=False,
+ )
+ except (ET.ParseError, ValueError):
+ animation = None
+
+ try:
+ has_object_animation = (
+ object_animation_fingerprint(slide_xml) is not None
+ )
+ except ValueError as exc:
+ errors.append(
+ _issue(
+ "animation_presence_readback_failed",
+ f"{slide.part.path}: {exc}",
+ slide_index=slide.index,
+ part=slide.part.path,
+ )
+ )
+ has_object_animation = False
+
+ root = ET.fromstring(slide_xml)
+ has_timing = any(
+ node.tag == f"{{{PRESENTATION_NS}}}timing"
+ for node in root
+ )
+ has_audio_timing = any(
+ node.tag == f"{{{PRESENTATION_NS}}}audio"
+ for node in root.iter()
+ )
+ if animation is not None:
+ has_timing = has_timing or bool(animation.timing_count)
+ has_object_animation = (
+ has_object_animation or bool(animation.rows)
+ )
+ has_audio_timing = (
+ has_audio_timing or bool(animation.audio_target_ids)
+ )
+ if has_timing:
+ timing_slides.append(slide.index)
+ if has_object_animation:
+ object_animation_slides.append(slide.index)
+ if has_audio_timing:
+ audio_timing_slides.append(slide.index)
+ if (
+ roster_count != loaded_count
+ or loaded_count != inspected_count
+ ):
+ errors.append(
+ _issue(
+ "slide_inventory_failed",
+ (
+ f"Presentation declares {roster_count} slides, "
+ f"but the loader resolved {loaded_count} and the "
+ f"delivery audit inspected {inspected_count}."
+ ),
+ roster_count=roster_count,
+ loaded_count=loaded_count,
+ inspected_count=inspected_count,
+ )
+ )
+ except (KeyError, OSError, RuntimeError, ValueError, zipfile.BadZipFile) as exc:
+ errors.append(
+ _issue(
+ "slide_inventory_failed",
+ f"Cannot inspect presentation slides: {exc}.",
+ )
+ )
+
+ return slide_count, hidden, {
+ "transitions": {
+ "carrier_slide_count": len(transition_carriers),
+ "visual_effect_slide_count": len(visual_transitions),
+ "timed_advance_slide_count": len(timed_advances),
+ "carrier_slides": transition_carriers,
+ "visual_effect_slides": visual_transitions,
+ "timed_advance_slides": timed_advances,
+ "effects": dict(sorted(transition_effects.items())),
+ },
+ "object_animations": {
+ "timing_slide_count": len(timing_slides),
+ "object_animation_slide_count": len(object_animation_slides),
+ "audio_timing_slide_count": len(audio_timing_slides),
+ "timing_slides": timing_slides,
+ "object_animation_slides": object_animation_slides,
+ "audio_timing_slides": audio_timing_slides,
+ },
+ }
+
+
+def _deduplicate_issues(
+ issues: list[dict[str, object]],
+) -> list[dict[str, object]]:
+ seen: set[str] = set()
+ output: list[dict[str, object]] = []
+ for issue in issues:
+ key = json.dumps(issue, ensure_ascii=False, sort_keys=True)
+ if key in seen:
+ continue
+ seen.add(key)
+ output.append(issue)
+ return output
+
+
+def audit_pptx_delivery(path: str | Path) -> dict[str, object]:
+ """Return a JSON-safe, read-only delivery audit for one PPTX file."""
+ pptx_path = Path(path).expanduser().resolve()
+ report = _empty_report(pptx_path)
+ errors = report["errors"]
+ advisories = report["advisories"]
+ if not isinstance(errors, list) or not isinstance(advisories, list):
+ raise AssertionError("delivery report issue containers are invalid")
+
+ if not pptx_path.is_file():
+ errors.append(
+ _issue(
+ "file_not_found",
+ f"PPTX file not found: {pptx_path}.",
+ )
+ )
+ return report
+
+ try:
+ with zipfile.ZipFile(pptx_path) as archive:
+ infos = archive.infolist()
+ file_infos = [info for info in infos if not info.is_dir()]
+ names = [info.filename for info in file_infos]
+ name_counts = Counter(names)
+ duplicate_parts = sorted(
+ name for name, count in name_counts.items() if count > 1
+ )
+ info_by_name = {info.filename: info for info in file_infos}
+ part_names = set(info_by_name)
+ canonical_names: dict[str, set[str]] = defaultdict(set)
+ invalid_part_names: list[str] = []
+ for name in part_names:
+ canonical = canonical_opc_part_path(name)
+ if canonical is None:
+ invalid_part_names.append(name)
+ else:
+ canonical_names[canonical].add(name)
+ canonical_collisions = sorted(
+ sorted(raw_names)
+ for raw_names in canonical_names.values()
+ if len(raw_names) > 1
+ )
+
+ package = report["package"]
+ if not isinstance(package, dict):
+ raise AssertionError("delivery report package container is invalid")
+ try:
+ corrupt_member = archive.testzip()
+ except (NotImplementedError, RuntimeError) as exc:
+ package["zip_integrity"] = "failed"
+ errors.append(
+ _issue(
+ "unsupported_zip_compression",
+ f"PPTX ZIP members cannot be decoded: {exc}.",
+ )
+ )
+ report["errors"] = _deduplicate_issues(errors)
+ return report
+ package["zip_integrity"] = (
+ "passed" if corrupt_member is None else "failed"
+ )
+ package["corrupt_member"] = corrupt_member
+ package["duplicate_parts"] = duplicate_parts
+ package["canonical_part_collisions"] = canonical_collisions
+ package["parts"] = {
+ "entries": len(file_infos),
+ "unique": len(part_names),
+ "slides": sum(bool(_SLIDE_PART_RE.fullmatch(name)) for name in part_names),
+ "notes": sum(bool(_NOTES_PART_RE.fullmatch(name)) for name in part_names),
+ "masters": sum(bool(_MASTER_PART_RE.fullmatch(name)) for name in part_names),
+ "layouts": sum(bool(_LAYOUT_PART_RE.fullmatch(name)) for name in part_names),
+ "media": sum(
+ (canonical_opc_part_path(name) or "").startswith(
+ "ppt/media/"
+ )
+ for name in part_names
+ ),
+ }
+ if corrupt_member is not None:
+ errors.append(
+ _issue(
+ "zip_integrity_failed",
+ f"PPTX ZIP integrity failed at {corrupt_member}.",
+ part=corrupt_member,
+ )
+ )
+ if duplicate_parts:
+ errors.append(
+ _issue(
+ "duplicate_package_parts",
+ "PPTX package contains duplicate part names.",
+ parts=duplicate_parts,
+ )
+ )
+ if canonical_collisions:
+ errors.append(
+ _issue(
+ "duplicate_opc_part_names",
+ (
+ "PPTX package contains case- or encoding-equivalent "
+ "part names."
+ ),
+ parts=canonical_collisions,
+ )
+ )
+ if invalid_part_names:
+ errors.append(
+ _issue(
+ "invalid_opc_part_name",
+ "PPTX package contains invalid OPC part names.",
+ parts=sorted(invalid_part_names),
+ )
+ )
+
+ defaults, overrides = _content_type_maps(archive, errors)
+ content_type_registry_valid = not any(
+ issue.get("code") in {
+ "missing_content_types",
+ "invalid_content_types",
+ }
+ for issue in errors
+ if isinstance(issue, dict)
+ )
+ if content_type_registry_valid:
+ missing_content_types = sorted(
+ name
+ for name in part_names
+ if name != "[Content_Types].xml"
+ and _declared_content_type_for_part(
+ name,
+ defaults,
+ overrides,
+ )
+ is None
+ )
+ if missing_content_types:
+ errors.append(
+ _issue(
+ "missing_part_content_type",
+ (
+ "PPTX package parts are missing a declared "
+ "Default or Override content type."
+ ),
+ parts=missing_content_types,
+ )
+ )
+ declared_fonts = _xml_and_font_inventory(
+ archive,
+ part_names,
+ errors,
+ )
+ reference_counts, relationship_types, external_media = (
+ _relationship_inventory(archive, part_names, errors)
+ )
+
+ media_infos = [
+ info_by_name[name]
+ for name in sorted(part_names)
+ if (
+ canonical_opc_part_path(name) or ""
+ ).startswith("ppt/media/")
+ ]
+ embedded_media = [
+ _embedded_part_record(
+ info,
+ content_type=_content_type_for_part(
+ info.filename,
+ defaults,
+ overrides,
+ ),
+ reference_counts=reference_counts,
+ relationship_types=relationship_types,
+ )
+ for info in media_infos
+ ]
+ embedded_media.sort(
+ key=lambda item: (
+ -int(item["bytes"]),
+ str(item["part"]),
+ )
+ )
+
+ embedded_font_infos = [
+ info_by_name[name]
+ for name in sorted(part_names)
+ if name.startswith("ppt/fonts/")
+ or name.lower().endswith(".fntdata")
+ ]
+ embedded_fonts = [
+ {
+ "part": info.filename,
+ "content_type": _content_type_for_part(
+ info.filename,
+ defaults,
+ overrides,
+ ),
+ "bytes": info.file_size,
+ "compressed_bytes": info.compress_size,
+ "reference_count": reference_counts.get(
+ canonical_opc_part_path(info.filename) or "",
+ 0,
+ ),
+ }
+ for info in embedded_font_infos
+ ]
+
+ media_bytes = sum(info.file_size for info in media_infos)
+ media_compressed_bytes = sum(
+ info.compress_size for info in media_infos
+ )
+ total_uncompressed_bytes = sum(
+ info.file_size for info in info_by_name.values()
+ )
+ file_bytes = pptx_path.stat().st_size
+ media = report["media"]
+ if not isinstance(media, dict):
+ raise AssertionError("delivery report media container is invalid")
+ media.update(
+ {
+ "embedded_count": len(embedded_media),
+ "external_count": len(external_media),
+ "embedded": embedded_media,
+ "external": external_media,
+ "uncompressed_bytes": media_bytes,
+ "archive_compressed_bytes": media_compressed_bytes,
+ "share_of_archive": (
+ round(media_compressed_bytes / file_bytes, 6)
+ if file_bytes
+ else 0.0
+ ),
+ "share_of_uncompressed_parts": (
+ round(media_bytes / total_uncompressed_bytes, 6)
+ if total_uncompressed_bytes
+ else 0.0
+ ),
+ "top_contributors": embedded_media[:10],
+ }
+ )
+ fonts = report["fonts"]
+ if not isinstance(fonts, dict):
+ raise AssertionError("delivery report fonts container is invalid")
+ fonts["embedded_parts"] = embedded_fonts
+ fonts["declared"] = declared_fonts
+
+ unsafe_members = _archive_member_problems(infos)
+ if unsafe_members:
+ errors.append(
+ _issue(
+ "unsafe_package_member",
+ "PPTX package contains unsafe member paths.",
+ parts=unsafe_members,
+ )
+ )
+ relationship_problems: list[str] = []
+ else:
+ with tempfile.TemporaryDirectory(
+ prefix="pptx-delivery-check-"
+ ) as tmp:
+ extract_dir = Path(tmp) / "pptx"
+ archive.extractall(extract_dir)
+ relationship_problems = verify_internal_relationships(
+ extract_dir
+ )
+ relationships = package["relationships"]
+ if not isinstance(relationships, dict):
+ raise AssertionError(
+ "delivery report relationships container is invalid"
+ )
+ relationships["problems"] = relationship_problems
+ for problem in relationship_problems:
+ errors.append(
+ _issue(
+ _relationship_problem_code(problem),
+ problem,
+ )
+ )
+ except zipfile.BadZipFile as exc:
+ errors.append(
+ _issue(
+ "invalid_zip_package",
+ f"File is not a readable PPTX ZIP package: {exc}.",
+ )
+ )
+ return report
+ except (NotImplementedError, RuntimeError) as exc:
+ errors.append(
+ _issue(
+ "unsupported_zip_compression",
+ f"PPTX ZIP members cannot be decoded: {exc}.",
+ )
+ )
+ return report
+ except OSError as exc:
+ errors.append(
+ _issue(
+ "package_read_failed",
+ f"Cannot read PPTX package: {exc}.",
+ )
+ )
+ return report
+
+ try:
+ identity = extract_identity(pptx_path)
+ except (KeyError, OSError, RuntimeError, ValueError, zipfile.BadZipFile) as exc:
+ advisories.append(
+ _issue(
+ "font_inventory_unavailable",
+ f"Could not resolve theme and declared font facts: {exc}.",
+ )
+ )
+ else:
+ identity_theme = identity.get("theme")
+ theme_fonts = (
+ identity_theme.get("fonts", {})
+ if isinstance(identity_theme, dict)
+ else {}
+ )
+ fonts = report["fonts"]
+ if not isinstance(fonts, dict):
+ raise AssertionError("delivery report fonts container is invalid")
+ declared_fonts = fonts.get("declared", {})
+ if not isinstance(declared_fonts, dict):
+ declared_fonts = {}
+ fonts["theme"] = theme_fonts
+ unsafe_faces = _unsafe_font_faces(
+ _font_faces_for_advisory(theme_fonts, declared_fonts)
+ )
+ fonts["portability_advisory_faces"] = unsafe_faces
+ if unsafe_faces:
+ advisories.append(
+ _issue(
+ "font_portability",
+ (
+ "Some fonts declared or referenced by the presentation "
+ "are outside the common Office/OS portability set; "
+ "target-system availability was not verified."
+ ),
+ faces=unsafe_faces,
+ )
+ )
+
+ slide_count, hidden_slides, motion = _motion_and_hidden_summary(
+ pptx_path,
+ errors,
+ )
+ slides = report["slides"]
+ if not isinstance(slides, dict):
+ raise AssertionError("delivery report slides container is invalid")
+ slides.update(
+ {
+ "count": slide_count,
+ "hidden_count": len(hidden_slides),
+ "hidden": hidden_slides,
+ }
+ )
+ report["motion"] = motion
+ if hidden_slides:
+ advisories.append(
+ _issue(
+ "hidden_slides",
+ "The presentation contains hidden slides; their state was not changed.",
+ slides=[item["index"] for item in hidden_slides],
+ )
+ )
+
+ media = report["media"]
+ if isinstance(media, dict) and media.get("external_count"):
+ advisories.append(
+ _issue(
+ "external_media",
+ (
+ "The presentation contains externally linked media; "
+ "offline delivery may depend on those targets."
+ ),
+ targets=[
+ item["target"]
+ for item in media.get("external", [])
+ if isinstance(item, dict) and "target" in item
+ ],
+ )
+ )
+
+ report["errors"] = _deduplicate_issues(errors)
+ report["advisories"] = _deduplicate_issues(advisories)
+ report["status"] = (
+ "failed"
+ if report["errors"]
+ else (
+ "passed-with-advisories"
+ if report["advisories"]
+ else "passed"
+ )
+ )
+ return report
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Inspect a finished PPTX for delivery risks without modifying it.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument("pptx", help="Finished .pptx file to inspect")
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ report = audit_pptx_delivery(args.pptx)
+ print(json.dumps(report, ensure_ascii=False, indent=2))
+ return 1 if report["status"] == "failed" else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/pptx_opc_validation.py b/skills/ppt-master/scripts/pptx_opc_validation.py
new file mode 100644
index 00000000..5d159ba9
--- /dev/null
+++ b/skills/ppt-master/scripts/pptx_opc_validation.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""Shared, dependency-light OPC package relationship validation."""
+
+from __future__ import annotations
+
+import posixpath
+import re
+from pathlib import Path
+from urllib.parse import urlsplit
+from xml.etree import ElementTree as ET
+
+
+PACKAGE_REL_NS = (
+ "http://schemas.openxmlformats.org/package/2006/relationships"
+)
+_RELATIONSHIPS_TAG = f"{{{PACKAGE_REL_NS}}}Relationships"
+_RELATIONSHIP_TAG = f"{{{PACKAGE_REL_NS}}}Relationship"
+_OPC_UNRESERVED = frozenset(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
+)
+_ASCII_LOWER_TRANSLATION = str.maketrans(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
+ "abcdefghijklmnopqrstuvwxyz",
+)
+
+
+def canonical_opc_part_path(path: str) -> str | None:
+ """Return an OPC-equivalent package path key, or None when invalid."""
+ if (
+ not path
+ or "\\" in path
+ or "?" in path
+ or "#" in path
+ or path.endswith("/")
+ or "//" in path
+ or any(ord(char) <= 0x20 for char in path)
+ ):
+ return None
+ output: list[str] = []
+ index = 0
+ while index < len(path):
+ char = path[index]
+ if char != "%":
+ output.append(char)
+ index += 1
+ continue
+ if (
+ index + 2 >= len(path)
+ or re.fullmatch(
+ r"[0-9A-Fa-f]{2}",
+ path[index + 1:index + 3],
+ )
+ is None
+ ):
+ return None
+ value = int(path[index + 1:index + 3], 16)
+ decoded = chr(value)
+ if value in {0, ord("/"), ord("\\")}:
+ return None
+ output.append(
+ decoded
+ if decoded in _OPC_UNRESERVED
+ else f"%{value:02X}"
+ )
+ index += 3
+
+ decoded_path = "".join(output)
+ if decoded_path.rsplit("/", 1)[-1] in {".", ".."}:
+ return None
+ normalized = posixpath.normpath(decoded_path)
+ if (
+ not normalized
+ or normalized in {".", ".."}
+ or normalized.startswith("/")
+ or normalized.startswith("../")
+ ):
+ return None
+ return normalized.translate(_ASCII_LOWER_TRANSLATION)
+
+
+def _source_part_for_rels(rels_path: str) -> str | None:
+ filename = posixpath.basename(rels_path)
+ if filename == ".rels" or not filename.endswith(".rels"):
+ return None
+ source_dir = posixpath.dirname(posixpath.dirname(rels_path))
+ source_name = filename.removesuffix(".rels")
+ return (
+ posixpath.join(source_dir, source_name)
+ if source_dir
+ else source_name
+ )
+
+
+def resolve_internal_opc_target(
+ rels_path: str,
+ target: str,
+) -> str | None:
+ """Resolve one valid internal OPC Target to its canonical package key."""
+ target_path_query = target.split("#", 1)[0]
+ if (
+ "\\" in target
+ or "?" in target_path_query
+ or any(ord(char) <= 0x20 for char in target)
+ ):
+ return None
+ try:
+ parsed = urlsplit(target)
+ except ValueError:
+ return None
+ if parsed.scheme or parsed.netloc or parsed.query:
+ return None
+
+ source_part = _source_part_for_rels(rels_path)
+ if parsed.path.startswith("/"):
+ resolved = parsed.path[1:]
+ elif parsed.path:
+ base_dir = posixpath.dirname(source_part) if source_part else ""
+ resolved = (
+ posixpath.join(base_dir, parsed.path)
+ if base_dir
+ else parsed.path
+ )
+ elif source_part and "#" in target:
+ resolved = source_part
+ else:
+ return None
+ return canonical_opc_part_path(resolved)
+
+
+def verify_internal_relationships(extract_dir: Path) -> list[str]:
+ """Return invalid or dangling internal relationships in an OPC package."""
+ package_parts: set[str] = set()
+ for path in extract_dir.rglob("*"):
+ if not path.is_file():
+ continue
+ key = canonical_opc_part_path(
+ path.relative_to(extract_dir).as_posix()
+ )
+ if key is not None:
+ package_parts.add(key)
+
+ problems: list[str] = []
+ for rels_path in sorted(extract_dir.rglob("*.rels")):
+ rels_rel = rels_path.relative_to(extract_dir).as_posix()
+ try:
+ root = ET.parse(rels_path).getroot()
+ except ET.ParseError as exc:
+ problems.append(
+ f"{rels_rel} -> <invalid relationships XML: {exc}>"
+ )
+ continue
+ if root.tag != _RELATIONSHIPS_TAG:
+ problems.append(
+ f"{rels_rel} -> <invalid Relationships namespace>"
+ )
+ continue
+
+ seen_ids: set[str] = set()
+ for element in root:
+ if element.tag != _RELATIONSHIP_TAG:
+ problems.append(
+ f"{rels_rel} -> <invalid relationships child "
+ f"{element.tag!r}>"
+ )
+ continue
+ relationship_id = (element.attrib.get("Id") or "").strip()
+ relationship_type = (
+ element.attrib.get("Type") or ""
+ ).strip()
+ target = (element.attrib.get("Target") or "").strip()
+ target_mode = (
+ element.attrib.get("TargetMode") or ""
+ ).strip()
+
+ if not relationship_id:
+ problems.append(f"{rels_rel} -> <missing relationship Id>")
+ elif relationship_id in seen_ids:
+ problems.append(
+ f"{rels_rel} -> <duplicate relationship Id "
+ f"{relationship_id!r}>"
+ )
+ else:
+ seen_ids.add(relationship_id)
+ if not relationship_type:
+ problems.append(
+ f"{rels_rel} -> <missing relationship Type>"
+ )
+ if not target:
+ problems.append(f"{rels_rel} -> <missing Target>")
+ continue
+ if target_mode and target_mode.lower() not in {
+ "internal",
+ "external",
+ }:
+ problems.append(
+ f"{rels_rel} -> <invalid TargetMode "
+ f"{target_mode!r}>"
+ )
+ continue
+ if target_mode.lower() == "external":
+ continue
+
+ resolved = resolve_internal_opc_target(rels_rel, target)
+ if resolved is None:
+ problems.append(
+ f"{rels_rel} -> <invalid Target {target!r}>"
+ )
+ elif resolved not in package_parts:
+ problems.append(f"{rels_rel} -> {resolved}")
+ return problems
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 e20f5abd..decef3c9 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
@@ -21,7 +21,6 @@ from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
-from urllib.parse import urlsplit
from xml.etree import ElementTree as ET
from xml.sax.saxutils import escape
@@ -50,6 +49,11 @@ from pptx_animations import (
validate_generated_animation_xml,
validate_pptx_animation_package,
)
+from pptx_opc_validation import (
+ canonical_opc_part_path as _canonical_opc_part_path,
+ resolve_internal_opc_target as _resolve_internal_opc_target,
+ verify_internal_relationships,
+)
from ..animation_config import MorphPair, resolve_morph_pairs
from ..drawingml.converter import convert_svg_to_slide_shapes
@@ -4411,133 +4415,6 @@ def _prerender_legacy_pngs(
return results
-_OPC_UNRESERVED = frozenset(
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
-)
-_ASCII_LOWER_TRANSLATION = str.maketrans(
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
- "abcdefghijklmnopqrstuvwxyz",
-)
-
-
-def _canonical_opc_part_path(path: str) -> str | None:
- """Return an OPC-equivalent package path key, or None when invalid."""
- if (
- not path
- or "\\" in path
- or path.endswith("/")
- or "//" in path
- or any(ord(char) <= 0x20 for char in path)
- ):
- return None
- output: list[str] = []
- index = 0
- while index < len(path):
- char = path[index]
- if char != "%":
- output.append(char)
- index += 1
- continue
- if index + 2 >= len(path) or not re.fullmatch(r"[0-9A-Fa-f]{2}", path[index + 1:index + 3]):
- return None
- value = int(path[index + 1:index + 3], 16)
- decoded = chr(value)
- if value in {0, ord("/"), ord("\\")}:
- return None
- output.append(decoded if decoded in _OPC_UNRESERVED else f"%{value:02X}")
- index += 3
-
- decoded_path = "".join(output)
- if decoded_path.rsplit("/", 1)[-1] in {".", ".."}:
- return None
- normalized = posixpath.normpath(decoded_path)
- if (
- not normalized
- or normalized in {".", ".."}
- or normalized.startswith("/")
- or normalized.startswith("../")
- ):
- return None
- return normalized.translate(_ASCII_LOWER_TRANSLATION)
-
-
-def _source_part_for_rels(rels_path: str) -> str | None:
- """Return the source part path represented by a relationship sidecar."""
- filename = posixpath.basename(rels_path)
- if filename == ".rels" or not filename.endswith(".rels"):
- return None
- source_dir = posixpath.dirname(posixpath.dirname(rels_path))
- source_name = filename[:-len(".rels")]
- return posixpath.join(source_dir, source_name) if source_dir else source_name
-
-
-def _resolve_internal_opc_target(rels_path: str, target: str) -> str | None:
- """Resolve one valid internal OPC Target to its canonical package key."""
- target_path_query = target.split("#", 1)[0]
- if (
- "\\" in target
- or "?" in target_path_query
- or any(ord(char) <= 0x20 for char in target)
- ):
- return None
- try:
- parsed = urlsplit(target)
- except ValueError:
- return None
- if parsed.scheme or parsed.netloc or parsed.query:
- return None
-
- source_part = _source_part_for_rels(rels_path)
- if parsed.path.startswith("/"):
- resolved = parsed.path[1:]
- elif parsed.path:
- base_dir = posixpath.dirname(source_part) if source_part else ""
- resolved = posixpath.join(base_dir, parsed.path) if base_dir else parsed.path
- elif source_part and "#" in target:
- resolved = source_part
- else:
- return None
- return _canonical_opc_part_path(resolved)
-
-
-def _verify_internal_rels_targets(extract_dir: Path) -> list[str]:
- """Return a list of dangling internal Targets across every .rels in the package.
-
- Each entry is formatted as "<rels-path> -> <missing-target>". An empty list
- means every internal Target resolves to a real file in the package.
- """
- package_parts: set[str] = set()
- for path in extract_dir.rglob("*"):
- if not path.is_file():
- continue
- key = _canonical_opc_part_path(path.relative_to(extract_dir).as_posix())
- if key is not None:
- package_parts.add(key)
- problems: list[str] = []
- for rels_path in extract_dir.rglob('*.rels'):
- rels_rel = rels_path.relative_to(extract_dir).as_posix()
- try:
- root = ET.parse(rels_path).getroot()
- except ET.ParseError as exc:
- problems.append(f'{rels_rel} -> <invalid relationships XML: {exc}>')
- continue
- for elem in root:
- attrs = _relationship_attrs(elem)
- if attrs.get('TargetMode', '').lower() == 'external':
- continue
- target = attrs.get('Target')
- if not target:
- problems.append(f'{rels_rel} -> <missing Target>')
- continue
- resolved = _resolve_internal_opc_target(rels_rel, target)
- if resolved is None:
- problems.append(f'{rels_rel} -> <invalid Target {target!r}>')
- continue
- if resolved not in package_parts:
- problems.append(f'{rels_rel} -> {resolved}')
- return problems
-
-
def _presentation_format(width: float, height: float) -> str:
"""Map the slide aspect ratio to PowerPoint's PresentationFormat label.
Non-standard ratios (square, portrait, banner crops) report 'Custom'.
@@ -5945,7 +5822,7 @@ def create_pptx_with_native_svg(
if package_uses_timings:
set_directory_use_timings(extract_dir)
- rels_problems = _verify_internal_rels_targets(extract_dir)
+ rels_problems = verify_internal_relationships(extract_dir)
if rels_problems:
details = '\n'.join(f' - {p}' for p in rels_problems)
raise RuntimeError(