dknowc-dsh 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +9 -4
  2. package/package.json +2 -2
  3. package/skills/dknowc-official-doc-writer/SKILL.md +17 -8
  4. package/skills/dknowc-official-doc-writer/reference/sample_search_result.md +48 -0
  5. package/skills/dknowc-official-doc-writer/reference/sample_trace_report.html +75 -0
  6. package/skills/dknowc-official-doc-writer/reference/search_intro.md +72 -8
  7. package/skills/dknowc-official-doc-writer/scripts/register.mjs +1 -1
  8. package/skills/dknowc-ppt-assistant/README.md +54 -0
  9. package/skills/dknowc-ppt-assistant/SKILL.md +151 -0
  10. package/skills/dknowc-ppt-assistant/THIRD_PARTY_NOTICES.md +36 -0
  11. package/skills/dknowc-ppt-assistant/official-docs/output/.gitkeep +0 -0
  12. package/skills/dknowc-ppt-assistant/official-docs/search-results/.gitkeep +0 -0
  13. package/skills/dknowc-ppt-assistant/projects/.gitkeep +0 -0
  14. package/skills/dknowc-ppt-assistant/references/content-pack.md +55 -0
  15. package/skills/dknowc-ppt-assistant/references/material_usage.md +51 -0
  16. package/skills/dknowc-ppt-assistant/references/sample_effect.html +89 -0
  17. package/skills/dknowc-ppt-assistant/references/sample_search_result.md +48 -0
  18. package/skills/dknowc-ppt-assistant/references/search_intro.md +79 -0
  19. package/skills/dknowc-ppt-assistant/references/style-presets.md +126 -0
  20. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +81 -0
  21. package/skills/dknowc-ppt-assistant/references/upstream-docs/svg-pipeline.md +842 -0
  22. package/skills/dknowc-ppt-assistant/references/upstream-example/01_cover.svg +28 -0
  23. package/skills/dknowc-ppt-assistant/references/upstream-example/02_quote.svg +38 -0
  24. package/skills/dknowc-ppt-assistant/references/upstream-example/03_origin.svg +96 -0
  25. package/skills/dknowc-ppt-assistant/references/upstream-example/README.md +15 -0
  26. package/skills/dknowc-ppt-assistant/references/upstream-example/design_spec.md +408 -0
  27. package/skills/dknowc-ppt-assistant/references/upstream-example/spec_lock.md +78 -0
  28. package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +279 -0
  29. package/skills/dknowc-ppt-assistant/scripts/check_release.py +106 -0
  30. package/skills/dknowc-ppt-assistant/scripts/compact_svg_coordinates.py +345 -0
  31. package/skills/dknowc-ppt-assistant/scripts/config.py +707 -0
  32. package/skills/dknowc-ppt-assistant/scripts/console_encoding.py +33 -0
  33. package/skills/dknowc-ppt-assistant/scripts/error_helper.py +434 -0
  34. package/skills/dknowc-ppt-assistant/scripts/finalize_svg.py +507 -0
  35. package/skills/dknowc-ppt-assistant/scripts/hyperlink_contract.py +399 -0
  36. package/skills/dknowc-ppt-assistant/scripts/initialize.py +182 -0
  37. package/skills/dknowc-ppt-assistant/scripts/language_tags.py +283 -0
  38. package/skills/dknowc-ppt-assistant/scripts/mcp_direct.py +158 -0
  39. package/skills/dknowc-ppt-assistant/scripts/native_payloads.py +655 -0
  40. package/skills/dknowc-ppt-assistant/scripts/pptx_animation_presets.json +3440 -0
  41. package/skills/dknowc-ppt-assistant/scripts/pptx_animations.py +3965 -0
  42. package/skills/dknowc-ppt-assistant/scripts/pptx_effects.py +143 -0
  43. package/skills/dknowc-ppt-assistant/scripts/pptx_opc_validation.py +346 -0
  44. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/__init__.py +130 -0
  45. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-APACHE-2.0.txt +202 -0
  46. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-OPEN-XML-SDK-MIT.txt +23 -0
  47. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/NOTICE.md +54 -0
  48. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeDefinitions.xml +19898 -0
  49. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeSemantics.json +1217 -0
  50. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/shape_type_values.txt +187 -0
  51. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/errors.py +39 -0
  52. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/formula.py +336 -0
  53. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/loader.py +364 -0
  54. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/models.py +201 -0
  55. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/registry.py +270 -0
  56. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantic_hash.py +456 -0
  57. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantics.py +543 -0
  58. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/xml_safety.py +21 -0
  59. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/__init__.py +21 -0
  60. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/animation_import.py +287 -0
  61. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chart_to_svg.py +2377 -0
  62. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chartex_to_svg.py +422 -0
  63. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/color_resolver.py +894 -0
  64. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/converter.py +1143 -0
  65. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/custgeom_to_svg.py +165 -0
  66. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/effect_to_svg.py +410 -0
  67. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/emu_units.py +258 -0
  68. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/fill_to_svg.py +816 -0
  69. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/formula_import.py +611 -0
  70. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/hyperlinks.py +93 -0
  71. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/import_diagnostics.py +37 -0
  72. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ln_to_svg.py +362 -0
  73. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/normalized_chart_svg.py +1217 -0
  74. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ooxml_loader.py +506 -0
  75. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/pic_to_svg.py +653 -0
  76. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_authoring.py +894 -0
  77. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_registry_to_svg.py +216 -0
  78. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_svg_markup.py +198 -0
  79. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/prstgeom_to_svg.py +162 -0
  80. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/shape_walker.py +556 -0
  81. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/slide_to_svg.py +2002 -0
  82. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/tbl_to_svg.py +1841 -0
  83. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/transition_import.py +201 -0
  84. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/txbody_to_svg.py +1433 -0
  85. package/skills/dknowc-ppt-assistant/scripts/pptx_transitions.py +3153 -0
  86. package/skills/dknowc-ppt-assistant/scripts/preset_shape_svg.py +450 -0
  87. package/skills/dknowc-ppt-assistant/scripts/project_utils.py +645 -0
  88. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +183 -0
  89. package/skills/dknowc-ppt-assistant/scripts/register_template.py +1327 -0
  90. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +1048 -0
  91. package/skills/dknowc-ppt-assistant/scripts/resource_paths.py +282 -0
  92. package/skills/dknowc-ppt-assistant/scripts/shape_boolean_svg.py +189 -0
  93. package/skills/dknowc-ppt-assistant/scripts/slide_roster.py +44 -0
  94. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/__init__.py +12 -0
  95. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/align_embed_images.py +672 -0
  96. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/crop_images.py +370 -0
  97. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_icons.py +564 -0
  98. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_images.py +288 -0
  99. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/fix_image_aspect.py +389 -0
  100. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/flatten_tspan.py +948 -0
  101. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/svg_rect_to_path.py +346 -0
  102. package/skills/dknowc-ppt-assistant/scripts/svg_quality/__init__.py +15 -0
  103. package/skills/dknowc-ppt-assistant/scripts/svg_quality/checker.py +7791 -0
  104. package/skills/dknowc-ppt-assistant/scripts/svg_quality/cli.py +193 -0
  105. package/skills/dknowc-ppt-assistant/scripts/svg_quality/svg_contracts.py +1121 -0
  106. package/skills/dknowc-ppt-assistant/scripts/svg_quality/xml_support.py +35 -0
  107. package/skills/dknowc-ppt-assistant/scripts/svg_quality_checker.py +59 -0
  108. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/__init__.py +37 -0
  109. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/animation_config.py +1622 -0
  110. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/canvas_contract.py +226 -0
  111. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/__init__.py +1 -0
  112. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/context.py +291 -0
  113. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/converter.py +1980 -0
  114. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/elements.py +5272 -0
  115. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/hyperlinks.py +162 -0
  116. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/paths.py +847 -0
  117. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/styles.py +752 -0
  118. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/text_properties.py +796 -0
  119. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_colors.py +283 -0
  120. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_fonts.py +330 -0
  121. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/utils.py +3555 -0
  122. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/geometry_properties.py +140 -0
  123. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/__init__.py +356 -0
  124. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_data.py +1449 -0
  125. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_style.py +886 -0
  126. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_xml.py +1495 -0
  127. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chartex.py +272 -0
  128. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/fallback_hash.py +161 -0
  129. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula.py +243 -0
  130. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_ast.py +592 -0
  131. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_compiler.py +96 -0
  132. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_omml.py +1049 -0
  133. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_parser.py +2181 -0
  134. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_profile.py +739 -0
  135. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_run_properties.py +234 -0
  136. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/inline_formula.py +311 -0
  137. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_attributes.py +182 -0
  138. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_common.py +806 -0
  139. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_status.py +190 -0
  140. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/table.py +1113 -0
  141. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/workbook.py +216 -0
  142. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/__init__.py +1 -0
  143. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/builder.py +6273 -0
  144. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/cli.py +2059 -0
  145. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/dimensions.py +189 -0
  146. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/discovery.py +120 -0
  147. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/media.py +160 -0
  148. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/narration.py +696 -0
  149. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/notes.py +336 -0
  150. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/slide_xml.py +138 -0
  151. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_structure.py +3457 -0
  152. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_validation.py +1536 -0
  153. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/semantic_markers.py +240 -0
  154. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/shape_boolean.py +1355 -0
  155. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/text_outline.py +1121 -0
  156. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/tspan_flattener.py +64 -0
  157. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/use_expander.py +577 -0
  158. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx.py +21 -0
  159. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +336 -0
  160. package/skills/dknowc-ppt-assistant/scripts/update_spec.py +404 -0
  161. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +142 -0
  162. package/skills/dknowc-ppt-assistant/workflows/routing.md +38 -0
  163. package/skills/dknowc-trusted-consulting/SKILL.md +21 -5
  164. package/skills/dknowc-trusted-consulting/reference/consult_intro.md +79 -0
  165. package/skills/dknowc-trusted-consulting/reference/sample_consult_answer.md +31 -0
  166. package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +76 -0
  167. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +1 -0
  168. package/skills/dknowc-trusted-search/SKILL.md +30 -2
  169. package/skills/dknowc-trusted-search/reference/sample_search_result.md +33 -0
  170. package/skills/dknowc-trusted-search/reference/sample_trace_report.html +450 -0
  171. package/skills/dknowc-trusted-search/reference/search_intro.md +79 -0
  172. package/skills/dknowc-trusted-search/scripts/register_key.mjs +1 -0
  173. package/src/index.js +7 -2
@@ -0,0 +1,2059 @@
1
+ """CLI entry point for svg_to_pptx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import math
9
+ import re
10
+ import shutil
11
+ import sys
12
+ import zipfile
13
+ from dataclasses import dataclass
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+ from xml.etree import ElementTree as ET
17
+
18
+ _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
19
+ if str(_SCRIPTS_DIR) not in sys.path:
20
+ sys.path.insert(0, str(_SCRIPTS_DIR))
21
+
22
+ from console_encoding import configure_utf8_stdio # noqa: E402
23
+ from language_tags import ( # noqa: E402
24
+ LanguageTagError,
25
+ normalize_language_tag,
26
+ )
27
+ from native_payloads import PAYLOAD_STORE_RELATIVE_PATH # noqa: E402
28
+ from pptx_animations import ( # noqa: E402
29
+ ANIMATIONS,
30
+ animation_seconds_to_milliseconds,
31
+ normalize_animation_effect,
32
+ normalize_animation_trigger,
33
+ )
34
+ from pptx_transitions import ( # noqa: E402
35
+ LEGACY_TRANSITION_KEYS,
36
+ NATIVE_TRANSITION_KEYS,
37
+ normalize_transition_effect_request,
38
+ validate_seconds,
39
+ )
40
+
41
+ configure_utf8_stdio()
42
+
43
+ if __package__ in {None, ''}:
44
+ import types
45
+
46
+ package = types.ModuleType('svg_to_pptx')
47
+ package.__path__ = [str(Path(__file__).resolve().parent)] # type: ignore[attr-defined]
48
+ sys.modules.setdefault('svg_to_pptx', package)
49
+ __package__ = 'svg_to_pptx'
50
+
51
+ from .dimensions import CANVAS_FORMATS, get_project_info
52
+ from .discovery import NotesFileReadError, find_notes_files, find_svg_files
53
+ from .builder import create_pptx_with_native_svg
54
+ from ..native_objects import (
55
+ native_fallback_kind,
56
+ native_replacement_kind,
57
+ native_replacement_status,
58
+ )
59
+ from ..native_objects.marker_status import native_marker_release_block_reason
60
+ from ..drawingml.theme_colors import ThemeColorError, load_theme_color_spec
61
+ from ..drawingml.context import (
62
+ TEXT_FLOW_PRESERVE,
63
+ TEXT_FLOW_REFLOW,
64
+ TEXT_FLOW_SPLIT,
65
+ )
66
+ from ..drawingml.theme_fonts import (
67
+ ThemeFontError,
68
+ load_master_text_style_spec,
69
+ load_theme_font_spec,
70
+ )
71
+ from ..drawingml.utils import unsafe_exported_font_faces
72
+ from .narration import (
73
+ DEFAULT_NARRATION_START_FLOOR,
74
+ NARRATION_EXTENSIONS,
75
+ find_narration_files,
76
+ probe_audio_duration,
77
+ )
78
+ from .template_structure import (
79
+ TemplateStructureError,
80
+ load_pptx_structure_lock,
81
+ parse_template_slides,
82
+ structured_layout_definition_files,
83
+ template_lock_errors,
84
+ template_prototype_errors,
85
+ )
86
+ from ..animation_config import (
87
+ animation_group_effect_entries,
88
+ load_animation_config,
89
+ validate_animation_config,
90
+ validate_animation_config_errors,
91
+ validate_transition_config,
92
+ )
93
+
94
+
95
+ def _as_dict(value: object) -> dict:
96
+ return value if isinstance(value, dict) else {}
97
+
98
+
99
+ _PPTX_STRUCTURE_SECTION_RE = re.compile(
100
+ r"(?ms)^##[ \t]+pptx_structure[ \t]*\r?\n(.*?)(?=^##[ \t]+|\Z)"
101
+ )
102
+ _PPTX_STRUCTURE_MODE_RE = re.compile(
103
+ r"(?m)^-[ \t]+mode[ \t]*:[ \t]*([^#\r\n]*?)[ \t]*(?:#.*)?$"
104
+ )
105
+ _LEGACY_PPTX_STRUCTURE_MODES = frozenset({
106
+ 'baseline',
107
+ 'generated',
108
+ 'preserve',
109
+ 'template',
110
+ })
111
+ _RELEASE_PPTX_STRUCTURE_MODES = frozenset({'flat', 'structured'})
112
+ _CSS_GENERIC_FONT_FAMILIES = frozenset({
113
+ 'cursive',
114
+ 'emoji',
115
+ 'fangsong',
116
+ 'fantasy',
117
+ 'math',
118
+ 'monospace',
119
+ 'sans-serif',
120
+ 'serif',
121
+ 'system-ui',
122
+ 'ui-monospace',
123
+ 'ui-rounded',
124
+ 'ui-sans-serif',
125
+ 'ui-serif',
126
+ })
127
+
128
+
129
+ class PptxPostflightValidationError(RuntimeError):
130
+ """Reject a generated PPTX that fails package postflight validation."""
131
+
132
+
133
+ @dataclass
134
+ class _PostflightReceipt:
135
+ """Carry the compact export result printed after the audit is written."""
136
+
137
+ output_path: Path
138
+ report_path: Path
139
+ status: str
140
+ quality_gate: str
141
+ slide_count: int
142
+ warnings: tuple[str, ...]
143
+
144
+
145
+ def _font_stack_is_generic_only(stack: str) -> bool:
146
+ """Return whether a CSS font stack contains no concrete family name."""
147
+ families = [
148
+ family.strip().strip('"\'').strip().lower()
149
+ for family in stack.split(',')
150
+ if family.strip().strip('"\'').strip()
151
+ ]
152
+ return bool(families) and all(
153
+ family in _CSS_GENERIC_FONT_FAMILIES
154
+ for family in families
155
+ )
156
+
157
+
158
+ def _package_part_counts(pptx_path: Path) -> dict[str, object]:
159
+ """Count public and structural OOXML parts in a completed PPTX package."""
160
+ with zipfile.ZipFile(pptx_path) as archive:
161
+ bad_member = archive.testzip()
162
+ names = archive.namelist()
163
+
164
+ def count(pattern: str) -> int:
165
+ matcher = re.compile(pattern)
166
+ return sum(bool(matcher.fullmatch(name)) for name in names)
167
+
168
+ return {
169
+ 'zip_integrity': 'passed' if bad_member is None else 'failed',
170
+ 'corrupt_member': bad_member,
171
+ 'slides': count(r'ppt/slides/slide\d+\.xml'),
172
+ 'notes': count(r'ppt/notesSlides/notesSlide\d+\.xml'),
173
+ 'masters': count(r'ppt/slideMasters/slideMaster\d+\.xml'),
174
+ 'layouts': count(r'ppt/slideLayouts/slideLayout\d+\.xml'),
175
+ }
176
+
177
+
178
+ def _source_resource_audit(svg_files: list[Path]) -> dict[str, object]:
179
+ """Collect unresolved tokens and portability-oriented source inventories."""
180
+ placeholder_re = re.compile(r'\{\{[^{}]+\}\}')
181
+ placeholders: list[dict[str, str]] = []
182
+ font_stacks: set[str] = set()
183
+ image_counts = {
184
+ 'data_uri': 0,
185
+ 'local': 0,
186
+ 'external': 0,
187
+ }
188
+ external_images: list[dict[str, str]] = []
189
+ for svg_path in svg_files:
190
+ try:
191
+ content = svg_path.read_text(encoding='utf-8')
192
+ root = ET.fromstring(content)
193
+ except (OSError, ET.ParseError):
194
+ continue
195
+ for token in sorted(set(placeholder_re.findall(content))):
196
+ placeholders.append({'file': svg_path.name, 'token': token})
197
+ for element in root.iter():
198
+ font_family = element.get('font-family')
199
+ if font_family:
200
+ font_stacks.add(font_family.strip())
201
+ style = element.get('style') or ''
202
+ for declaration in style.split(';'):
203
+ if ':' not in declaration:
204
+ continue
205
+ name, value = declaration.split(':', 1)
206
+ if name.strip().lower() == 'font-family' and value.strip():
207
+ font_stacks.add(value.strip())
208
+ if element.tag.rsplit('}', 1)[-1] != 'image':
209
+ continue
210
+ href = (
211
+ element.get('href')
212
+ or element.get('{http://www.w3.org/1999/xlink}href')
213
+ or ''
214
+ ).strip()
215
+ if href.startswith('data:'):
216
+ image_counts['data_uri'] += 1
217
+ elif re.match(r'^[a-z][a-z0-9+.-]*://', href, re.IGNORECASE):
218
+ image_counts['external'] += 1
219
+ external_images.append({
220
+ 'file': svg_path.name,
221
+ 'href': href,
222
+ })
223
+ elif href:
224
+ image_counts['local'] += 1
225
+ generic_only_font_stacks = sorted({
226
+ stack
227
+ for stack in font_stacks
228
+ if _font_stack_is_generic_only(stack)
229
+ })
230
+ unsafe_font_faces = [
231
+ {
232
+ 'stack': stack,
233
+ 'role': role,
234
+ 'typeface': typeface,
235
+ }
236
+ for stack in sorted(font_stacks)
237
+ for role, typeface in unsafe_exported_font_faces(stack).items()
238
+ ]
239
+ return {
240
+ 'unresolved_template_tokens': placeholders,
241
+ 'fonts': {
242
+ 'stacks': sorted(font_stacks),
243
+ 'generic_only_stacks': generic_only_font_stacks,
244
+ 'unsafe_exported_faces': unsafe_font_faces,
245
+ },
246
+ 'images': {
247
+ **image_counts,
248
+ 'external_references': external_images,
249
+ },
250
+ }
251
+
252
+
253
+ def _svg_source_fingerprint(svg_files: list[Path]) -> dict[str, object]:
254
+ """Return one deterministic digest for the exact SVG export inputs."""
255
+ files: list[dict[str, object]] = []
256
+ aggregate = hashlib.sha256()
257
+ for path in sorted(svg_files, key=lambda item: item.name):
258
+ file_sha256 = hashlib.sha256(path.read_bytes()).hexdigest()
259
+ files.append({'file': path.name, 'sha256': file_sha256})
260
+ aggregate.update(path.name.encode('utf-8'))
261
+ aggregate.update(b'\0')
262
+ aggregate.update(file_sha256.encode('ascii'))
263
+ aggregate.update(b'\n')
264
+ return {
265
+ 'algorithm': 'sha256',
266
+ 'digest': aggregate.hexdigest(),
267
+ 'file_count': len(files),
268
+ 'files': files,
269
+ }
270
+
271
+
272
+ def _quality_report_context(
273
+ project_path: Path,
274
+ source_fingerprint: dict[str, object],
275
+ ) -> dict[str, object]:
276
+ """Load the final SVG quality report when the preceding gate wrote one."""
277
+ quality_path = project_path / 'validation' / 'svg_quality_report.json'
278
+ try:
279
+ quality = json.loads(quality_path.read_text(encoding='utf-8'))
280
+ except FileNotFoundError:
281
+ return {'status': 'not-provided', 'path': str(quality_path)}
282
+ except (OSError, json.JSONDecodeError) as exc:
283
+ return {
284
+ 'status': 'unreadable',
285
+ 'path': str(quality_path),
286
+ 'error': str(exc),
287
+ }
288
+ schema = quality.get('schema')
289
+ if schema != 'ppt-master.svg-quality-report.v1':
290
+ return {
291
+ 'status': 'unsupported-schema',
292
+ 'path': str(quality_path),
293
+ 'schema': schema,
294
+ }
295
+ categories = quality.get('categories')
296
+ quality_fingerprint = quality.get('source_fingerprint')
297
+ if not isinstance(quality_fingerprint, dict):
298
+ source_match = 'unavailable'
299
+ elif (
300
+ quality_fingerprint.get('algorithm') == 'sha256'
301
+ and quality_fingerprint.get('digest') == source_fingerprint.get('digest')
302
+ and quality_fingerprint.get('file_count')
303
+ == source_fingerprint.get('file_count')
304
+ ):
305
+ source_match = 'passed'
306
+ else:
307
+ source_match = 'mismatch'
308
+ return {
309
+ 'status': 'loaded',
310
+ 'path': str(quality_path),
311
+ 'schema': schema,
312
+ 'stage': quality.get('stage'),
313
+ 'source_match': source_match,
314
+ 'source_fingerprint': quality_fingerprint,
315
+ 'summary': quality.get('summary'),
316
+ 'categories': categories if isinstance(categories, dict) else {},
317
+ }
318
+
319
+
320
+ def _quality_gate_status(
321
+ quality: dict[str, object],
322
+ ) -> tuple[str, int]:
323
+ """Return final-gate status and introduced-warning count."""
324
+ categories = quality.get('categories')
325
+ blocking_count = None
326
+ introduced_warning_count = 0
327
+ if isinstance(categories, dict):
328
+ blocking = categories.get('blocking')
329
+ if isinstance(blocking, dict):
330
+ blocking_count = blocking.get('count')
331
+ introduced = categories.get('introduced')
332
+ if (
333
+ isinstance(introduced, dict)
334
+ and isinstance(introduced.get('count'), int)
335
+ ):
336
+ introduced_warning_count = int(introduced['count'])
337
+ if quality.get('status') != 'loaded':
338
+ return str(quality.get('status') or 'not-provided'), introduced_warning_count
339
+ if quality.get('stage') != 'final':
340
+ return 'non-final', introduced_warning_count
341
+ if not isinstance(blocking_count, int):
342
+ return 'unverified', introduced_warning_count
343
+ if blocking_count > 0:
344
+ return 'failed', introduced_warning_count
345
+ if quality.get('source_match') == 'mismatch':
346
+ return 'stale', introduced_warning_count
347
+ if quality.get('source_match') != 'passed':
348
+ return 'unverified', introduced_warning_count
349
+ return 'passed', introduced_warning_count
350
+
351
+
352
+ def _postflight_warning_summaries(
353
+ *,
354
+ quality_gate: str,
355
+ introduced_warning_count: int,
356
+ unresolved_token_count: int,
357
+ external_image_count: int,
358
+ generic_font_stack_count: int,
359
+ unsafe_font_face_count: int,
360
+ ) -> tuple[str, ...]:
361
+ """Return stable warning summaries for the terminal receipt."""
362
+ warnings: list[str] = []
363
+ if quality_gate != 'passed':
364
+ warnings.append(f'quality_gate={quality_gate}')
365
+ if introduced_warning_count:
366
+ warnings.append(f'quality_introduced_warnings={introduced_warning_count}')
367
+ if unresolved_token_count:
368
+ warnings.append(f'unresolved_template_tokens={unresolved_token_count}')
369
+ if external_image_count:
370
+ warnings.append(f'external_images={external_image_count}')
371
+ if generic_font_stack_count:
372
+ warnings.append(f'generic_only_font_stacks={generic_font_stack_count}')
373
+ if unsafe_font_face_count:
374
+ warnings.append(f'unsafe_exported_font_faces={unsafe_font_face_count}')
375
+ return tuple(warnings)
376
+
377
+
378
+ def _write_postflight_report(
379
+ *,
380
+ output_path: Path,
381
+ project_path: Path,
382
+ svg_files: list[Path],
383
+ layout_definition_files: list[Path],
384
+ pptx_structure: str,
385
+ backup_path: Path | None,
386
+ conversion_trace_path: Path | None,
387
+ deck_motion: dict[str, object],
388
+ ) -> _PostflightReceipt:
389
+ """Write the unified package/resource audit for a successful PPTX."""
390
+ try:
391
+ package = _package_part_counts(output_path)
392
+ except (OSError, zipfile.BadZipFile) as exc:
393
+ raise PptxPostflightValidationError(
394
+ f"generated PPTX is not a readable ZIP package: {exc}"
395
+ ) from exc
396
+ if package['zip_integrity'] != 'passed':
397
+ raise PptxPostflightValidationError(
398
+ f"PPTX ZIP integrity failed at {package['corrupt_member']}"
399
+ )
400
+ if package['slides'] != len(svg_files):
401
+ raise PptxPostflightValidationError(
402
+ "Published Slide count does not match authored SVG count: "
403
+ f"{package['slides']} != {len(svg_files)}"
404
+ )
405
+ source_audit = _source_resource_audit(svg_files)
406
+ source_fingerprint = _svg_source_fingerprint(svg_files)
407
+ quality = _quality_report_context(project_path, source_fingerprint)
408
+ quality_gate, introduced_warning_count = _quality_gate_status(quality)
409
+ unresolved_tokens = source_audit['unresolved_template_tokens']
410
+ external_image_count = source_audit['images']['external']
411
+ generic_only_font_stacks = source_audit['fonts']['generic_only_stacks']
412
+ unsafe_font_faces = source_audit['fonts']['unsafe_exported_faces']
413
+ if quality_gate == 'failed':
414
+ report_status = 'failed'
415
+ elif (
416
+ not unresolved_tokens
417
+ and not external_image_count
418
+ and not generic_only_font_stacks
419
+ and not unsafe_font_faces
420
+ and not introduced_warning_count
421
+ and quality_gate == 'passed'
422
+ ):
423
+ report_status = 'passed'
424
+ else:
425
+ report_status = 'passed-with-warnings'
426
+ report_path = (
427
+ project_path / 'validation' / f'{output_path.stem}.report.json'
428
+ )
429
+ report = {
430
+ 'schema': 'ppt-master.pptx-postflight-report.v1',
431
+ 'status': report_status,
432
+ 'output': {
433
+ 'path': str(output_path.resolve()),
434
+ 'bytes': output_path.stat().st_size,
435
+ },
436
+ 'source': {
437
+ 'svg_slide_count': len(svg_files),
438
+ 'layout_definition_count': len(layout_definition_files),
439
+ 'fingerprint': source_fingerprint,
440
+ },
441
+ 'package': package,
442
+ 'checks': {
443
+ 'zip_integrity': 'passed',
444
+ 'slide_count': 'passed',
445
+ 'internal_relationships': 'enforced-at-build',
446
+ 'structured_package': (
447
+ 'enforced-at-build'
448
+ if pptx_structure == 'structured'
449
+ else 'not-applicable'
450
+ ),
451
+ 'transitions': 'enforced-at-build',
452
+ 'animations': 'enforced-at-build',
453
+ 'quality_gate': quality_gate,
454
+ 'quality_warnings': (
455
+ 'passed' if not introduced_warning_count else 'warning'
456
+ ),
457
+ 'template_tokens': (
458
+ 'passed' if not unresolved_tokens else 'warning'
459
+ ),
460
+ 'external_images': (
461
+ 'passed' if not external_image_count else 'warning'
462
+ ),
463
+ 'font_portability': (
464
+ 'passed'
465
+ if not generic_only_font_stacks and not unsafe_font_faces
466
+ else 'warning'
467
+ ),
468
+ },
469
+ 'quality': quality,
470
+ 'resources': source_audit,
471
+ 'deck_motion': deck_motion,
472
+ 'backup_path': str(backup_path.resolve()) if backup_path else None,
473
+ 'conversion_trace_path': (
474
+ str(conversion_trace_path.resolve())
475
+ if conversion_trace_path and conversion_trace_path.is_file()
476
+ else None
477
+ ),
478
+ }
479
+ report_path.parent.mkdir(parents=True, exist_ok=True)
480
+ report_path.write_text(
481
+ json.dumps(report, ensure_ascii=False, indent=2) + '\n',
482
+ encoding='utf-8',
483
+ )
484
+ warnings = _postflight_warning_summaries(
485
+ quality_gate=quality_gate,
486
+ introduced_warning_count=introduced_warning_count,
487
+ unresolved_token_count=len(unresolved_tokens),
488
+ external_image_count=external_image_count,
489
+ generic_font_stack_count=len(generic_only_font_stacks),
490
+ unsafe_font_face_count=len(unsafe_font_faces),
491
+ )
492
+ return _PostflightReceipt(
493
+ output_path=output_path,
494
+ report_path=report_path,
495
+ status=report_status,
496
+ quality_gate=quality_gate,
497
+ slide_count=int(package['slides']),
498
+ warnings=warnings,
499
+ )
500
+
501
+
502
+ def _load_deck_motion_handoff(
503
+ project_path: Path,
504
+ report_arg: str,
505
+ svg_files: list[Path],
506
+ ) -> dict[str, object]:
507
+ """Load source-bound deck motion from a successful base export report."""
508
+ report_path = Path(report_arg).expanduser()
509
+ if not report_path.is_absolute() and not report_path.is_file():
510
+ report_path = project_path / report_path
511
+ try:
512
+ report = json.loads(report_path.read_text(encoding='utf-8'))
513
+ except FileNotFoundError as exc:
514
+ raise ValueError(
515
+ f'deck-motion handoff report does not exist: {report_path}'
516
+ ) from exc
517
+ except (OSError, json.JSONDecodeError) as exc:
518
+ raise ValueError(
519
+ f'deck-motion handoff report is unreadable: {report_path}: {exc}'
520
+ ) from exc
521
+ if not isinstance(report, dict):
522
+ raise ValueError('deck-motion handoff report must be a JSON object')
523
+ if report.get('schema') != 'ppt-master.pptx-postflight-report.v1':
524
+ raise ValueError(
525
+ 'deck-motion handoff requires a ppt-master postflight report'
526
+ )
527
+ if report.get('status') not in {'passed', 'passed-with-warnings'}:
528
+ raise ValueError('deck-motion handoff report is not a successful export')
529
+ source = _as_dict(report.get('source'))
530
+ if source.get('fingerprint') != _svg_source_fingerprint(svg_files):
531
+ raise ValueError(
532
+ 'deck-motion handoff does not match the current svg_output; '
533
+ 'run the base export again'
534
+ )
535
+ motion = report.get('deck_motion')
536
+ if not isinstance(motion, dict):
537
+ raise ValueError(
538
+ 'deck-motion handoff is missing from the base export report; '
539
+ 'run the base export again'
540
+ )
541
+ if motion.get('narration_timings') is True:
542
+ raise ValueError(
543
+ 'deck-motion handoff must reference a base non-narrated export report'
544
+ )
545
+ if not isinstance(motion.get('transition'), dict):
546
+ raise ValueError('deck-motion handoff transition must be an object')
547
+ if not isinstance(motion.get('animation'), dict):
548
+ raise ValueError('deck-motion handoff animation must be an object')
549
+ if not isinstance(motion.get('cli_overrides'), dict):
550
+ raise ValueError('deck-motion handoff cli_overrides must be an object')
551
+ return motion
552
+
553
+
554
+ def _print_postflight_receipt(receipt: _PostflightReceipt) -> None:
555
+ """Print the compact completion evidence; keep the full JSON on disk."""
556
+ print(
557
+ ' [POSTFLIGHT] '
558
+ f'status={receipt.status} '
559
+ f'quality_gate={receipt.quality_gate} '
560
+ f'slides={receipt.slide_count} '
561
+ f'warning_categories={len(receipt.warnings)}'
562
+ )
563
+ for warning in receipt.warnings:
564
+ print(f' [POSTFLIGHT][WARNING] {warning}')
565
+ print(f' [PPTX] {receipt.output_path}')
566
+ print(f' [REPORT] {receipt.report_path}')
567
+
568
+
569
+ def _declared_pptx_structure_mode(project_path: Path) -> str | None:
570
+ """Return the explicitly locked SVG export mode, if the lock declares one."""
571
+ lock_path = project_path / 'spec_lock.md'
572
+ try:
573
+ content = lock_path.read_text(encoding='utf-8')
574
+ except OSError:
575
+ return None
576
+ section_match = _PPTX_STRUCTURE_SECTION_RE.search(content)
577
+ if section_match is None:
578
+ return None
579
+ mode_match = _PPTX_STRUCTURE_MODE_RE.search(section_match.group(1))
580
+ return mode_match.group(1).strip().lower() if mode_match else None
581
+
582
+
583
+ def _declared_canvas_viewbox(project_path: Path) -> str | None:
584
+ """Return the project-lock root canvas without inferring from its name."""
585
+ lock_path = project_path / 'spec_lock.md'
586
+ try:
587
+ from update_spec import parse_lock
588
+
589
+ lock = parse_lock(lock_path)
590
+ except (OSError, ValueError):
591
+ return None
592
+ canvas = lock.get('canvas', {})
593
+ value = canvas.get('viewBox')
594
+ return value.strip() if isinstance(value, str) and value.strip() else None
595
+
596
+
597
+ def _declared_primary_language(project_path: Path) -> str | None:
598
+ """Return the canonical content language declared by the execution lock."""
599
+ lock_path = project_path / 'spec_lock.md'
600
+ try:
601
+ from update_spec import parse_lock
602
+
603
+ lock = parse_lock(lock_path)
604
+ except (OSError, ValueError):
605
+ return None
606
+ communication = lock.get('communication', {})
607
+ value = communication.get('primary_language')
608
+ if not isinstance(value, str) or not value.strip():
609
+ return None
610
+ try:
611
+ return normalize_language_tag(value)
612
+ except LanguageTagError as exc:
613
+ raise LanguageTagError(
614
+ 'spec_lock.md communication.primary_language '
615
+ f'is invalid: {exc}'
616
+ ) from exc
617
+
618
+
619
+ def _print_structure_contract_error(
620
+ mode: str | None,
621
+ *,
622
+ requested_mode: str | None = None,
623
+ ) -> None:
624
+ """Explain an unsupported mode or a structured-export lock mismatch."""
625
+ label = repr(mode) if mode is not None else 'missing'
626
+ if requested_mode == 'structured':
627
+ print(
628
+ "Error: --pptx-structure structured requires an explicit "
629
+ "spec_lock.md pptx_structure.mode: structured contract; found "
630
+ + label + ".",
631
+ file=sys.stderr,
632
+ )
633
+ print(
634
+ " A legacy lock without pptx_structure.mode defaults only to flat. "
635
+ "Mirror/layout reuse must first create a current template workspace "
636
+ "through skills/ppt-master/workflows/create-template.md, then generate "
637
+ "new structured SVG pages.",
638
+ file=sys.stderr,
639
+ )
640
+ return
641
+ print(
642
+ "Error: unsupported spec_lock.md pptx_structure.mode " + label + ". "
643
+ "Current release modes are flat (style reference / free design / "
644
+ "brand-only) and structured (mirror/layout reuse).",
645
+ file=sys.stderr,
646
+ )
647
+ print(
648
+ " A legacy lock with no pptx_structure.mode defaults to flat. "
649
+ "Explicit legacy or unknown values are not inferred. Mirror/layout reuse "
650
+ "must first create a current template workspace "
651
+ "through skills/ppt-master/workflows/create-template.md, then generate "
652
+ "new structured SVG pages.",
653
+ file=sys.stderr,
654
+ )
655
+
656
+
657
+ def _native_object_fallbacks(svg_files: list[Path]) -> list[tuple[str, str, str]]:
658
+ """Return fallback-only chart/table replacement statuses from SVG inputs."""
659
+ fallbacks: list[tuple[str, str, str]] = []
660
+ for svg_path in svg_files:
661
+ try:
662
+ root = ET.parse(svg_path).getroot()
663
+ except (OSError, ET.ParseError):
664
+ continue
665
+ for elem in root.iter():
666
+ status = native_replacement_status(elem)
667
+ if not status or elem.tag.rsplit('}', 1)[-1] == 'metadata':
668
+ continue
669
+ marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'
670
+ fallbacks.append((svg_path.name, marker_id, status))
671
+ return fallbacks
672
+
673
+
674
+ def _release_blocked_graphics(
675
+ svg_files: list[Path],
676
+ ) -> list[tuple[str, str, str]]:
677
+ """Return graphics whose status metadata is invalid."""
678
+ blocked: list[tuple[str, str, str]] = []
679
+ for svg_path in svg_files:
680
+ try:
681
+ root = ET.parse(svg_path).getroot()
682
+ except (OSError, ET.ParseError):
683
+ continue
684
+ for elem in root.iter():
685
+ if elem.tag.rsplit('}', 1)[-1] == 'metadata':
686
+ continue
687
+ reason = native_marker_release_block_reason(elem)
688
+ if reason is None:
689
+ continue
690
+ marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'
691
+ blocked.append((svg_path.name, marker_id, reason))
692
+ return blocked
693
+
694
+
695
+ def _reconstruction_only_graphics(
696
+ svg_files: list[Path],
697
+ ) -> list[tuple[str, str, bool]]:
698
+ """Return valid placeholder routes for non-blocking diagnostics."""
699
+ diagnostics: list[tuple[str, str, bool]] = []
700
+ for svg_path in svg_files:
701
+ try:
702
+ root = ET.parse(svg_path).getroot()
703
+ except (OSError, ET.ParseError):
704
+ continue
705
+ for elem in root.iter():
706
+ if elem.tag.rsplit('}', 1)[-1] == 'metadata':
707
+ continue
708
+ if native_fallback_kind(elem) != 'placeholder':
709
+ continue
710
+ if native_marker_release_block_reason(elem) is not None:
711
+ continue
712
+ marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'
713
+ active_native = bool(native_replacement_kind(elem))
714
+ diagnostics.append((svg_path.name, marker_id, active_native))
715
+ return diagnostics
716
+
717
+
718
+ def _recorded_narration_on_click_slides(
719
+ ref_files: list[Path],
720
+ animation_config: dict | None,
721
+ animation: str | None,
722
+ animation_trigger: str,
723
+ animation_cli_overrides: dict[str, bool],
724
+ ) -> list[str]:
725
+ """Return slides whose effective recorded-video animation trigger is on-click."""
726
+ if animation_cli_overrides.get('animation') and animation is None:
727
+ return []
728
+ slides_cfg = _as_dict(_as_dict(animation_config).get('slides'))
729
+ blocked: list[str] = []
730
+ for svg_path in ref_files:
731
+ slide_cfg = _as_dict(slides_cfg.get(svg_path.stem))
732
+ anim_cfg = _as_dict(slide_cfg.get('animation'))
733
+
734
+ slide_animation = animation
735
+ if not animation_cli_overrides.get('animation') and 'effect' in anim_cfg:
736
+ slide_animation = normalize_animation_effect(anim_cfg.get('effect'))
737
+ slide_trigger = animation_trigger
738
+ if (
739
+ not animation_cli_overrides.get('animation_trigger')
740
+ and anim_cfg.get('trigger')
741
+ ):
742
+ slide_trigger = normalize_animation_trigger(anim_cfg.get('trigger'))
743
+
744
+ groups_cfg = _as_dict(slide_cfg.get('groups'))
745
+ has_interactive_animation = False
746
+ for group_id, group_cfg in groups_cfg.items():
747
+ if not isinstance(group_cfg, dict):
748
+ continue
749
+ group_path = (
750
+ f'slides[{json.dumps(svg_path.stem, ensure_ascii=False)}]'
751
+ f'.groups[{json.dumps(str(group_id), ensure_ascii=False)}]'
752
+ )
753
+ for _effect_path, effect_cfg in animation_group_effect_entries(
754
+ group_cfg,
755
+ path=group_path,
756
+ ):
757
+ row_effect = (
758
+ normalize_animation_effect(effect_cfg.get('effect'))
759
+ if 'effect' in effect_cfg
760
+ else slide_animation
761
+ )
762
+ if row_effect is None:
763
+ continue
764
+ row_trigger = (
765
+ normalize_animation_trigger(effect_cfg.get('trigger'))
766
+ if effect_cfg.get('trigger')
767
+ else slide_trigger
768
+ )
769
+ if effect_cfg.get('trigger_shape') is not None:
770
+ has_interactive_animation = True
771
+ break
772
+ if row_trigger == 'on-click':
773
+ has_interactive_animation = True
774
+ break
775
+ if has_interactive_animation:
776
+ break
777
+
778
+ if has_interactive_animation or (
779
+ slide_animation is not None and slide_trigger == 'on-click'
780
+ ):
781
+ blocked.append(svg_path.stem)
782
+ return blocked
783
+
784
+
785
+ def _resolve_animation_config_source(
786
+ project_path: Path,
787
+ requested_config: str | None,
788
+ *,
789
+ recorded_narration: bool,
790
+ no_animations: bool,
791
+ ) -> str | None:
792
+ """Resolve the animation sidecar selected for this export."""
793
+ if requested_config is not None or not recorded_narration or no_animations:
794
+ return requested_config
795
+
796
+ canonical_exists = (project_path / 'animations.json').is_file()
797
+ narration_exists = (project_path / 'narration_animations.json').is_file()
798
+ if canonical_exists or narration_exists:
799
+ return 'narration_animations.json'
800
+ return None
801
+
802
+
803
+ def main(argv: list[str] | None = None) -> int:
804
+ """CLI entry point for the SVG to PPTX conversion tool."""
805
+ transition_choices = [
806
+ 'none',
807
+ *NATIVE_TRANSITION_KEYS,
808
+ *LEGACY_TRANSITION_KEYS,
809
+ ]
810
+
811
+ animation_choices = ['none', *ANIMATIONS, 'auto', 'mixed', 'random']
812
+
813
+ parser = argparse.ArgumentParser(
814
+ description='PPT Master - SVG to native DrawingML PPTX Tool',
815
+ formatter_class=argparse.RawDescriptionHelpFormatter,
816
+ epilog=f'''
817
+ Examples:
818
+ %(prog)s examples/ppt169_demo # Default: native pptx -> exports/, svg_output -> backup/<ts>/
819
+ %(prog)s examples/ppt169_demo -o out.pptx # Explicit path (no backup/)
820
+ %(prog)s projects/quick_generate_demo --quick-generate # Lockless flat export with normal postflight
821
+
822
+ # Disable transition / change transition effect
823
+ %(prog)s examples/ppt169_demo -t none
824
+ %(prog)s examples/ppt169_demo -t push --transition-duration 1.0
825
+
826
+ SVG source directory (-s):
827
+ output - svg_output (hand-authored source; native default)
828
+ final - svg_final (post-processed preview; diagnostic native input only)
829
+ <any> - Specify a subdirectory name directly
830
+ Omit -s to use the default: native export reads svg_output.
831
+
832
+ Transition effects (-t/--transition):
833
+ New selections use the 48 PowerPoint-native gallery keys. The 8 old
834
+ names remain accepted only as compatibility inputs. Run
835
+ scripts/pptx_animations.py --list for the categorized registry and
836
+ --describe-transition <effect> for its Effect Options.
837
+
838
+ Per-element object animation (-a/--animation, native shapes mode):
839
+ Use PowerPoint-native entrance_*, emphasis_*, path_*, and exit_* keys for
840
+ new animation choices. The 29 old short names remain accepted only as
841
+ compatibility inputs. Run scripts/pptx_animations.py --list for the
842
+ complete categorized 232-key input registry.
843
+ Notes: applied to top-level <g id="..."> SVG groups in z-order. Default is
844
+ "none" (no auto element builds; page transitions still apply). Use
845
+ "-a auto" to map effects from group id: chart→entrance_wipe,
846
+ card-/step-/pillar-→entrance_fly,
847
+ title/takeaway→entrance_fade; image-like ids
848
+ hero/figure-/image/img-/kpi cycle canonical entrance presets;
849
+ unmatched ids cycle entrance_fade/entrance_wipe/entrance_fly/
850
+ entrance_zoom. Start mode set by --animation-trigger, matching
851
+ PowerPoint's Start dropdown:
852
+ on-click one presenter click per group
853
+ with-previous all groups start together on slide entry
854
+ after-previous (default) cascade on slide entry;
855
+ gap = --animation-stagger seconds
856
+ mixed (compatible mode name) cycles a larger 16-preset canonical
857
+ PowerPoint entrance pool by group order; random samples from the
858
+ same entrance pool. Use explicit canonical keys for emphasis,
859
+ motion-path, or exit duties. Use "-a none" to disable element
860
+ builds explicitly.
861
+
862
+ Speaker notes:
863
+ - Automatically reads Markdown notes files from the notes/ directory
864
+ - Supports two naming conventions:
865
+ 1. Match by filename (recommended): 01_cover.md corresponds to 01_cover.svg
866
+ 2. Match by index: slide01.md corresponds to the 1st SVG (backward compatible)
867
+ - Enabled by default outside Quick Generate; use --no-notes to disable
868
+ - Disabled by default in Quick Generate; use --with-notes to enable
869
+
870
+ Recorded narration:
871
+ %(prog)s examples/ppt169_demo --recorded-narration audio \\
872
+ --inherit-motion-from validation/<base>.report.json
873
+ - Keeps speaker notes when enabled
874
+ - Prepares PowerPoint recorded timings and narrations
875
+ - Requires one m4a/mp3/wav file per slide
876
+ - Unless --no-animations is set, recorded narration without an explicit
877
+ config selects narration_animations.json when either sidecar exists
878
+ - With no sidecar, --inherit-motion-from may restore base-report deck motion
879
+ - Use --animation-config animations.json for narration-independent custom motion
880
+ - Use --no-animations for narration and timings without animation motion
881
+ - Embeds per-slide audio matched by SVG filename / slide number
882
+ - Sets slide auto-advance from audio duration so video export can use
883
+ "recorded timings and narrations"
884
+ - Rejects on-click object animations; use after-previous or with-previous
885
+ %(prog)s examples/ppt169_demo --narration-audio-dir audio
886
+ - Lower-level audio embedding: embeds matched files but allows partial matches
887
+ - Use only when you do not need a complete recorded-timings export
888
+ ''',
889
+ )
890
+
891
+ parser.add_argument('project_path', type=str, help='Project directory path')
892
+ parser.add_argument('-o', '--output', type=str, default=None, help='Output file path')
893
+ parser.add_argument('-s', '--source', type=str, default=None,
894
+ help='Native SVG source directory. Default: svg_output/. '
895
+ 'Pass output/final/<name> only for diagnostics.')
896
+ parser.add_argument('-f', '--format', type=str,
897
+ choices=list(CANVAS_FORMATS.keys()), default=None,
898
+ help='Require SVG canvases to match this registered format')
899
+ parser.add_argument('-q', '--quiet', action='store_true', help='Quiet mode')
900
+ parser.add_argument(
901
+ '--quick-generate',
902
+ action='store_true',
903
+ help=(
904
+ 'Export a Quick Generate SVG roster from svg_output/ without '
905
+ 'spec_lock.md. Require a matching final quality report, infer one '
906
+ 'consistent canvas, use a flat package with converter defaults, '
907
+ 'and support normal export capabilities.'
908
+ ),
909
+ )
910
+
911
+ text_flow_group = parser.add_mutually_exclusive_group()
912
+ text_flow_group.add_argument(
913
+ '--reflow-text',
914
+ action='store_const',
915
+ const=TEXT_FLOW_REFLOW,
916
+ dest='text_flow',
917
+ help=(
918
+ 'Let PowerPoint automatically reflow conservative dy-stacked text '
919
+ 'inside one editable text frame.'
920
+ ),
921
+ )
922
+ text_flow_group.add_argument(
923
+ '--merge-paragraphs',
924
+ action='store_const',
925
+ const=TEXT_FLOW_REFLOW,
926
+ dest='text_flow',
927
+ help='Compatibility alias for --reflow-text.',
928
+ )
929
+ text_flow_group.add_argument(
930
+ '--no-merge',
931
+ action='store_const',
932
+ const=TEXT_FLOW_SPLIT,
933
+ dest='text_flow',
934
+ help=(
935
+ 'Emit every positioned visual line as its own text frame for '
936
+ 'strict per-line SVG positioning.'
937
+ ),
938
+ )
939
+ parser.set_defaults(text_flow=TEXT_FLOW_PRESERVE)
940
+ parser.add_argument(
941
+ '--conversion-trace',
942
+ nargs='?',
943
+ const='',
944
+ default=None,
945
+ metavar='PATH',
946
+ help='Write per-slide SVG conversion diagnostics. Without PATH, write '
947
+ '<project>/validation/<output_stem>.trace.json; relative PATHs '
948
+ 'are resolved from the project root.',
949
+ )
950
+ parser.add_argument(
951
+ '--native-charts-and-tables',
952
+ dest='native_objects',
953
+ action='store_true',
954
+ default=False,
955
+ help=(
956
+ 'Replace explicit data-pptx-replace-with chart/table groups with '
957
+ 'PowerPoint native Chart/Table objects. This data-object route may '
958
+ 'normalize styling or omit fallback-only visuals. Default off: groups '
959
+ 'export as editable SVG-derived DrawingML shapes. The default-flow '
960
+ 'output uses <project>_<ts>_native_charts_tables.pptx.'
961
+ ),
962
+ )
963
+ parser.add_argument(
964
+ '--native-objects',
965
+ dest='native_objects',
966
+ action='store_true',
967
+ help=argparse.SUPPRESS,
968
+ )
969
+ parser.add_argument(
970
+ '--pptx-structure',
971
+ choices=[
972
+ 'structured',
973
+ 'flat',
974
+ 'baseline',
975
+ 'template',
976
+ 'preserve',
977
+ 'generated',
978
+ ],
979
+ default=None,
980
+ help=(
981
+ 'PPTX structure strategy for native export. Omitting this flag reads '
982
+ 'spec_lock.md; a legacy lock without pptx_structure.mode defaults to '
983
+ 'flat. Flat is the style-reference/free-design/brand-only release mode and '
984
+ 'builds one clean project-owned Master plus Blank Layout while keeping '
985
+ 'all SVG objects slide-local; structured is the mirror/layout reuse '
986
+ 'mode and requires complete explicit metadata. baseline, template, '
987
+ 'preserve, and generated are accepted only to report a migration error.'
988
+ ),
989
+ )
990
+ parser.add_argument('--no-image-optimize', action='store_true',
991
+ help='Disable native PPTX raster image optimization and always embed '
992
+ 'the original image bytes.')
993
+ parser.add_argument('--image-max-dimension', type=int, default=2560,
994
+ help='Preferred raster cap in pixels. Cap mode re-encodes only images '
995
+ 'that require resizing or EXIF geometry normalization, and may '
996
+ 'retain more pixels for cropped/stretched visible resolution '
997
+ '(default: 2560).')
998
+ parser.add_argument('--image-sizing', choices=['cap', 'display'], default='cap',
999
+ help='Raster sizing mode: cap preserves original bytes unless resizing '
1000
+ 'or EXIF geometry normalization is required; display targets the '
1001
+ 'SVG rendered box for explicit compaction (default: cap).')
1002
+ parser.add_argument('--image-scale', type=float, default=2.0,
1003
+ help='Target optimized image pixels per SVG display pixel '
1004
+ 'when --image-sizing=display (default: 2.0).')
1005
+ parser.add_argument('--image-quality', type=int, default=85,
1006
+ help='JPEG quality for raster images re-encoded during optimization, '
1007
+ '1-100 (default: 85).')
1008
+
1009
+ def non_negative_float(value: str) -> float:
1010
+ try:
1011
+ number = float(value)
1012
+ except ValueError as exc:
1013
+ raise argparse.ArgumentTypeError(f"must be a number: {value}") from exc
1014
+ if not math.isfinite(number):
1015
+ raise argparse.ArgumentTypeError("must be finite")
1016
+ if number < 0:
1017
+ raise argparse.ArgumentTypeError("must be non-negative")
1018
+ return number
1019
+
1020
+ def positive_float(value: str) -> float:
1021
+ number = non_negative_float(value)
1022
+ if number <= 0:
1023
+ raise argparse.ArgumentTypeError("must be greater than zero")
1024
+ return number
1025
+
1026
+ parser.add_argument('-t', '--transition', type=str, choices=transition_choices, default=None,
1027
+ help='Page transition effect (default: fade; "none" removes visual motion)')
1028
+ parser.add_argument('--transition-duration', type=non_negative_float, default=None,
1029
+ help='Transition duration in seconds (default: 0.4)')
1030
+ parser.add_argument('--auto-advance', type=non_negative_float, default=None,
1031
+ help='Auto-advance interval in seconds (default: manual advance)')
1032
+
1033
+ parser.add_argument('-a', '--animation', type=str, choices=animation_choices,
1034
+ default=None,
1035
+ help='Per-element object animation (native shapes mode '
1036
+ 'only). Default "none" (no auto element builds; page '
1037
+ 'transitions still apply). Pick a native entrance_*/'
1038
+ 'emphasis_*/path_*/exit_* key or "auto" '
1039
+ '(map effect from group id — image-like ids cycle a '
1040
+ 'richer canonical pool for visual variation, fallback '
1041
+ 'cycles entrance_fade/entrance_wipe/entrance_fly/'
1042
+ 'entrance_zoom), "mixed" (canonical 16-preset entrance '
1043
+ 'pool), or "random" (the same entrance pool). Use '
1044
+ 'explicit keys for emphasis/path/exit. Legacy short '
1045
+ 'names remain accepted only for compatibility.')
1046
+ parser.add_argument('--animation-duration', type=positive_float, default=None,
1047
+ help='Per-element object-animation duration in seconds '
1048
+ '(default: 0.4; instantaneous native presets keep their '
1049
+ 'PowerPoint-authored duration)')
1050
+ parser.add_argument('--animation-trigger', type=str,
1051
+ choices=['on-click', 'with-previous', 'after-previous'],
1052
+ default=None,
1053
+ help='Per-element Start mode (matches PowerPoint Start dropdown): '
1054
+ '"on-click" (one click per element), '
1055
+ '"with-previous" (all start together on slide entry), '
1056
+ '"after-previous" (default, cascade after the previous element).')
1057
+ parser.add_argument('--animation-stagger', type=non_negative_float, default=None,
1058
+ help='Delay between elements in --animation-trigger=after-previous '
1059
+ '(seconds, default 0.5). Ignored in other modes.')
1060
+ animation_source = parser.add_mutually_exclusive_group()
1061
+ animation_source.add_argument(
1062
+ '--animation-config',
1063
+ type=str,
1064
+ default=None,
1065
+ help=(
1066
+ 'Per-slide/per-object animation config. While motion remains enabled, '
1067
+ 'recorded narration without an explicit config selects '
1068
+ '<project>/narration_animations.json when either animation sidecar '
1069
+ 'exists, or may inherit base postflight motion with '
1070
+ '--inherit-motion-from when neither exists. '
1071
+ 'Other exports default to <project>/animations.json when present.'
1072
+ ),
1073
+ )
1074
+ animation_source.add_argument(
1075
+ '--no-animations',
1076
+ action='store_true',
1077
+ help=(
1078
+ 'Export without object animations or page-transition motion. '
1079
+ 'Narration audio and slide advance timings are preserved.'
1080
+ ),
1081
+ )
1082
+
1083
+ notes_mode = parser.add_mutually_exclusive_group()
1084
+ notes_mode.add_argument(
1085
+ '--with-notes',
1086
+ action='store_true',
1087
+ help='Embed speaker notes. Required to opt in during Quick Generate.',
1088
+ )
1089
+ notes_mode.add_argument(
1090
+ '--no-notes',
1091
+ action='store_true',
1092
+ help='Disable speaker notes embedding (enabled by default outside Quick Generate)',
1093
+ )
1094
+ parser.add_argument('--narration-audio-dir', type=str, default=None,
1095
+ help='Low-level audio embedding from this directory; allows partial matches. '
1096
+ 'Default-flow exports get the _narrated name suffix.')
1097
+ parser.add_argument('--use-narration-timings', action='store_true',
1098
+ help='Set slide auto-advance timings from narration audio durations')
1099
+ parser.add_argument('--recorded-narration', type=str, default=None,
1100
+ help='Prepare PowerPoint recorded timings and narrations from a complete audio '
1101
+ 'directory. Default-flow exports get the _narrated name suffix '
1102
+ '(<project>_<ts>_narrated.pptx) to tell them apart from silent exports.')
1103
+ parser.add_argument('--narration-padding', type=non_negative_float, default=0.5,
1104
+ help='Seconds to add after each narration before auto-advance (default: 0.5)')
1105
+ parser.add_argument(
1106
+ '--narration-start-floor',
1107
+ type=non_negative_float,
1108
+ default=DEFAULT_NARRATION_START_FLOOR,
1109
+ help=(
1110
+ 'Minimum seconds from slide-transition start to narration start; '
1111
+ 'set 0 to start immediately after the transition '
1112
+ f'(default: {DEFAULT_NARRATION_START_FLOOR})'
1113
+ ),
1114
+ )
1115
+ parser.add_argument(
1116
+ '--inherit-motion-from',
1117
+ type=str,
1118
+ default=None,
1119
+ metavar='BASE_POSTFLIGHT_REPORT',
1120
+ help=(
1121
+ 'For recorded narration, inherit source-bound deck-wide transition, '
1122
+ 'animation, and advance settings from a successful base export report'
1123
+ ),
1124
+ )
1125
+
1126
+ raw_argv = list(argv) if argv is not None else sys.argv[1:]
1127
+ legacy_native_objects = '--native-objects' in raw_argv
1128
+ args = parser.parse_args(raw_argv)
1129
+ if legacy_native_objects:
1130
+ print(
1131
+ 'Warning: --native-objects is deprecated; use '
1132
+ '--native-charts-and-tables.',
1133
+ file=sys.stderr,
1134
+ )
1135
+ if args.animation_config is not None and not args.animation_config.strip():
1136
+ print(
1137
+ 'Error: --animation-config must be a non-empty file path',
1138
+ file=sys.stderr,
1139
+ )
1140
+ return 1
1141
+ if args.inherit_motion_from and not args.recorded_narration:
1142
+ print(
1143
+ 'Error: --inherit-motion-from requires --recorded-narration',
1144
+ file=sys.stderr,
1145
+ )
1146
+ return 1
1147
+ if args.inherit_motion_from and args.no_animations:
1148
+ print(
1149
+ 'Error: --inherit-motion-from cannot be combined with --no-animations',
1150
+ file=sys.stderr,
1151
+ )
1152
+ return 1
1153
+
1154
+ if args.quick_generate:
1155
+ conflicts: list[str] = []
1156
+ if args.source not in {None, 'output'}:
1157
+ conflicts.append('--source must be omitted or output')
1158
+ if args.pptx_structure not in {None, 'flat'}:
1159
+ conflicts.append('--pptx-structure must be omitted or flat')
1160
+ if conflicts:
1161
+ print(
1162
+ "Error: --quick-generate cannot be combined with: "
1163
+ + ", ".join(conflicts),
1164
+ file=sys.stderr,
1165
+ )
1166
+ return 1
1167
+ if not args.with_notes:
1168
+ args.no_notes = True
1169
+ args.pptx_structure = 'flat'
1170
+
1171
+ project_path = Path(args.project_path)
1172
+ if not project_path.exists():
1173
+ print(f"Error: Path does not exist: {project_path}")
1174
+ return 1
1175
+
1176
+ structure_lock = None
1177
+ native_structure_contract = None
1178
+ pptx_structure = args.pptx_structure
1179
+ lock_path = project_path / 'spec_lock.md'
1180
+ if not args.quick_generate and not lock_path.is_file():
1181
+ print(
1182
+ "Error: spec_lock.md is required for release SVG export",
1183
+ file=sys.stderr,
1184
+ )
1185
+ return 1
1186
+ declared_structure_mode = (
1187
+ None
1188
+ if args.quick_generate
1189
+ else _declared_pptx_structure_mode(project_path)
1190
+ )
1191
+ primary_language = None
1192
+ if not args.quick_generate:
1193
+ try:
1194
+ primary_language = _declared_primary_language(project_path)
1195
+ except LanguageTagError as exc:
1196
+ print(f"Error: {exc}", file=sys.stderr)
1197
+ return 1
1198
+ if primary_language is None:
1199
+ print(
1200
+ "Warning: spec_lock.md has no "
1201
+ "communication.primary_language; using legacy per-run "
1202
+ "language detection.",
1203
+ file=sys.stderr,
1204
+ )
1205
+ if pptx_structure in _LEGACY_PPTX_STRUCTURE_MODES:
1206
+ _print_structure_contract_error(pptx_structure)
1207
+ return 1
1208
+ if (
1209
+ declared_structure_mode is not None
1210
+ and declared_structure_mode not in _RELEASE_PPTX_STRUCTURE_MODES
1211
+ ):
1212
+ _print_structure_contract_error(declared_structure_mode)
1213
+ return 1
1214
+ if pptx_structure is None:
1215
+ if declared_structure_mode is None:
1216
+ pptx_structure = 'flat'
1217
+ print(
1218
+ "Warning: spec_lock.md has no pptx_structure.mode; using flat "
1219
+ "compatibility mode.",
1220
+ file=sys.stderr,
1221
+ )
1222
+ else:
1223
+ pptx_structure = declared_structure_mode
1224
+ elif pptx_structure == 'structured' and declared_structure_mode != 'structured':
1225
+ _print_structure_contract_error(
1226
+ declared_structure_mode,
1227
+ requested_mode='structured',
1228
+ )
1229
+ return 1
1230
+
1231
+ if (
1232
+ pptx_structure in _RELEASE_PPTX_STRUCTURE_MODES
1233
+ and declared_structure_mode == pptx_structure
1234
+ ):
1235
+ try:
1236
+ structure_lock = load_pptx_structure_lock(project_path)
1237
+ except TemplateStructureError as exc:
1238
+ print(f"Error: {exc}", file=sys.stderr)
1239
+ return 1
1240
+ if structure_lock is None or structure_lock.mode != pptx_structure:
1241
+ print(
1242
+ "Error: spec_lock.md must contain one complete "
1243
+ f"pptx_structure.mode: {pptx_structure} contract",
1244
+ file=sys.stderr,
1245
+ )
1246
+ return 1
1247
+
1248
+ theme_font_spec = None
1249
+ master_text_style_spec = None
1250
+ theme_color_spec = None
1251
+ if pptx_structure in {'flat', 'structured'} and not args.quick_generate:
1252
+ try:
1253
+ theme_font_spec = load_theme_font_spec(project_path)
1254
+ master_text_style_spec = load_master_text_style_spec(project_path)
1255
+ theme_color_spec = load_theme_color_spec(project_path)
1256
+ except (ThemeFontError, ThemeColorError) as exc:
1257
+ print(f"Error: {exc}", file=sys.stderr)
1258
+ return 1
1259
+ missing_theme_fields = []
1260
+ if theme_font_spec is None:
1261
+ missing_theme_fields.append(
1262
+ 'typography font_family/title_family/body_family'
1263
+ )
1264
+ if theme_color_spec is None:
1265
+ missing_theme_fields.append('colors')
1266
+ if missing_theme_fields:
1267
+ print(
1268
+ f"Error: {pptx_structure} export requires a current-project "
1269
+ "theme contract in spec_lock.md; missing: "
1270
+ + ", ".join(missing_theme_fields),
1271
+ file=sys.stderr,
1272
+ )
1273
+ return 1
1274
+ if args.image_max_dimension < 1:
1275
+ print("Error: --image-max-dimension must be >= 1", file=sys.stderr)
1276
+ return 1
1277
+ if args.image_scale < 1:
1278
+ print("Error: --image-scale must be >= 1", file=sys.stderr)
1279
+ return 1
1280
+ if not 1 <= args.image_quality <= 100:
1281
+ print("Error: --image-quality must be between 1 and 100", file=sys.stderr)
1282
+ return 1
1283
+
1284
+ try:
1285
+ project_info = get_project_info(str(project_path))
1286
+ project_name = project_info.get('name', project_path.name)
1287
+ except Exception:
1288
+ project_name = project_path.name
1289
+
1290
+ canvas_format = args.format
1291
+ expected_viewbox = (
1292
+ None
1293
+ if args.quick_generate
1294
+ else _declared_canvas_viewbox(project_path)
1295
+ )
1296
+ if expected_viewbox is None and not args.quick_generate:
1297
+ print(
1298
+ "Error: spec_lock.md must contain canvas.viewBox for release export",
1299
+ file=sys.stderr,
1300
+ )
1301
+ return 1
1302
+
1303
+ # Native DrawingML is the only PPTX product. A non-output ``-s`` remains a
1304
+ # diagnostic source override; default and explicit output use release rules.
1305
+ native_source = args.source or 'output'
1306
+ native_files, native_source_dir = find_svg_files(
1307
+ project_path,
1308
+ native_source,
1309
+ allow_fallback=args.source is None and not args.quick_generate,
1310
+ )
1311
+ ref_files = native_files
1312
+ if not native_files:
1313
+ if args.quick_generate:
1314
+ print(
1315
+ "Error: No SVG files found for --quick-generate in: "
1316
+ f"{project_path / 'svg_output'}",
1317
+ file=sys.stderr,
1318
+ )
1319
+ elif args.source is not None:
1320
+ requested_dir = project_path / native_source_dir
1321
+ print(
1322
+ "Error: No SVG files found in explicitly requested source: "
1323
+ f"{requested_dir}",
1324
+ file=sys.stderr,
1325
+ )
1326
+ else:
1327
+ print("Error: No SVG files found", file=sys.stderr)
1328
+ return 1
1329
+
1330
+ release_quality_gate = args.quick_generate or args.source in {None, 'output'}
1331
+ if release_quality_gate:
1332
+ source_fingerprint = _svg_source_fingerprint(native_files)
1333
+ quality = _quality_report_context(project_path, source_fingerprint)
1334
+ quality_gate, _ = _quality_gate_status(quality)
1335
+ if quality_gate != 'passed':
1336
+ export_mode = (
1337
+ '--quick-generate'
1338
+ if args.quick_generate
1339
+ else 'default release export'
1340
+ )
1341
+ print(
1342
+ f"Error: {export_mode} requires a passing final SVG quality "
1343
+ f"report for the current {native_source_dir}/; found "
1344
+ f"{quality_gate}.",
1345
+ file=sys.stderr,
1346
+ )
1347
+ quick_flag = ' --quick-generate' if args.quick_generate else ''
1348
+ print(
1349
+ "Run: python3 skills/ppt-master/scripts/svg_quality_checker.py "
1350
+ f'"{project_path}"{quick_flag} --stage final --json',
1351
+ file=sys.stderr,
1352
+ )
1353
+ return 1
1354
+
1355
+ # Compatibility kwargs remain until the builder's old baseline-specific
1356
+ # parameters are removed. Structured export never activates either path.
1357
+ structured_baseline = False
1358
+ baseline_layout_specs = None
1359
+ layout_definition_files: list[Path] = []
1360
+ if pptx_structure == 'structured' and structure_lock is not None:
1361
+ try:
1362
+ template_specs = parse_template_slides(native_files)
1363
+ except TemplateStructureError as exc:
1364
+ print(f"Error: {exc}", file=sys.stderr)
1365
+ return 1
1366
+ lock_errors = template_lock_errors(template_specs, structure_lock)
1367
+ if lock_errors:
1368
+ print("Error: PPTX structure does not match spec_lock.md:", file=sys.stderr)
1369
+ for message in lock_errors:
1370
+ print(f" {message}", file=sys.stderr)
1371
+ return 1
1372
+ try:
1373
+ layout_definition_files = structured_layout_definition_files(
1374
+ template_specs,
1375
+ structure_lock,
1376
+ )
1377
+ except TemplateStructureError as exc:
1378
+ print(f"Error: {exc}", file=sys.stderr)
1379
+ return 1
1380
+ prototype_errors = template_prototype_errors(
1381
+ template_specs,
1382
+ structure_lock,
1383
+ )
1384
+ if prototype_errors:
1385
+ print(
1386
+ "Error: structured template output does not match page_layouts "
1387
+ "prototypes:",
1388
+ file=sys.stderr,
1389
+ )
1390
+ for message in prototype_errors:
1391
+ print(f" {message}", file=sys.stderr)
1392
+ return 1
1393
+
1394
+ release_blocked = _release_blocked_graphics(native_files)
1395
+ if release_blocked:
1396
+ print(
1397
+ "Error: invalid PPTX graphic status metadata cannot enter an export. "
1398
+ "Correct the reported replacement/fallback/import-source attributes first.",
1399
+ file=sys.stderr,
1400
+ )
1401
+ for filename, marker_id, status in release_blocked[:20]:
1402
+ print(f" {filename}: {marker_id} ({status})", file=sys.stderr)
1403
+ if len(release_blocked) > 20:
1404
+ print(
1405
+ f" ... and {len(release_blocked) - 20} more",
1406
+ file=sys.stderr,
1407
+ )
1408
+ return 1
1409
+
1410
+ reconstruction_only = _reconstruction_only_graphics(native_files)
1411
+ if reconstruction_only:
1412
+ print(
1413
+ "Warning: reconstruction-only PPTX chart placeholder(s) have no baked "
1414
+ "preview. Default export keeps the placeholder; "
1415
+ "--native-charts-and-tables "
1416
+ "reconstructs entries that carry a valid active replacement marker.",
1417
+ file=sys.stderr,
1418
+ )
1419
+ for filename, marker_id, active_native in reconstruction_only[:20]:
1420
+ route = (
1421
+ "active native Chart/Table replacement"
1422
+ if active_native else "placeholder fallback"
1423
+ )
1424
+ print(f" {filename}: {marker_id} ({route})", file=sys.stderr)
1425
+ if len(reconstruction_only) > 20:
1426
+ print(
1427
+ f" ... and {len(reconstruction_only) - 20} more",
1428
+ file=sys.stderr,
1429
+ )
1430
+
1431
+ if args.native_objects:
1432
+ print(
1433
+ "Warning: --native-charts-and-tables replaces shape-based SVG fallbacks "
1434
+ "with PowerPoint Chart/Table objects. The native objects may normalize "
1435
+ "styling or omit SVG details that are not represented by marker metadata; "
1436
+ "use the default shape-based export when exact fallback artwork is required.",
1437
+ file=sys.stderr,
1438
+ )
1439
+ fallbacks = _native_object_fallbacks(native_files)
1440
+ if fallbacks:
1441
+ print(
1442
+ "Warning: --native-charts-and-tables found fallback-only PPTX objects; "
1443
+ "they will export through their SVG-derived DrawingML shapes instead "
1444
+ "of native Chart/Table objects.",
1445
+ file=sys.stderr,
1446
+ )
1447
+ for filename, marker_id, status in fallbacks[:20]:
1448
+ print(f" {filename}: {marker_id} ({status})", file=sys.stderr)
1449
+ if len(fallbacks) > 20:
1450
+ print(f" ... and {len(fallbacks) - 20} more", file=sys.stderr)
1451
+
1452
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1453
+
1454
+ backup_dir: Path | None = None
1455
+ if args.output:
1456
+ native_path = Path(args.output)
1457
+ else:
1458
+ exports_dir = project_path / "exports"
1459
+ exports_dir.mkdir(parents=True, exist_ok=True)
1460
+ # --native-charts-and-tables yields a materially different file (PowerPoint
1461
+ # Chart/Table objects instead of SVG-derived DrawingML shapes), so mark it
1462
+ # in the default-flow name to distinguish the two editable object models.
1463
+ # Narration flags likewise mark _narrated (audio embedded per slide +
1464
+ # auto-advance timings). Flag-driven (not content-sniffed) so the name
1465
+ # is predictable; an explicit -o keeps the caller's exact name untouched.
1466
+ native_tag = "_native_charts_tables" if args.native_objects else ""
1467
+ narrated_tag = "_narrated" if (args.recorded_narration or args.narration_audio_dir) else ""
1468
+ native_path = exports_dir / f"{project_name}_{timestamp}{native_tag}{narrated_tag}.pptx"
1469
+ # Preserve the authored svg_output/ beside every default-path export.
1470
+ backup_dir = project_path / "backup" / timestamp
1471
+
1472
+ native_path.parent.mkdir(parents=True, exist_ok=True)
1473
+
1474
+ verbose = not args.quiet
1475
+
1476
+ enable_notes = not args.no_notes
1477
+ notes: dict[str, str] = {}
1478
+ if enable_notes:
1479
+ try:
1480
+ notes = find_notes_files(project_path, ref_files)
1481
+ except NotesFileReadError as exc:
1482
+ print(f"Error: {exc}", file=sys.stderr)
1483
+ return 1
1484
+
1485
+ narration_audio: dict[str, Path] = {}
1486
+ narration_audio_dir_arg = args.recorded_narration or args.narration_audio_dir
1487
+ use_narration_timings = args.use_narration_timings or bool(args.recorded_narration)
1488
+ if narration_audio_dir_arg:
1489
+ narration_audio_dir = Path(narration_audio_dir_arg)
1490
+ if not narration_audio_dir.is_absolute():
1491
+ narration_audio_dir = project_path / narration_audio_dir
1492
+ if args.recorded_narration and not narration_audio_dir.is_dir():
1493
+ print(
1494
+ f"Error: Recorded narration directory does not exist: {narration_audio_dir}",
1495
+ file=sys.stderr,
1496
+ )
1497
+ return 1
1498
+ try:
1499
+ narration_audio = find_narration_files(
1500
+ narration_audio_dir,
1501
+ ref_files,
1502
+ )
1503
+ except ValueError as exc:
1504
+ print(f"Error: {exc}", file=sys.stderr)
1505
+ return 1
1506
+ if verbose:
1507
+ print(f" Narration audio directory: {narration_audio_dir}")
1508
+ print(f" Narration audio matched: {len(narration_audio)}/{len(ref_files)} slide(s)")
1509
+ if args.recorded_narration:
1510
+ missing = [path.stem for path in ref_files if path.stem not in narration_audio]
1511
+ if missing:
1512
+ print(
1513
+ "Error: Recorded narration requires one supported audio file per slide. "
1514
+ f"Matched {len(narration_audio)}/{len(ref_files)} slide(s). "
1515
+ f"Supported extensions: {', '.join(NARRATION_EXTENSIONS)}",
1516
+ file=sys.stderr,
1517
+ )
1518
+ for stem in missing[:20]:
1519
+ print(f" Missing audio for: {stem}", file=sys.stderr)
1520
+ if len(missing) > 20:
1521
+ print(f" ... and {len(missing) - 20} more", file=sys.stderr)
1522
+ return 1
1523
+ unreadable = [
1524
+ f"{stem}: {audio_path}"
1525
+ for stem, audio_path in sorted(narration_audio.items())
1526
+ if probe_audio_duration(audio_path) is None
1527
+ ]
1528
+ if unreadable:
1529
+ print(
1530
+ "Error: Recorded narration requires readable audio durations. "
1531
+ "Install ffprobe/ffmpeg or replace the listed audio files.",
1532
+ file=sys.stderr,
1533
+ )
1534
+ for item in unreadable[:20]:
1535
+ print(f" {item}", file=sys.stderr)
1536
+ if len(unreadable) > 20:
1537
+ print(f" ... and {len(unreadable) - 20} more", file=sys.stderr)
1538
+ return 1
1539
+ elif narration_audio_dir_arg and verbose:
1540
+ missing = [path.stem for path in ref_files if path.stem not in narration_audio]
1541
+ if missing:
1542
+ print(
1543
+ f" [warn] Narration audio matched {len(narration_audio)}/{len(ref_files)} slide(s); "
1544
+ "unmatched slides will export without audio."
1545
+ )
1546
+
1547
+ if args.no_animations and any(
1548
+ value is not None
1549
+ for value in (
1550
+ args.transition,
1551
+ args.transition_duration,
1552
+ args.animation,
1553
+ args.animation_duration,
1554
+ args.animation_trigger,
1555
+ args.animation_stagger,
1556
+ )
1557
+ ):
1558
+ print(
1559
+ "Error: --no-animations cannot be combined with transition or "
1560
+ "object-animation overrides.",
1561
+ file=sys.stderr,
1562
+ )
1563
+ return 1
1564
+
1565
+ effective_animation_config = _resolve_animation_config_source(
1566
+ project_path,
1567
+ args.animation_config,
1568
+ recorded_narration=bool(args.recorded_narration),
1569
+ no_animations=args.no_animations,
1570
+ )
1571
+
1572
+ if effective_animation_config:
1573
+ config_path = Path(effective_animation_config)
1574
+ if not config_path.is_absolute():
1575
+ config_path = project_path / config_path
1576
+ if not config_path.exists():
1577
+ print(
1578
+ f"Error: Animation config does not exist: {config_path}",
1579
+ file=sys.stderr,
1580
+ )
1581
+ if (
1582
+ args.recorded_narration
1583
+ and args.animation_config is None
1584
+ and config_path.name == 'narration_animations.json'
1585
+ ):
1586
+ print(
1587
+ "Generate it with narration_sync.py animations, select the "
1588
+ "canonical config with --animation-config animations.json, "
1589
+ "or disable animations with --no-animations.",
1590
+ file=sys.stderr,
1591
+ )
1592
+ return 1
1593
+
1594
+ try:
1595
+ animation_config = (
1596
+ None
1597
+ if args.no_animations
1598
+ else load_animation_config(
1599
+ project_path,
1600
+ effective_animation_config,
1601
+ )
1602
+ )
1603
+ except Exception as exc:
1604
+ print(f"Error: Failed to load animation config: {exc}", file=sys.stderr)
1605
+ return 1
1606
+ config_errors: list[str] = []
1607
+ if animation_config:
1608
+ config_errors.extend(validate_transition_config(animation_config))
1609
+ config_errors.extend(validate_animation_config_errors(animation_config))
1610
+ config_errors = list(dict.fromkeys(config_errors))
1611
+ if config_errors:
1612
+ for error in config_errors:
1613
+ print(f"Error: {error}", file=sys.stderr)
1614
+ return 1
1615
+
1616
+ config_warnings: list[str] = []
1617
+ if animation_config:
1618
+ reference_messages = validate_animation_config(
1619
+ project_path,
1620
+ animation_config,
1621
+ svg_files=native_files,
1622
+ )
1623
+ config_warnings = [
1624
+ message for message in reference_messages
1625
+ if ' has no id and cannot be customized in animations.json' in message
1626
+ ]
1627
+ reference_errors = [
1628
+ message for message in reference_messages
1629
+ if message not in config_warnings
1630
+ ]
1631
+ if reference_errors:
1632
+ for error in reference_errors:
1633
+ print(f"Error: {error}", file=sys.stderr)
1634
+ return 1
1635
+
1636
+ if animation_config and verbose:
1637
+ config_label = (
1638
+ effective_animation_config
1639
+ or str(project_path / 'animations.json')
1640
+ )
1641
+ print(f" Animation config: {config_label}")
1642
+ for warning in config_warnings:
1643
+ print(f" [warn] {warning}")
1644
+ elif args.no_animations and verbose:
1645
+ print(" Animations: disabled")
1646
+
1647
+ inherited_motion: dict[str, object] = {}
1648
+ if args.inherit_motion_from:
1649
+ try:
1650
+ inherited_motion = _load_deck_motion_handoff(
1651
+ project_path,
1652
+ args.inherit_motion_from,
1653
+ native_files,
1654
+ )
1655
+ except ValueError as exc:
1656
+ print(f"Error: {exc}", file=sys.stderr)
1657
+ return 1
1658
+ if verbose:
1659
+ print(f" Deck motion handoff: {args.inherit_motion_from}")
1660
+
1661
+ defaults = animation_config.get('defaults', {}) if animation_config else {}
1662
+ transition_defaults = _as_dict(defaults.get('transition')) if isinstance(defaults, dict) else {}
1663
+ animation_defaults = _as_dict(defaults.get('animation')) if isinstance(defaults, dict) else {}
1664
+ inherited_transition = _as_dict(inherited_motion.get('transition'))
1665
+ inherited_animation = _as_dict(inherited_motion.get('animation'))
1666
+ inherited_overrides = _as_dict(inherited_motion.get('cli_overrides'))
1667
+
1668
+ transition_arg = args.transition
1669
+ transition_effect = (
1670
+ 'none'
1671
+ if args.no_animations
1672
+ else (
1673
+ transition_arg
1674
+ if transition_arg is not None
1675
+ else (
1676
+ inherited_transition['effect']
1677
+ if 'effect' in inherited_transition
1678
+ else transition_defaults.get('effect', 'fade')
1679
+ )
1680
+ )
1681
+ )
1682
+ try:
1683
+ transition, transition_effect_options = (
1684
+ normalize_transition_effect_request(
1685
+ transition_effect,
1686
+ (
1687
+ None
1688
+ if transition_arg is not None or args.no_animations
1689
+ else (
1690
+ inherited_transition.get('effect_options')
1691
+ if 'effect' in inherited_transition
1692
+ else transition_defaults.get('effect_options')
1693
+ )
1694
+ ),
1695
+ )
1696
+ )
1697
+ transition_duration = validate_seconds(
1698
+ (
1699
+ args.transition_duration
1700
+ if args.transition_duration is not None
1701
+ else (
1702
+ inherited_transition['duration']
1703
+ if 'duration' in inherited_transition
1704
+ else transition_defaults.get('duration', 0.4)
1705
+ )
1706
+ ),
1707
+ "transition duration",
1708
+ allow_zero=transition is None,
1709
+ )
1710
+ auto_advance = (
1711
+ args.auto_advance
1712
+ if args.auto_advance is not None
1713
+ else (
1714
+ inherited_transition['auto_advance']
1715
+ if 'auto_advance' in inherited_transition
1716
+ else transition_defaults.get('auto_advance')
1717
+ )
1718
+ )
1719
+ if auto_advance is not None:
1720
+ auto_advance = validate_seconds(
1721
+ auto_advance,
1722
+ "transition auto_advance",
1723
+ allow_zero=True,
1724
+ )
1725
+ transition_sound = (
1726
+ None
1727
+ if args.no_animations
1728
+ else (
1729
+ inherited_transition['sound']
1730
+ if 'sound' in inherited_transition
1731
+ else transition_defaults.get('sound')
1732
+ )
1733
+ )
1734
+ if transition_sound is not None and not isinstance(
1735
+ transition_sound,
1736
+ str,
1737
+ ):
1738
+ raise ValueError(
1739
+ 'transition sound must be a project-relative .wav path or null'
1740
+ )
1741
+ except ValueError as exc:
1742
+ print(f"Error: {exc}", file=sys.stderr)
1743
+ return 1
1744
+
1745
+ try:
1746
+ animation_effect = (
1747
+ 'none'
1748
+ if args.no_animations
1749
+ else (
1750
+ args.animation
1751
+ if args.animation is not None
1752
+ # Per-element object motion is opt-in by default: unsolicited
1753
+ # auto-firing builds read as the "AI deck" tell. Page transitions
1754
+ # stay on; enable objects with -a or animations.json.
1755
+ else (
1756
+ inherited_animation['effect_request']
1757
+ if 'effect_request' in inherited_animation
1758
+ else animation_defaults.get('effect', 'none')
1759
+ )
1760
+ )
1761
+ )
1762
+ normalized_animation = normalize_animation_effect(animation_effect)
1763
+ # Keep the raw request for the builder so legacy directional aliases
1764
+ # can desugar into canonical effect_options instead of losing their
1765
+ # direction during early CLI normalization.
1766
+ animation = (
1767
+ None
1768
+ if normalized_animation is None
1769
+ else str(animation_effect)
1770
+ )
1771
+ animation_duration = validate_seconds(
1772
+ (
1773
+ args.animation_duration
1774
+ if args.animation_duration is not None
1775
+ else (
1776
+ inherited_animation['duration']
1777
+ if 'duration' in inherited_animation
1778
+ else animation_defaults.get('duration', 0.4)
1779
+ )
1780
+ ),
1781
+ "animation duration",
1782
+ allow_zero=False,
1783
+ )
1784
+ animation_seconds_to_milliseconds(
1785
+ animation_duration,
1786
+ "animation duration",
1787
+ allow_zero=False,
1788
+ )
1789
+ animation_stagger = validate_seconds(
1790
+ (
1791
+ args.animation_stagger
1792
+ if args.animation_stagger is not None
1793
+ else (
1794
+ inherited_animation['stagger']
1795
+ if 'stagger' in inherited_animation
1796
+ else animation_defaults.get('stagger', 0.5)
1797
+ )
1798
+ ),
1799
+ "animation stagger",
1800
+ allow_zero=True,
1801
+ )
1802
+ animation_seconds_to_milliseconds(
1803
+ animation_stagger,
1804
+ "animation stagger",
1805
+ allow_zero=True,
1806
+ )
1807
+ animation_trigger = normalize_animation_trigger(
1808
+ args.animation_trigger
1809
+ if args.animation_trigger is not None
1810
+ else (
1811
+ inherited_animation['trigger']
1812
+ if 'trigger' in inherited_animation
1813
+ else animation_defaults.get('trigger', 'after-previous')
1814
+ )
1815
+ )
1816
+ except ValueError as exc:
1817
+ print(f"Error: {exc}", file=sys.stderr)
1818
+ return 1
1819
+
1820
+ animation_cli_overrides = {
1821
+ 'transition': (
1822
+ args.transition is not None
1823
+ or inherited_overrides.get('transition') is True
1824
+ ),
1825
+ 'transition_duration': (
1826
+ args.transition_duration is not None
1827
+ or inherited_overrides.get('transition_duration') is True
1828
+ ),
1829
+ 'auto_advance': (
1830
+ args.auto_advance is not None
1831
+ or inherited_overrides.get('auto_advance') is True
1832
+ ),
1833
+ 'transition_sound': 'sound' in inherited_transition,
1834
+ 'animation': (
1835
+ args.animation is not None
1836
+ or inherited_overrides.get('animation') is True
1837
+ ),
1838
+ 'animation_duration': (
1839
+ args.animation_duration is not None
1840
+ or inherited_overrides.get('animation_duration') is True
1841
+ ),
1842
+ 'animation_stagger': (
1843
+ args.animation_stagger is not None
1844
+ or inherited_overrides.get('animation_stagger') is True
1845
+ ),
1846
+ 'animation_trigger': (
1847
+ args.animation_trigger is not None
1848
+ or inherited_overrides.get('animation_trigger') is True
1849
+ ),
1850
+ }
1851
+
1852
+ deck_motion: dict[str, object] = {
1853
+ 'transition': {
1854
+ 'effect': transition,
1855
+ 'effect_options': transition_effect_options,
1856
+ 'duration': transition_duration,
1857
+ 'auto_advance': auto_advance,
1858
+ 'sound': transition_sound,
1859
+ },
1860
+ 'animation': {
1861
+ 'effect': normalized_animation or 'none',
1862
+ 'effect_request': animation,
1863
+ 'duration': animation_duration,
1864
+ 'stagger': animation_stagger,
1865
+ 'trigger': animation_trigger,
1866
+ },
1867
+ 'cli_overrides': animation_cli_overrides,
1868
+ 'narration_timings': use_narration_timings,
1869
+ }
1870
+
1871
+ if args.recorded_narration:
1872
+ on_click_slides = _recorded_narration_on_click_slides(
1873
+ ref_files,
1874
+ animation_config,
1875
+ animation,
1876
+ animation_trigger,
1877
+ animation_cli_overrides,
1878
+ )
1879
+ if on_click_slides:
1880
+ print(
1881
+ "Error: --recorded-narration cannot be used with on-click object animations. "
1882
+ "Use --animation-trigger after-previous or --animation-trigger with-previous.",
1883
+ file=sys.stderr,
1884
+ )
1885
+ for slide in on_click_slides[:20]:
1886
+ print(f" on-click trigger: {slide}", file=sys.stderr)
1887
+ if len(on_click_slides) > 20:
1888
+ print(f" ... and {len(on_click_slides) - 20} more", file=sys.stderr)
1889
+ return 1
1890
+
1891
+ # Optional per-project document properties. Absent file → factual fields
1892
+ # are still stamped at export; only the authored fields stay blank.
1893
+ doc_metadata = None
1894
+ metadata_path = project_path / 'metadata.json'
1895
+ if metadata_path.is_file():
1896
+ try:
1897
+ loaded = json.loads(metadata_path.read_text(encoding='utf-8'))
1898
+ except (json.JSONDecodeError, OSError) as exc:
1899
+ print(f" [warn] metadata.json ignored ({exc})", file=sys.stderr)
1900
+ else:
1901
+ if isinstance(loaded, dict):
1902
+ doc_metadata = loaded
1903
+ if verbose:
1904
+ print(f" Document properties: metadata.json ({len(loaded)} field(s))")
1905
+ else:
1906
+ print(" [warn] metadata.json ignored (top level is not an object)", file=sys.stderr)
1907
+
1908
+ structure_name = project_name
1909
+ if isinstance(doc_metadata, dict):
1910
+ metadata_title = doc_metadata.get('title')
1911
+ if isinstance(metadata_title, str) and metadata_title.strip():
1912
+ structure_name = metadata_title
1913
+
1914
+ shared_kwargs = dict(
1915
+ canvas_format=canvas_format,
1916
+ expected_viewbox=expected_viewbox,
1917
+ doc_metadata=doc_metadata,
1918
+ structure_name=structure_name,
1919
+ verbose=verbose,
1920
+ transition=transition,
1921
+ transition_effect_options=transition_effect_options,
1922
+ transition_sound=transition_sound,
1923
+ transition_duration=transition_duration,
1924
+ auto_advance=auto_advance,
1925
+ notes=notes,
1926
+ enable_notes=enable_notes,
1927
+ animation=animation,
1928
+ animation_duration=animation_duration,
1929
+ animation_stagger=animation_stagger,
1930
+ animation_trigger=animation_trigger,
1931
+ animation_config=animation_config,
1932
+ animation_resource_root=project_path,
1933
+ animation_cli_overrides=animation_cli_overrides,
1934
+ narration_audio=narration_audio,
1935
+ use_narration_timings=use_narration_timings,
1936
+ narration_padding=args.narration_padding,
1937
+ narration_start_floor=args.narration_start_floor,
1938
+ text_flow=args.text_flow,
1939
+ image_optimize=not args.no_image_optimize,
1940
+ image_max_dimension=args.image_max_dimension,
1941
+ image_sizing=args.image_sizing,
1942
+ image_scale=args.image_scale,
1943
+ image_quality=args.image_quality,
1944
+ native_objects=args.native_objects,
1945
+ pptx_structure=pptx_structure,
1946
+ structured_baseline=structured_baseline,
1947
+ baseline_layout_specs=baseline_layout_specs,
1948
+ layout_definition_files=layout_definition_files,
1949
+ native_structure_contract=native_structure_contract,
1950
+ theme_font_spec=theme_font_spec,
1951
+ master_text_style_spec=master_text_style_spec,
1952
+ theme_color_spec=theme_color_spec,
1953
+ primary_language=primary_language,
1954
+ )
1955
+
1956
+ if verbose:
1957
+ print("PPT Master - SVG to native DrawingML PPTX Tool")
1958
+ print("=" * 50)
1959
+ print(f" Project path: {project_path}")
1960
+ print(f" SVG directory: {native_source_dir}")
1961
+ print(f" Output file: {native_path}")
1962
+ print()
1963
+
1964
+ conversion_trace_path: Path | None = None
1965
+ if args.conversion_trace is not None:
1966
+ if args.conversion_trace:
1967
+ requested_trace_path = Path(args.conversion_trace).expanduser()
1968
+ conversion_trace_path = (
1969
+ requested_trace_path
1970
+ if requested_trace_path.is_absolute()
1971
+ else project_path / requested_trace_path
1972
+ )
1973
+ else:
1974
+ conversion_trace_path = (
1975
+ project_path / 'validation' / f'{native_path.stem}.trace.json'
1976
+ )
1977
+ try:
1978
+ success = create_pptx_with_native_svg(
1979
+ output_path=native_path,
1980
+ use_native_shapes=True,
1981
+ svg_files=native_files,
1982
+ conversion_trace_path=conversion_trace_path,
1983
+ **shared_kwargs,
1984
+ )
1985
+ except (TemplateStructureError, ValueError) as exc:
1986
+ print(f"Error: {exc}", file=sys.stderr)
1987
+ return 1
1988
+
1989
+ # Archive svg_output/ once per default-flow export. This preserves the
1990
+ # authored SVG sources under backup/<ts>/svg_output/ for inspection and
1991
+ # deterministic re-export.
1992
+ backup_path: Path | None = None
1993
+ if success and backup_dir is not None:
1994
+ svg_output_src = project_path / "svg_output"
1995
+ if svg_output_src.is_dir():
1996
+ backup_dir.mkdir(parents=True, exist_ok=True)
1997
+ svg_output_dst = backup_dir / "svg_output"
1998
+ try:
1999
+ shutil.copytree(svg_output_src, svg_output_dst)
2000
+ except Exception as exc:
2001
+ if verbose:
2002
+ print(f" [warn] svg_output backup skipped: {exc}")
2003
+ else:
2004
+ backup_path = svg_output_dst
2005
+ if verbose:
2006
+ print(f" svg_output backup: {svg_output_dst}")
2007
+ payload_store_src = project_path / PAYLOAD_STORE_RELATIVE_PATH
2008
+ if payload_store_src.is_file():
2009
+ try:
2010
+ payload_store_dst = backup_dir / PAYLOAD_STORE_RELATIVE_PATH
2011
+ payload_store_dst.parent.mkdir(parents=True, exist_ok=True)
2012
+ shutil.copy2(payload_store_src, payload_store_dst)
2013
+ if verbose:
2014
+ print(f" native payload backup: {payload_store_dst}")
2015
+ except Exception as exc:
2016
+ if verbose:
2017
+ print(f" [warn] native payload backup skipped: {exc}")
2018
+ elif verbose:
2019
+ print(f" [info] svg_output/ not found, backup skipped")
2020
+
2021
+ if success:
2022
+ try:
2023
+ receipt = _write_postflight_report(
2024
+ output_path=native_path,
2025
+ project_path=project_path,
2026
+ svg_files=native_files,
2027
+ layout_definition_files=layout_definition_files,
2028
+ pptx_structure=pptx_structure,
2029
+ backup_path=backup_path,
2030
+ conversion_trace_path=conversion_trace_path,
2031
+ deck_motion=deck_motion,
2032
+ )
2033
+ except PptxPostflightValidationError as exc:
2034
+ print(
2035
+ "Error: generated PPTX failed postflight validation and must "
2036
+ f"not be used: {exc}",
2037
+ file=sys.stderr,
2038
+ )
2039
+ print(
2040
+ f" Invalid output remains at: {native_path}",
2041
+ file=sys.stderr,
2042
+ )
2043
+ return 1
2044
+ except OSError as exc:
2045
+ print(
2046
+ "Error: PPTX generation succeeded, but its postflight report "
2047
+ f"could not be written: {exc}",
2048
+ file=sys.stderr,
2049
+ )
2050
+ print(f" PPTX output remains at: {native_path}", file=sys.stderr)
2051
+ return 1
2052
+ if verbose:
2053
+ _print_postflight_receipt(receipt)
2054
+
2055
+ return 0 if success else 1
2056
+
2057
+
2058
+ if __name__ == '__main__':
2059
+ raise SystemExit(main())