dknowc-dsh 1.0.4 → 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 (158) hide show
  1. package/README.md +9 -4
  2. package/package.json +2 -2
  3. package/skills/dknowc-ppt-assistant/README.md +54 -0
  4. package/skills/dknowc-ppt-assistant/SKILL.md +151 -0
  5. package/skills/dknowc-ppt-assistant/THIRD_PARTY_NOTICES.md +36 -0
  6. package/skills/dknowc-ppt-assistant/official-docs/output/.gitkeep +0 -0
  7. package/skills/dknowc-ppt-assistant/official-docs/search-results/.gitkeep +0 -0
  8. package/skills/dknowc-ppt-assistant/projects/.gitkeep +0 -0
  9. package/skills/dknowc-ppt-assistant/references/content-pack.md +55 -0
  10. package/skills/dknowc-ppt-assistant/references/material_usage.md +51 -0
  11. package/skills/dknowc-ppt-assistant/references/sample_effect.html +89 -0
  12. package/skills/dknowc-ppt-assistant/references/sample_search_result.md +48 -0
  13. package/skills/dknowc-ppt-assistant/references/search_intro.md +79 -0
  14. package/skills/dknowc-ppt-assistant/references/style-presets.md +126 -0
  15. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +81 -0
  16. package/skills/dknowc-ppt-assistant/references/upstream-docs/svg-pipeline.md +842 -0
  17. package/skills/dknowc-ppt-assistant/references/upstream-example/01_cover.svg +28 -0
  18. package/skills/dknowc-ppt-assistant/references/upstream-example/02_quote.svg +38 -0
  19. package/skills/dknowc-ppt-assistant/references/upstream-example/03_origin.svg +96 -0
  20. package/skills/dknowc-ppt-assistant/references/upstream-example/README.md +15 -0
  21. package/skills/dknowc-ppt-assistant/references/upstream-example/design_spec.md +408 -0
  22. package/skills/dknowc-ppt-assistant/references/upstream-example/spec_lock.md +78 -0
  23. package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +279 -0
  24. package/skills/dknowc-ppt-assistant/scripts/check_release.py +106 -0
  25. package/skills/dknowc-ppt-assistant/scripts/compact_svg_coordinates.py +345 -0
  26. package/skills/dknowc-ppt-assistant/scripts/config.py +707 -0
  27. package/skills/dknowc-ppt-assistant/scripts/console_encoding.py +33 -0
  28. package/skills/dknowc-ppt-assistant/scripts/error_helper.py +434 -0
  29. package/skills/dknowc-ppt-assistant/scripts/finalize_svg.py +507 -0
  30. package/skills/dknowc-ppt-assistant/scripts/hyperlink_contract.py +399 -0
  31. package/skills/dknowc-ppt-assistant/scripts/initialize.py +182 -0
  32. package/skills/dknowc-ppt-assistant/scripts/language_tags.py +283 -0
  33. package/skills/dknowc-ppt-assistant/scripts/mcp_direct.py +158 -0
  34. package/skills/dknowc-ppt-assistant/scripts/native_payloads.py +655 -0
  35. package/skills/dknowc-ppt-assistant/scripts/pptx_animation_presets.json +3440 -0
  36. package/skills/dknowc-ppt-assistant/scripts/pptx_animations.py +3965 -0
  37. package/skills/dknowc-ppt-assistant/scripts/pptx_effects.py +143 -0
  38. package/skills/dknowc-ppt-assistant/scripts/pptx_opc_validation.py +346 -0
  39. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/__init__.py +130 -0
  40. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-APACHE-2.0.txt +202 -0
  41. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-OPEN-XML-SDK-MIT.txt +23 -0
  42. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/NOTICE.md +54 -0
  43. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeDefinitions.xml +19898 -0
  44. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeSemantics.json +1217 -0
  45. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/shape_type_values.txt +187 -0
  46. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/errors.py +39 -0
  47. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/formula.py +336 -0
  48. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/loader.py +364 -0
  49. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/models.py +201 -0
  50. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/registry.py +270 -0
  51. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantic_hash.py +456 -0
  52. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantics.py +543 -0
  53. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/xml_safety.py +21 -0
  54. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/__init__.py +21 -0
  55. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/animation_import.py +287 -0
  56. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chart_to_svg.py +2377 -0
  57. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chartex_to_svg.py +422 -0
  58. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/color_resolver.py +894 -0
  59. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/converter.py +1143 -0
  60. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/custgeom_to_svg.py +165 -0
  61. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/effect_to_svg.py +410 -0
  62. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/emu_units.py +258 -0
  63. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/fill_to_svg.py +816 -0
  64. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/formula_import.py +611 -0
  65. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/hyperlinks.py +93 -0
  66. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/import_diagnostics.py +37 -0
  67. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ln_to_svg.py +362 -0
  68. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/normalized_chart_svg.py +1217 -0
  69. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ooxml_loader.py +506 -0
  70. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/pic_to_svg.py +653 -0
  71. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_authoring.py +894 -0
  72. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_registry_to_svg.py +216 -0
  73. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_svg_markup.py +198 -0
  74. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/prstgeom_to_svg.py +162 -0
  75. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/shape_walker.py +556 -0
  76. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/slide_to_svg.py +2002 -0
  77. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/tbl_to_svg.py +1841 -0
  78. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/transition_import.py +201 -0
  79. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/txbody_to_svg.py +1433 -0
  80. package/skills/dknowc-ppt-assistant/scripts/pptx_transitions.py +3153 -0
  81. package/skills/dknowc-ppt-assistant/scripts/preset_shape_svg.py +450 -0
  82. package/skills/dknowc-ppt-assistant/scripts/project_utils.py +645 -0
  83. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +183 -0
  84. package/skills/dknowc-ppt-assistant/scripts/register_template.py +1327 -0
  85. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +1048 -0
  86. package/skills/dknowc-ppt-assistant/scripts/resource_paths.py +282 -0
  87. package/skills/dknowc-ppt-assistant/scripts/shape_boolean_svg.py +189 -0
  88. package/skills/dknowc-ppt-assistant/scripts/slide_roster.py +44 -0
  89. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/__init__.py +12 -0
  90. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/align_embed_images.py +672 -0
  91. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/crop_images.py +370 -0
  92. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_icons.py +564 -0
  93. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_images.py +288 -0
  94. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/fix_image_aspect.py +389 -0
  95. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/flatten_tspan.py +948 -0
  96. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/svg_rect_to_path.py +346 -0
  97. package/skills/dknowc-ppt-assistant/scripts/svg_quality/__init__.py +15 -0
  98. package/skills/dknowc-ppt-assistant/scripts/svg_quality/checker.py +7791 -0
  99. package/skills/dknowc-ppt-assistant/scripts/svg_quality/cli.py +193 -0
  100. package/skills/dknowc-ppt-assistant/scripts/svg_quality/svg_contracts.py +1121 -0
  101. package/skills/dknowc-ppt-assistant/scripts/svg_quality/xml_support.py +35 -0
  102. package/skills/dknowc-ppt-assistant/scripts/svg_quality_checker.py +59 -0
  103. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/__init__.py +37 -0
  104. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/animation_config.py +1622 -0
  105. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/canvas_contract.py +226 -0
  106. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/__init__.py +1 -0
  107. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/context.py +291 -0
  108. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/converter.py +1980 -0
  109. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/elements.py +5272 -0
  110. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/hyperlinks.py +162 -0
  111. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/paths.py +847 -0
  112. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/styles.py +752 -0
  113. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/text_properties.py +796 -0
  114. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_colors.py +283 -0
  115. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_fonts.py +330 -0
  116. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/utils.py +3555 -0
  117. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/geometry_properties.py +140 -0
  118. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/__init__.py +356 -0
  119. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_data.py +1449 -0
  120. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_style.py +886 -0
  121. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_xml.py +1495 -0
  122. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chartex.py +272 -0
  123. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/fallback_hash.py +161 -0
  124. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula.py +243 -0
  125. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_ast.py +592 -0
  126. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_compiler.py +96 -0
  127. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_omml.py +1049 -0
  128. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_parser.py +2181 -0
  129. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_profile.py +739 -0
  130. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_run_properties.py +234 -0
  131. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/inline_formula.py +311 -0
  132. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_attributes.py +182 -0
  133. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_common.py +806 -0
  134. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_status.py +190 -0
  135. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/table.py +1113 -0
  136. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/workbook.py +216 -0
  137. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/__init__.py +1 -0
  138. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/builder.py +6273 -0
  139. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/cli.py +2059 -0
  140. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/dimensions.py +189 -0
  141. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/discovery.py +120 -0
  142. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/media.py +160 -0
  143. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/narration.py +696 -0
  144. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/notes.py +336 -0
  145. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/slide_xml.py +138 -0
  146. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_structure.py +3457 -0
  147. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_validation.py +1536 -0
  148. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/semantic_markers.py +240 -0
  149. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/shape_boolean.py +1355 -0
  150. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/text_outline.py +1121 -0
  151. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/tspan_flattener.py +64 -0
  152. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/use_expander.py +577 -0
  153. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx.py +21 -0
  154. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +336 -0
  155. package/skills/dknowc-ppt-assistant/scripts/update_spec.py +404 -0
  156. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +142 -0
  157. package/skills/dknowc-ppt-assistant/workflows/routing.md +38 -0
  158. package/src/index.js +7 -2
@@ -0,0 +1,2002 @@
1
+ """Per-slide composition: dispatches every ShapeNode through the right
2
+ converter, accumulates <defs>, and produces one final SVG string.
3
+
4
+ The output structure mirrors what svg_to_pptx expects so the deck can be
5
+ round-tripped:
6
+ <svg viewBox="0 0 W H">
7
+ <defs>
8
+ <linearGradient id=.../>
9
+ <marker id=.../>
10
+ <filter id=.../>
11
+ </defs>
12
+ <!-- background -->
13
+ <rect ... /> (slide background, if any)
14
+ <g id="shape-1">...</g>
15
+ <g id="shape-2">...</g>
16
+ ...
17
+ </svg>
18
+
19
+ Each top-level <g> wraps one shape and is treated by svg_to_pptx as an
20
+ animation anchor.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import base64
26
+ import copy
27
+ import hashlib
28
+ import json
29
+ from dataclasses import dataclass, field
30
+ from xml.etree import ElementTree as ET
31
+
32
+ from pptx_shapes import (
33
+ CONNECTOR_PRESET_TYPES,
34
+ NATIVE_FALLBACK_SHA256_ATTR,
35
+ has_relationship_attributes,
36
+ svg_native_fallback_markup_fingerprint,
37
+ svg_text_fingerprint,
38
+ )
39
+ from pptx_effects import (
40
+ EFFECT_REASON_ATTR,
41
+ EFFECT_STATUS_ATTR,
42
+ txbody_has_run_effects,
43
+ unsupported_effect_metadata,
44
+ )
45
+ from hyperlink_contract import SHAPE_HYPERLINK_ATTR
46
+
47
+ from .color_resolver import ColorPalette, find_color_elem, resolve_color
48
+ from .chart_to_svg import CHART_URI, CHARTEX_URI, extract_native_chart_payload
49
+ from .custgeom_to_svg import convert_custom_geom
50
+ from .effect_to_svg import (
51
+ EffectResult,
52
+ convert_effects,
53
+ unsupported_target_effect_metadata,
54
+ )
55
+ from .emu_units import NS, Xfrm, fmt_num, format_canvas_px_from_emu
56
+ from .fill_to_svg import FillResult, resolve_fill
57
+ from .formula_import import (
58
+ A14_NS,
59
+ FormulaImport,
60
+ FormulaImportError,
61
+ import_formula,
62
+ opaque_formula_preview,
63
+ )
64
+ from .import_diagnostics import (
65
+ ImportDiagnostic,
66
+ append_diagnostic,
67
+ )
68
+ from .hyperlinks import resolve_click_hyperlink
69
+ from .ln_to_svg import StrokeResult, resolve_stroke
70
+ from .ooxml_loader import (
71
+ OoxmlPackage,
72
+ PartRef,
73
+ SlideRef,
74
+ inherited_shape_visibility,
75
+ )
76
+ from .pic_to_svg import (
77
+ MediaResolutionError,
78
+ PictureResult,
79
+ convert_blip_fill,
80
+ convert_picture,
81
+ )
82
+ from .prstgeom_to_svg import GeomResult, convert_prst_geom
83
+ from .preset_svg_markup import serialize_preset_layers
84
+ from .shape_walker import (
85
+ CONNECTOR, GRAPHIC, GROUP, PICTURE, SHAPE,
86
+ ShapeNode, get_background, walk_sp_tree,
87
+ )
88
+ from .tbl_to_svg import convert_tbl
89
+ from .txbody_to_svg import (
90
+ TextResult,
91
+ convert_txbody,
92
+ convert_vertical_txbody,
93
+ is_vertical_txbody,
94
+ DEFAULT_FONT_SIZE_PX,
95
+ )
96
+
97
+
98
+ # ---------------------------------------------------------------------------
99
+ # AssemblyContext
100
+ # ---------------------------------------------------------------------------
101
+
102
+ @dataclass
103
+ class AssemblyContext:
104
+ """Per-slide accumulator for unique IDs + media + defs."""
105
+
106
+ palette: ColorPalette | None
107
+ pkg: OoxmlPackage
108
+ slide_part: PartRef
109
+ slide_number: int | None = None
110
+ theme_fonts: dict[str, str] = field(default_factory=dict)
111
+ media_subdir: str = "assets"
112
+ embed_images: bool = False
113
+ keep_hidden: bool = False
114
+ strict: bool = False
115
+ group_id_prefix: str = ""
116
+ render_graphic_previews: bool = True
117
+ asset_name_map: dict[str, str] = field(default_factory=dict)
118
+ diagnostics: list[ImportDiagnostic] = field(default_factory=list)
119
+ source_slide_index: int | None = None
120
+ current_node: ShapeNode | None = None
121
+
122
+ # Sequence counters (single-element lists so handlers can mutate)
123
+ grad_seq: list[int] = field(default_factory=lambda: [0])
124
+ marker_seq: list[int] = field(default_factory=lambda: [0])
125
+ filter_seq: list[int] = field(default_factory=lambda: [0])
126
+ shape_seq: list[int] = field(default_factory=lambda: [0])
127
+ clip_seq: list[int] = field(default_factory=lambda: [0])
128
+
129
+ # Accumulated outputs
130
+ defs: list[str] = field(default_factory=list)
131
+ media: dict[str, bytes] = field(default_factory=dict)
132
+
133
+ def bind_palette(self) -> None:
134
+ """Route tolerant color diagnostics through the current object context."""
135
+ if self.palette is None:
136
+ return
137
+ self.palette.strict = self.strict
138
+ self.palette.diagnostic_sink = self._diagnose_color
139
+
140
+ def diagnose(
141
+ self,
142
+ code: str,
143
+ message: str,
144
+ fallback: str,
145
+ *,
146
+ node: ShapeNode | None = None,
147
+ ) -> None:
148
+ """Record one recoverable source-contract violation."""
149
+ source_node = node or self.current_node
150
+ append_diagnostic(
151
+ self.diagnostics,
152
+ ImportDiagnostic(
153
+ code=code,
154
+ message=message,
155
+ fallback=fallback,
156
+ part_path=self.slide_part.path,
157
+ slide_index=self.source_slide_index,
158
+ shape_id=source_node.spid if source_node is not None else "",
159
+ shape_name=source_node.name if source_node is not None else "",
160
+ shape_kind=source_node.kind if source_node is not None else "",
161
+ ),
162
+ )
163
+
164
+ def _diagnose_color(self, code: str, message: str, fallback: str) -> None:
165
+ self.diagnose(code, message, fallback)
166
+
167
+
168
+ def _diagnose_picture_result(
169
+ ctx: AssemblyContext,
170
+ result: PictureResult,
171
+ ) -> None:
172
+ """Project recoverable picture losses into the import report."""
173
+ for diagnostic in result.diagnostics:
174
+ ctx.diagnose(
175
+ diagnostic.code,
176
+ diagnostic.message,
177
+ diagnostic.fallback,
178
+ )
179
+
180
+
181
+ def _resolve_svg_hyperlink(
182
+ ctx: AssemblyContext,
183
+ relationship_id: str,
184
+ action: str,
185
+ ) -> str | None:
186
+ """Resolve one source-part click link or record its explicit loss."""
187
+ resolution = resolve_click_hyperlink(
188
+ ctx.slide_part.rels,
189
+ relationship_id,
190
+ action,
191
+ slide_index_by_part=ctx.pkg.slide_index_by_part,
192
+ )
193
+ if resolution.error is None:
194
+ return resolution.href
195
+ if ctx.strict:
196
+ raise ValueError(resolution.error)
197
+ ctx.diagnose(
198
+ "hyperlink-omitted",
199
+ resolution.error,
200
+ "retain the object and omit only its unsupported click link",
201
+ )
202
+ return None
203
+
204
+
205
+ # ---------------------------------------------------------------------------
206
+ # Public entry
207
+ # ---------------------------------------------------------------------------
208
+
209
+ def assemble_slide(
210
+ pkg: OoxmlPackage,
211
+ slide: SlideRef,
212
+ palette: ColorPalette | None,
213
+ *,
214
+ theme_fonts: dict[str, str] | None = None,
215
+ media_subdir: str = "assets",
216
+ embed_images: bool = False,
217
+ keep_hidden: bool = False,
218
+ inheritance_mode: str = "flat",
219
+ asset_name_map: dict[str, str] | None = None,
220
+ strict: bool = False,
221
+ diagnostics: list[ImportDiagnostic] | None = None,
222
+ ) -> tuple[str, dict[str, bytes]]:
223
+ """Convert one slide to a complete SVG string + media files map.
224
+
225
+ inheritance_mode controls how master/layout shapes are rendered:
226
+ - "flat" (default): emit the effective visible Master/Layout
227
+ non-placeholder shapes inline inside the slide SVG, honoring both
228
+ source ``showMasterSp`` flags. This view is used for round-trip
229
+ fidelity with svg_to_pptx.
230
+ - "layered": skip inherited shapes entirely. The slide SVG contains
231
+ only its own shapes. Callers (e.g. /create-template's PPTX import)
232
+ render master/layout once each as separate SVGs and record the
233
+ inheritance graph in inheritance.json.
234
+ """
235
+ ctx = AssemblyContext(
236
+ palette=palette,
237
+ pkg=pkg,
238
+ slide_part=slide.part,
239
+ slide_number=pkg.first_slide_number + slide.index - 1,
240
+ theme_fonts=theme_fonts or {},
241
+ media_subdir=media_subdir,
242
+ embed_images=embed_images,
243
+ keep_hidden=keep_hidden,
244
+ strict=strict,
245
+ render_graphic_previews=(inheritance_mode == "flat"),
246
+ asset_name_map=asset_name_map or {},
247
+ diagnostics=diagnostics if diagnostics is not None else [],
248
+ source_slide_index=slide.index,
249
+ )
250
+ ctx.bind_palette()
251
+
252
+ canvas_w, canvas_h = pkg.slide_size_px
253
+ canvas_w_token, canvas_h_token = (
254
+ format_canvas_px_from_emu(value) for value in pkg.slide_size_emu
255
+ )
256
+
257
+ # Background (cSld/bg) — emit as the first body element.
258
+ body_parts: list[str] = []
259
+ try:
260
+ bg_xml = (
261
+ _emit_background(slide, ctx, canvas_w, canvas_h)
262
+ if inheritance_mode == "flat"
263
+ else _emit_part_background(
264
+ SlideRef(index=slide.index, part=slide.part, layout=None, master=slide.master),
265
+ ctx, canvas_w, canvas_h,
266
+ )
267
+ )
268
+ except (ValueError, MediaResolutionError) as exc:
269
+ if strict:
270
+ raise
271
+ ctx.diagnose(
272
+ "background-omitted",
273
+ str(exc),
274
+ "omit the unsupported background and continue the slide",
275
+ )
276
+ bg_xml = ""
277
+ if bg_xml:
278
+ body_parts.append(bg_xml)
279
+
280
+ if inheritance_mode == "flat":
281
+ # Inherited layout/master shapes render behind slide-local shapes. Skip
282
+ # placeholders; they define editable regions, not visible background.
283
+ body_parts.extend(_emit_inherited_shapes(slide, ctx))
284
+ elif inheritance_mode != "layered":
285
+ raise ValueError(
286
+ f"inheritance_mode must be 'flat' or 'layered', got {inheritance_mode!r}"
287
+ )
288
+
289
+ # Walk shapes — placeholders without their own xfrm inherit geometry from
290
+ # layout, then master.
291
+ nodes = walk_sp_tree(
292
+ slide.part.xml,
293
+ layout_xml=slide.layout.xml if slide.layout else None,
294
+ master_xml=slide.master.xml if slide.master else None,
295
+ )
296
+ for node in nodes:
297
+ chunk = _convert_node(node, ctx, top_level=True)
298
+ if chunk:
299
+ body_parts.append(chunk)
300
+
301
+ # Compose final SVG
302
+ defs_xml = "".join(ctx.defs) if ctx.defs else ""
303
+ defs_block = f"<defs>{defs_xml}</defs>" if defs_xml else ""
304
+
305
+ svg = (
306
+ f'<svg xmlns="http://www.w3.org/2000/svg" '
307
+ f'xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" '
308
+ f'width="{canvas_w_token}" height="{canvas_h_token}" '
309
+ f'viewBox="0 0 {canvas_w_token} {canvas_h_token}">'
310
+ f"{defs_block}"
311
+ + "\n".join(body_parts)
312
+ + "</svg>"
313
+ )
314
+ return svg, ctx.media
315
+
316
+
317
+ def assemble_part_solo(
318
+ pkg: OoxmlPackage,
319
+ part: PartRef,
320
+ palette: ColorPalette | None,
321
+ *,
322
+ role: str,
323
+ parent_master: PartRef | None = None,
324
+ theme_fonts: dict[str, str] | None = None,
325
+ media_subdir: str = "assets",
326
+ embed_images: bool = False,
327
+ keep_hidden: bool = False,
328
+ asset_name_map: dict[str, str] | None = None,
329
+ strict: bool = False,
330
+ diagnostics: list[ImportDiagnostic] | None = None,
331
+ ) -> tuple[str, dict[str, bytes]]:
332
+ """Render a single slideMaster or slideLayout part as a standalone SVG.
333
+
334
+ Used by the layered export path. Skips placeholders the same way
335
+ `_emit_inherited_shapes` does, so the output represents the part's
336
+ decorative / structural shapes only — what the part *contributes* to its
337
+ descendants. The first ancestor's background (if any) is emitted as the
338
+ first body element so the output reads like a real slide.
339
+
340
+ Args:
341
+ role: 'master' or 'layout'. Used as the group_id_prefix to keep ids
342
+ unique when the workspace inlines multiple parts in a viewer.
343
+ parent_master: when ``role == "layout"``, pass the parent slide
344
+ master so theme-style background fills (``<p:bgRef idx=...>``)
345
+ can resolve via the theme attached to that master. For
346
+ ``role == "master"`` the master is its own parent and this
347
+ argument is ignored.
348
+ """
349
+ if role not in {"master", "layout"}:
350
+ raise ValueError(f"role must be 'master' or 'layout', got {role!r}")
351
+
352
+ ctx = AssemblyContext(
353
+ palette=palette,
354
+ pkg=pkg,
355
+ slide_part=part,
356
+ theme_fonts=theme_fonts or {},
357
+ media_subdir=media_subdir,
358
+ embed_images=embed_images,
359
+ keep_hidden=keep_hidden,
360
+ strict=strict,
361
+ group_id_prefix=f"{role}-",
362
+ render_graphic_previews=False,
363
+ asset_name_map=asset_name_map or {},
364
+ diagnostics=diagnostics if diagnostics is not None else [],
365
+ )
366
+ ctx.bind_palette()
367
+
368
+ canvas_w, canvas_h = pkg.slide_size_px
369
+ canvas_w_token, canvas_h_token = (
370
+ format_canvas_px_from_emu(value) for value in pkg.slide_size_emu
371
+ )
372
+
373
+ body_parts: list[str] = []
374
+
375
+ # Layered semantics: each part's standalone SVG must contain only that
376
+ # part's own contribution. The master gets its own bg, the layout gets
377
+ # its own bg only if it overrides the master's, and consumers re-stack
378
+ # the layers when they need a flat view. We therefore inspect <p:bg> on
379
+ # this part alone — never inherited from above. Theme-style fills
380
+ # (<p:bgRef idx=...>) still need the parent master's <a:fmtScheme> to
381
+ # resolve, hence the SlideRef.master plumbing below.
382
+ if role == "master":
383
+ master_for_theme: PartRef | None = part
384
+ else:
385
+ master_for_theme = parent_master
386
+ fake_slide = SlideRef(
387
+ index=0,
388
+ part=part,
389
+ layout=None,
390
+ master=master_for_theme,
391
+ )
392
+ try:
393
+ bg_xml = _emit_part_background(fake_slide, ctx, canvas_w, canvas_h)
394
+ except (ValueError, MediaResolutionError) as exc:
395
+ if strict:
396
+ raise
397
+ ctx.diagnose(
398
+ "background-omitted",
399
+ str(exc),
400
+ "omit the unsupported background and continue the part",
401
+ )
402
+ bg_xml = ""
403
+ if bg_xml:
404
+ body_parts.append(bg_xml)
405
+
406
+ # Walk shapes. Layered master/layout SVGs retain each placeholder's source
407
+ # appearance so mirror materialization can recover its editable decoration.
408
+ for node in walk_sp_tree(part.xml):
409
+ if _is_placeholder_node(node):
410
+ chunk = _convert_placeholder_guide(node, ctx, top_level=True)
411
+ else:
412
+ chunk = _convert_node(node, ctx, top_level=True)
413
+ if chunk:
414
+ body_parts.append(chunk)
415
+
416
+ defs_xml = "".join(ctx.defs) if ctx.defs else ""
417
+ defs_block = f"<defs>{defs_xml}</defs>" if defs_xml else ""
418
+
419
+ svg = (
420
+ f'<svg xmlns="http://www.w3.org/2000/svg" '
421
+ f'xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" '
422
+ f'width="{canvas_w_token}" height="{canvas_h_token}" '
423
+ f'viewBox="0 0 {canvas_w_token} {canvas_h_token}">'
424
+ f"{defs_block}"
425
+ + "\n".join(body_parts)
426
+ + "</svg>"
427
+ )
428
+ return svg, ctx.media
429
+
430
+
431
+ # ---------------------------------------------------------------------------
432
+ # Per-node dispatch
433
+ # ---------------------------------------------------------------------------
434
+
435
+ def _convert_node(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
436
+ previous_node = ctx.current_node
437
+ ctx.current_node = node
438
+ try:
439
+ if node.hidden and not ctx.keep_hidden:
440
+ return ""
441
+ if node.kind == SHAPE:
442
+ return _convert_shape(node, ctx, top_level=top_level)
443
+ if node.kind == PICTURE:
444
+ return _convert_picture(node, ctx, top_level=top_level)
445
+ if node.kind == CONNECTOR:
446
+ return _convert_connector(node, ctx, top_level=top_level)
447
+ if node.kind == GROUP:
448
+ return _convert_group(node, ctx, top_level=top_level)
449
+ if node.kind == GRAPHIC:
450
+ return _convert_graphic_fallback(node, ctx, top_level=top_level)
451
+ return ""
452
+ except ValueError as exc:
453
+ if ctx.strict:
454
+ raise
455
+ ctx.diagnose(
456
+ "object-replaced",
457
+ str(exc),
458
+ "replace only this object with a visible placeholder",
459
+ node=node,
460
+ )
461
+ return _fallback_node_svg(node, ctx, top_level=top_level)
462
+ finally:
463
+ ctx.current_node = previous_node
464
+
465
+
466
+ def _fallback_node_svg(
467
+ node: ShapeNode,
468
+ ctx: AssemblyContext,
469
+ *,
470
+ top_level: bool,
471
+ ) -> str:
472
+ """Keep one unsupported source object visible without aborting its deck."""
473
+ if node.xfrm.w <= 0 or node.xfrm.h <= 0:
474
+ return ""
475
+ x = fmt_num(node.xfrm.x)
476
+ y = fmt_num(node.xfrm.y)
477
+ width = fmt_num(node.xfrm.w)
478
+ height = fmt_num(node.xfrm.h)
479
+ label = _xml_escape(node.name or f"Unsupported {node.kind}")
480
+ inner = (
481
+ f'<rect x="{x}" y="{y}" width="{width}" height="{height}" '
482
+ 'fill="#F8FAFC" fill-opacity="0.72" stroke="#DC2626" '
483
+ 'stroke-width="1" stroke-dasharray="6 4"/>'
484
+ f'<text x="{fmt_num(node.xfrm.x + 8)}" '
485
+ f'y="{fmt_num(node.xfrm.y + min(18, node.xfrm.h / 2))}" '
486
+ f'font-size="12" fill="#991B1B">{label}</text>'
487
+ )
488
+ return _wrap_shape_group(inner, node, ctx, top_level=top_level)
489
+
490
+
491
+ # ---------------------------------------------------------------------------
492
+ # Shape (<p:sp>)
493
+ # ---------------------------------------------------------------------------
494
+
495
+ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
496
+ sp_pr = node.xml.find("p:spPr", NS)
497
+
498
+ # Check for blipFill (image-filled shape, e.g. Canva exports where images
499
+ # are expressed as <p:sp> + <a:blipFill> rather than <p:pic>).
500
+ geom = _resolve_geometry(node, sp_pr)
501
+
502
+ blip_fill_elem = sp_pr.find("a:blipFill", NS) if sp_pr is not None else None
503
+ blip_image = ""
504
+ if blip_fill_elem is not None:
505
+ try:
506
+ blip_result = convert_blip_fill(
507
+ blip_fill_elem, node.xfrm, ctx.slide_part, ctx.pkg,
508
+ media_subdir=ctx.media_subdir,
509
+ embed_inline=ctx.embed_images,
510
+ asset_name_map=ctx.asset_name_map,
511
+ strict=ctx.strict,
512
+ )
513
+ except (ValueError, MediaResolutionError) as exc:
514
+ if ctx.strict:
515
+ raise
516
+ ctx.diagnose(
517
+ "image-fill-omitted",
518
+ str(exc),
519
+ "omit the image fill and retain shape geometry/text",
520
+ )
521
+ else:
522
+ _diagnose_picture_result(ctx, blip_result)
523
+ if blip_result.svg:
524
+ blip_image = _clip_blip_image(blip_result.svg, geom, ctx)
525
+ ctx.media.update(blip_result.media)
526
+
527
+ # Text body (a:txBody)
528
+ source_tx_body = node.xml.find("p:txBody", NS)
529
+ tx_body = _effective_placeholder_tx_body(
530
+ source_tx_body,
531
+ node.inherited_body_properties,
532
+ )
533
+ is_vertical = is_vertical_txbody(tx_body, node.xfrm)
534
+ block_formula = _block_formula_zone(tx_body)
535
+ block_formula_failed = False
536
+ if block_formula is not None and not is_vertical:
537
+ try:
538
+ carrier_error = _block_formula_carrier_error(
539
+ node,
540
+ top_level=top_level,
541
+ )
542
+ if carrier_error is not None:
543
+ raise FormulaImportError(carrier_error)
544
+ imported_formula = import_formula(block_formula, display=True)
545
+ except FormulaImportError as exc:
546
+ _diagnose_formula_fallback(ctx, exc)
547
+ block_formula_failed = True
548
+ else:
549
+ return _render_block_formula(
550
+ node,
551
+ ctx,
552
+ imported_formula,
553
+ top_level=top_level,
554
+ )
555
+ inline_formula_resolver = _prepare_inline_formula_resolver(
556
+ tx_body,
557
+ ctx,
558
+ allow_native=not is_vertical,
559
+ force_opaque=block_formula_failed,
560
+ )
561
+ local_has_run_effects = txbody_has_run_effects(source_tx_body)
562
+ inherited_has_run_effects = txbody_has_run_effects(
563
+ *node.inherited_lst_styles
564
+ )
565
+ has_run_effects = local_has_run_effects or inherited_has_run_effects
566
+ if geom is not None and has_run_effects:
567
+ if is_vertical:
568
+ geom.attrs.update(unsupported_effect_metadata(
569
+ "unsupported-run-effect-route:vertical-text"
570
+ ))
571
+ elif tx_body is not None and has_relationship_attributes(tx_body):
572
+ geom.attrs.update(unsupported_effect_metadata(
573
+ "unsupported-run-effect-route:relationship-bearing-text"
574
+ ))
575
+ elif inherited_has_run_effects:
576
+ geom.attrs.update(unsupported_effect_metadata(
577
+ "unsupported-run-effect-route:inherited-text-style"
578
+ ))
579
+
580
+ # Geometry (fill is "none" when blipFill is present, so only stroke draws)
581
+ geom_xml = _build_geometry_xml(node, sp_pr, ctx, geom=geom)
582
+
583
+ try:
584
+ text_default_fill = _resolve_text_style_default(node, ctx)
585
+ if tx_body is not None and is_vertical:
586
+ text_result = convert_vertical_txbody(
587
+ tx_body, node.xfrm, ctx.palette,
588
+ theme_fonts=ctx.theme_fonts,
589
+ slide_number=ctx.slide_number,
590
+ default_fill=text_default_fill,
591
+ default_font_size_px=DEFAULT_FONT_SIZE_PX,
592
+ fallback_lst_styles=node.inherited_lst_styles,
593
+ id_prefix=f"{ctx.group_id_prefix}txt",
594
+ id_seq=ctx.grad_seq,
595
+ hyperlink_resolver=lambda rid, action: _resolve_svg_hyperlink(
596
+ ctx,
597
+ rid,
598
+ action,
599
+ ),
600
+ inline_formula_resolver=inline_formula_resolver,
601
+ )
602
+ else:
603
+ text_result = convert_txbody(
604
+ tx_body, node.xfrm, ctx.palette,
605
+ theme_fonts=ctx.theme_fonts,
606
+ slide_number=ctx.slide_number,
607
+ default_fill=text_default_fill,
608
+ default_font_size_px=DEFAULT_FONT_SIZE_PX,
609
+ fallback_lst_styles=node.inherited_lst_styles,
610
+ id_prefix=f"{ctx.group_id_prefix}txt",
611
+ id_seq=ctx.grad_seq,
612
+ hyperlink_resolver=lambda rid, action: _resolve_svg_hyperlink(
613
+ ctx,
614
+ rid,
615
+ action,
616
+ ),
617
+ inline_formula_resolver=inline_formula_resolver,
618
+ ) if tx_body is not None else TextResult()
619
+ except ValueError as exc:
620
+ if ctx.strict:
621
+ raise
622
+ ctx.diagnose(
623
+ "text-omitted",
624
+ str(exc),
625
+ "omit this text body and retain the object's other visuals",
626
+ )
627
+ text_result = TextResult()
628
+ if text_result.defs:
629
+ ctx.defs.extend(text_result.defs)
630
+
631
+ if is_vertical:
632
+ # Vertical text: geometry + image in one group, text in separate group
633
+ geom_inner = (blip_image + "\n" + geom_xml) if blip_image else geom_xml
634
+ shape_xml = _wrap_shape_group(
635
+ geom_inner,
636
+ node,
637
+ ctx,
638
+ top_level=top_level,
639
+ extra_attrs=_geometry_group_attrs(geom),
640
+ )
641
+ if not text_result.svg:
642
+ return shape_xml
643
+ text_group = (
644
+ f'<g id="{ctx.group_id_prefix}shape-{node.spid or ctx.shape_seq[0]}-text"'
645
+ f' data-name="{_xml_escape(node.name)} text">\n'
646
+ f"{text_result.svg}\n</g>"
647
+ )
648
+ return f"{shape_xml}\n{text_group}"
649
+
650
+ # Normal: image (behind) + geometry (stroke) + text (top)
651
+ inner_parts = []
652
+ if blip_image:
653
+ inner_parts.append(blip_image)
654
+ if geom_xml:
655
+ inner_parts.append(geom_xml)
656
+ if (
657
+ source_tx_body is not None
658
+ and geom is not None
659
+ and not text_result.contains_inline_formula
660
+ ):
661
+ inner_parts.append(
662
+ _txbody_metadata(
663
+ source_tx_body,
664
+ text_result.svg,
665
+ )
666
+ )
667
+ if text_result.svg:
668
+ inner_parts.append(text_result.svg)
669
+ inner = "\n".join(inner_parts) if inner_parts else ""
670
+ return _wrap_shape_group(
671
+ inner,
672
+ node,
673
+ ctx,
674
+ top_level=top_level,
675
+ extra_attrs=_geometry_group_attrs(geom),
676
+ )
677
+
678
+
679
+ def _effective_placeholder_tx_body(
680
+ tx_body: ET.Element | None,
681
+ inherited_body_properties: tuple[ET.Element, ...],
682
+ ) -> ET.Element | None:
683
+ """Merge inherited placeholder bodyPr settings into one visible text body."""
684
+ if tx_body is None or not inherited_body_properties:
685
+ return tx_body
686
+ effective = copy.deepcopy(tx_body)
687
+ body_pr = effective.find("a:bodyPr", NS)
688
+ if body_pr is None:
689
+ body_pr = ET.Element(f"{{{NS['a']}}}bodyPr")
690
+ effective.insert(0, body_pr)
691
+
692
+ child_groups = (
693
+ {"prstTxWarp"},
694
+ {"noAutofit", "normAutofit", "spAutoFit"},
695
+ {"scene3d"},
696
+ {"sp3d"},
697
+ )
698
+ for inherited in inherited_body_properties:
699
+ for name, value in inherited.attrib.items():
700
+ body_pr.attrib.setdefault(name, value)
701
+ local_names = {
702
+ child.tag.rsplit("}", 1)[-1]
703
+ for child in body_pr
704
+ if isinstance(child.tag, str)
705
+ }
706
+ for group in child_groups:
707
+ if local_names & group:
708
+ continue
709
+ inherited_child = next(
710
+ (
711
+ child
712
+ for child in inherited
713
+ if isinstance(child.tag, str)
714
+ and child.tag.rsplit("}", 1)[-1] in group
715
+ ),
716
+ None,
717
+ )
718
+ if inherited_child is not None:
719
+ body_pr.append(copy.deepcopy(inherited_child))
720
+ local_names.add(inherited_child.tag.rsplit("}", 1)[-1])
721
+ return effective
722
+
723
+
724
+ def _block_formula_zone(tx_body: ET.Element | None) -> ET.Element | None:
725
+ """Return the sole block-math zone from a canonical formula text body."""
726
+ if tx_body is None:
727
+ return None
728
+ paragraphs = tx_body.findall("a:p", NS)
729
+ if len(paragraphs) != 1:
730
+ return None
731
+ paragraph = paragraphs[0]
732
+ formula_zones = [
733
+ child
734
+ for child in paragraph
735
+ if child.tag == f"{{{A14_NS}}}m"
736
+ ]
737
+ allowed = {
738
+ f"{{{NS['a']}}}pPr",
739
+ f"{{{NS['a']}}}endParaRPr",
740
+ f"{{{A14_NS}}}m",
741
+ }
742
+ if len(formula_zones) != 1 or any(
743
+ child.tag not in allowed
744
+ for child in paragraph
745
+ if isinstance(child.tag, str)
746
+ ):
747
+ return None
748
+ root_children = [
749
+ child for child in formula_zones[0] if isinstance(child.tag, str)
750
+ ]
751
+ if (
752
+ len(root_children) != 1
753
+ or root_children[0].tag
754
+ != "{http://schemas.openxmlformats.org/officeDocument/2006/math}oMathPara"
755
+ ):
756
+ return None
757
+ return formula_zones[0]
758
+
759
+
760
+ def _block_formula_carrier_error(
761
+ node: ShapeNode,
762
+ *,
763
+ top_level: bool,
764
+ ) -> str | None:
765
+ """Reject block carriers whose non-formula state would be discarded."""
766
+ if not top_level:
767
+ return "grouped block formula carrier is not reversible"
768
+ if (
769
+ node.xfrm.rot
770
+ or node.xfrm.flip_h
771
+ or node.xfrm.flip_v
772
+ or node.effective_rotation
773
+ ):
774
+ return "block formula carrier rotation or flip is not reversible"
775
+ if node.placeholder is not None:
776
+ return "block formula carrier cannot retain placeholder ownership"
777
+ if node.hyperlink_rid or node.hyperlink_action:
778
+ return "block formula carrier hyperlink is not reversible"
779
+ if node.xml.find("p:style", NS) is not None:
780
+ return "block formula carrier style reference is not reversible"
781
+
782
+ sp_pr = node.xml.find("p:spPr", NS)
783
+ if sp_pr is None:
784
+ return "block formula carrier is missing p:spPr"
785
+ preset = sp_pr.find("a:prstGeom", NS)
786
+ if preset is None or preset.get("prst") != "rect":
787
+ return "block formula carrier must use rectangular geometry"
788
+ if any(
789
+ sp_pr.find(path, NS) is not None
790
+ for path in (
791
+ "a:solidFill",
792
+ "a:gradFill",
793
+ "a:pattFill",
794
+ "a:blipFill",
795
+ "a:grpFill",
796
+ "a:effectLst",
797
+ "a:effectDag",
798
+ "a:scene3d",
799
+ "a:sp3d",
800
+ )
801
+ ):
802
+ return "block formula carrier paint or effect is not reversible"
803
+ line = sp_pr.find("a:ln", NS)
804
+ if line is not None and line.find("a:noFill", NS) is None:
805
+ return "block formula carrier line is not reversible"
806
+ return None
807
+
808
+
809
+ def _prepare_inline_formula_resolver(
810
+ tx_body: ET.Element | None,
811
+ ctx: AssemblyContext,
812
+ *,
813
+ allow_native: bool,
814
+ force_opaque: bool = False,
815
+ ):
816
+ """Build one all-or-opaque resolver for formula runs in a text body."""
817
+ if tx_body is None:
818
+ return None
819
+ zones = [
820
+ child
821
+ for paragraph in tx_body.findall("a:p", NS)
822
+ for child in paragraph
823
+ if child.tag == f"{{{A14_NS}}}m"
824
+ ]
825
+ if not zones:
826
+ return None
827
+
828
+ imported: dict[int, FormulaImport] = {}
829
+ failed = force_opaque
830
+ if not allow_native:
831
+ failed = True
832
+ _diagnose_formula_fallback(
833
+ ctx,
834
+ FormulaImportError(
835
+ "formula reconstruction is not supported inside vertical text"
836
+ ),
837
+ )
838
+ elif not force_opaque:
839
+ for zone in zones:
840
+ try:
841
+ imported[id(zone)] = import_formula(zone, display=False)
842
+ except FormulaImportError as exc:
843
+ failed = True
844
+ _diagnose_formula_fallback(ctx, exc)
845
+
846
+ def _resolve(zone: ET.Element) -> tuple[str | None, str]:
847
+ if failed:
848
+ return None, opaque_formula_preview(zone)
849
+ item = imported.get(id(zone))
850
+ if item is None:
851
+ return None, opaque_formula_preview(zone)
852
+ return item.latex, item.preview
853
+
854
+ return _resolve
855
+
856
+
857
+ def _diagnose_formula_fallback(
858
+ ctx: AssemblyContext,
859
+ error: FormulaImportError,
860
+ ) -> None:
861
+ message = f"Office Math was not reconstructed: {error}"
862
+ if ctx.strict:
863
+ raise ValueError(message) from error
864
+ ctx.diagnose(
865
+ "formula-not-reconstructed",
866
+ message,
867
+ "render a linear text preview and preserve the relationship-free source txBody",
868
+ )
869
+
870
+
871
+ def _render_block_formula(
872
+ node: ShapeNode,
873
+ ctx: AssemblyContext,
874
+ formula: FormulaImport,
875
+ *,
876
+ top_level: bool,
877
+ ) -> str:
878
+ """Emit one canonical block marker and a dependency-free SVG preview."""
879
+ x = fmt_num(node.xfrm.x)
880
+ y = fmt_num(node.xfrm.y)
881
+ width = fmt_num(node.xfrm.w)
882
+ height = fmt_num(node.xfrm.h)
883
+ align = formula.align
884
+ if align == "right":
885
+ preview_x = node.xfrm.x + node.xfrm.w
886
+ anchor = "end"
887
+ elif align == "left":
888
+ preview_x = node.xfrm.x
889
+ anchor = "start"
890
+ else:
891
+ preview_x = node.xfrm.x + node.xfrm.w / 2.0
892
+ anchor = "middle"
893
+ preview_y = node.xfrm.y + node.xfrm.h / 2.0 + formula.font_size_px * 0.35
894
+ payload = {
895
+ "latex": formula.latex,
896
+ "display": "block",
897
+ "font_size": formula.font_size_px,
898
+ "color": formula.color,
899
+ "align": align,
900
+ "language": formula.language,
901
+ "name": node.name or f"Formula {node.spid}",
902
+ }
903
+ metadata = (
904
+ '<metadata type="application/json">'
905
+ + _xml_escape(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
906
+ + "</metadata>"
907
+ )
908
+ preview = (
909
+ f'<text x="{fmt_num(preview_x)}" y="{fmt_num(preview_y)}" '
910
+ f'text-anchor="{anchor}" font-family="Cambria Math" '
911
+ f'font-size="{fmt_num(formula.font_size_px)}" '
912
+ f'fill="{_xml_escape(formula.color)}">'
913
+ f'{_xml_escape(formula.preview)}</text>'
914
+ )
915
+ return _wrap_shape_group(
916
+ metadata + "\n" + preview,
917
+ node,
918
+ ctx,
919
+ top_level=top_level,
920
+ extra_attrs=[
921
+ 'data-pptx-replace-with="formula"',
922
+ 'data-pptx-import-source="pptx"',
923
+ f'data-pptx-x="{x}"',
924
+ f'data-pptx-y="{y}"',
925
+ f'data-pptx-width="{width}"',
926
+ f'data-pptx-height="{height}"',
927
+ f'data-pptx-bounds="{x} {y} {width} {height}"',
928
+ ],
929
+ )
930
+
931
+
932
+ def _txbody_metadata(
933
+ tx_body: ET.Element,
934
+ visible_text_svg: str,
935
+ ) -> str:
936
+ """Preserve the native text body while its visible SVG remains authoritative."""
937
+ if has_relationship_attributes(tx_body):
938
+ # Relationship ids are part-local and cannot be copied into a newly
939
+ # generated slide without rebuilding the relationship target.
940
+ return ""
941
+ raw = ET.tostring(tx_body, encoding="utf-8")
942
+ encoded = base64.b64encode(raw).decode("ascii")
943
+ wrapper = ET.fromstring(
944
+ f'<svg xmlns="http://www.w3.org/2000/svg">{visible_text_svg}</svg>'
945
+ )
946
+ digest = svg_text_fingerprint(wrapper)
947
+ return (
948
+ '<metadata data-pptx-part="txbody" data-pptx-encoding="base64" '
949
+ f'data-pptx-text-sha256="{digest}">{encoded}</metadata>'
950
+ )
951
+
952
+
953
+ def _resolve_geometry(node: ShapeNode, sp_pr: ET.Element | None) -> GeomResult | None:
954
+ """Resolve a DrawingML shape geometry into an absolute SVG geometry model."""
955
+ prst_geom = sp_pr.find("a:prstGeom", NS) if sp_pr is not None else None
956
+ cust_geom = sp_pr.find("a:custGeom", NS) if sp_pr is not None else None
957
+ prst = prst_geom.attrib.get("prst", "rect") if prst_geom is not None else None
958
+
959
+ geom: GeomResult | None = None
960
+ if prst_geom is not None:
961
+ geom = convert_prst_geom(prst, node.xfrm, prst_geom)
962
+ elif cust_geom is not None:
963
+ d = convert_custom_geom(cust_geom, node.xfrm)
964
+ if d:
965
+ raw = ET.tostring(cust_geom, encoding="utf-8")
966
+ geom = GeomResult(
967
+ tag="path",
968
+ path_d=d,
969
+ attrs={
970
+ "data-pptx-part": "geometry",
971
+ "data-pptx-geometry-kind": "custom",
972
+ "data-pptx-custgeom": base64.b64encode(raw).decode("ascii"),
973
+ "data-pptx-geometry-sha256": hashlib.sha256(
974
+ d.strip().encode("utf-8")
975
+ ).hexdigest(),
976
+ },
977
+ )
978
+ else:
979
+ # No geometry hint at all — render bounding rect
980
+ geom = convert_prst_geom("rect", node.xfrm, None)
981
+
982
+ if geom is None:
983
+ return None
984
+ permits_degenerate_axis = (
985
+ node.kind == CONNECTOR
986
+ or prst in CONNECTOR_PRESET_TYPES
987
+ )
988
+ if (
989
+ not permits_degenerate_axis
990
+ and (node.xfrm.w <= 0 or node.xfrm.h <= 0)
991
+ ):
992
+ return None
993
+ return geom
994
+
995
+
996
+ def _build_geometry_xml(node: ShapeNode, sp_pr: ET.Element | None,
997
+ ctx: AssemblyContext,
998
+ geom: GeomResult | None = None) -> str:
999
+ """Build the SVG geometry element with fill/stroke/effect attributes."""
1000
+ if geom is None:
1001
+ geom = _resolve_geometry(node, sp_pr)
1002
+ if geom is None:
1003
+ return ""
1004
+
1005
+ # Resolve style defaults early so markers can adopt the theme stroke color
1006
+ # when <a:ln> doesn't carry an explicit solidFill.
1007
+ try:
1008
+ style_defaults = _resolve_shape_style_defaults(node, ctx)
1009
+ except ValueError as exc:
1010
+ if ctx.strict:
1011
+ raise
1012
+ ctx.diagnose(
1013
+ "shape-style-omitted",
1014
+ str(exc),
1015
+ "omit unresolved theme style defaults",
1016
+ )
1017
+ style_defaults = {}
1018
+
1019
+ # Fill / stroke / effect
1020
+ try:
1021
+ fill = resolve_fill(
1022
+ sp_pr,
1023
+ ctx.palette,
1024
+ id_prefix="g",
1025
+ id_seq=ctx.grad_seq,
1026
+ )
1027
+ except ValueError as exc:
1028
+ if ctx.strict:
1029
+ raise
1030
+ ctx.diagnose(
1031
+ "fill-omitted",
1032
+ str(exc),
1033
+ "omit only the unsupported fill",
1034
+ )
1035
+ fill = FillResult.none_fill()
1036
+ try:
1037
+ stroke = resolve_stroke(
1038
+ sp_pr,
1039
+ ctx.palette,
1040
+ id_prefix="m",
1041
+ id_seq=ctx.marker_seq,
1042
+ style_stroke_default=style_defaults.get("stroke"),
1043
+ )
1044
+ except ValueError as exc:
1045
+ if ctx.strict:
1046
+ raise
1047
+ ctx.diagnose(
1048
+ "stroke-omitted",
1049
+ str(exc),
1050
+ "omit only the unsupported outline",
1051
+ )
1052
+ stroke = StrokeResult(attrs={"stroke": "none"})
1053
+ try:
1054
+ effect = convert_effects(
1055
+ sp_pr,
1056
+ ctx.palette,
1057
+ id_prefix="fx",
1058
+ id_seq=ctx.filter_seq,
1059
+ target_rotation_degrees=node.effective_rotation,
1060
+ )
1061
+ except ValueError as exc:
1062
+ if ctx.strict:
1063
+ raise
1064
+ ctx.diagnose(
1065
+ "effect-omitted",
1066
+ str(exc),
1067
+ "omit only the unsupported visual effect",
1068
+ )
1069
+ effect = EffectResult()
1070
+
1071
+ ctx.defs.extend(fill.defs)
1072
+ ctx.defs.extend(stroke.defs)
1073
+ ctx.defs.extend(effect.defs)
1074
+ effect_attrs = dict(effect.metadata)
1075
+ effect_reason = effect_attrs.get(EFFECT_REASON_ATTR)
1076
+ existing_reason = geom.attrs.get(EFFECT_REASON_ATTR)
1077
+ if effect_reason is not None and existing_reason is not None:
1078
+ effect_attrs.update(unsupported_effect_metadata(
1079
+ existing_reason,
1080
+ effect_reason,
1081
+ ))
1082
+ geom.attrs.update(effect_attrs)
1083
+ _diagnose_unsupported_effect(ctx, geom.attrs)
1084
+
1085
+ attrs = {**fill.attrs, **stroke.attrs}
1086
+ for key, value in style_defaults.items():
1087
+ attrs.setdefault(key, value)
1088
+ if effect.filter_id is not None:
1089
+ attrs["filter"] = f"url(#{effect.filter_id})"
1090
+
1091
+ # Default fill / stroke when not specified by spPr (matches PowerPoint
1092
+ # behavior: a:noFill on shape-level fill if there's a txBody, else any
1093
+ # explicit fill present in spPr should already have been captured).
1094
+ if "fill" not in attrs:
1095
+ attrs["fill"] = "none"
1096
+ if "stroke" not in attrs:
1097
+ # Spec default for shapes is no stroke unless ln says otherwise.
1098
+ # Skip emitting stroke="none" to keep markup tight.
1099
+ pass
1100
+
1101
+ semantic_attrs = {
1102
+ **geom.attrs,
1103
+ **_object_metadata(node, ctx),
1104
+ }
1105
+ shape_style = node.xml.find("p:style", NS)
1106
+ if shape_style is not None:
1107
+ semantic_attrs["data-pptx-shape-style"] = base64.b64encode(
1108
+ ET.tostring(shape_style, encoding="utf-8")
1109
+ ).decode("ascii")
1110
+ if geom.layers:
1111
+ return _preset_layers_to_svg(geom, semantic_attrs, attrs)
1112
+ return _geom_to_svg(
1113
+ geom,
1114
+ _attrs_to_xml({**semantic_attrs, **attrs}),
1115
+ )
1116
+
1117
+
1118
+ def _resolve_shape_style_defaults(node: ShapeNode, ctx: AssemblyContext) -> dict[str, str]:
1119
+ """Resolve minimal p:style defaults used when spPr omits explicit style.
1120
+
1121
+ Full theme style matrix reproduction is intentionally out of scope here;
1122
+ this only prevents common theme-styled placeholders/shapes from becoming
1123
+ transparent or unstroked when their visible color lives in p:style.
1124
+ """
1125
+ style = node.xml.find("p:style", NS)
1126
+ if style is None:
1127
+ return {}
1128
+
1129
+ defaults: dict[str, str] = {}
1130
+
1131
+ fill_ref = style.find("a:fillRef", NS)
1132
+ fill_color = _resolve_ref_color(fill_ref, ctx)
1133
+ if fill_color:
1134
+ defaults["fill"] = fill_color
1135
+
1136
+ ln_ref = style.find("a:lnRef", NS)
1137
+ line_color = _resolve_ref_color(ln_ref, ctx)
1138
+ if line_color:
1139
+ defaults["stroke"] = line_color
1140
+ defaults.setdefault("stroke-width", "1")
1141
+
1142
+ return defaults
1143
+
1144
+
1145
+ def _resolve_text_style_default(node: ShapeNode, ctx: AssemblyContext) -> str:
1146
+ """Resolve p:style fontRef color used by runs without explicit fill."""
1147
+ style = node.xml.find("p:style", NS)
1148
+ if style is None:
1149
+ return "#000000"
1150
+ font_ref = style.find("a:fontRef", NS)
1151
+ font_color = _resolve_ref_color(font_ref, ctx)
1152
+ return font_color or "#000000"
1153
+
1154
+
1155
+ def _resolve_ref_color(ref_elem: ET.Element | None, ctx: AssemblyContext) -> str | None:
1156
+ color_elem = find_color_elem(ref_elem)
1157
+ hex_, _alpha = resolve_color(color_elem, ctx.palette)
1158
+ return hex_
1159
+
1160
+
1161
+ def _geom_to_svg(geom: GeomResult, attrs_xml: str | None = None) -> str:
1162
+ """Serialize a resolved geometry with optional SVG attributes."""
1163
+ if attrs_xml is None:
1164
+ attrs_xml = _attrs_to_xml(geom.attrs)
1165
+ if geom.tag == "path":
1166
+ return f'<path d="{geom.path_d}"{attrs_xml}/>'
1167
+ if geom.tag in ("polygon", "polyline"):
1168
+ return f'<{geom.tag} points="{geom.points}"{attrs_xml}/>'
1169
+ return f"<{geom.tag}{attrs_xml}/>"
1170
+
1171
+
1172
+ def _preset_layers_to_svg(
1173
+ geom: GeomResult,
1174
+ semantic_attrs: dict[str, str],
1175
+ style_attrs: dict[str, str],
1176
+ ) -> str:
1177
+ """Serialize one semantic carrier plus every visible preset path layer.
1178
+
1179
+ DrawingML applies shape-level fill/line first, then each preset path can
1180
+ override whether and how that paint is used. A hidden carrier retains the
1181
+ unmodified shape-level style for native round-trip; visible detail paths
1182
+ reproduce the preset's independent paint behavior without being exported
1183
+ as duplicate PowerPoint shapes.
1184
+ """
1185
+ markup = serialize_preset_layers(
1186
+ geom.layers,
1187
+ semantic_attrs,
1188
+ style_attrs,
1189
+ )
1190
+ geom.attrs["data-pptx-preview-sha256"] = markup.preview_hash
1191
+ semantic_attrs["data-pptx-preview-sha256"] = markup.preview_hash
1192
+ return markup.markup
1193
+
1194
+
1195
+ def _clip_blip_image(image_xml: str, geom: GeomResult | None,
1196
+ ctx: AssemblyContext) -> str:
1197
+ """Clip image fills to the owning shape geometry when it is not a plain rect."""
1198
+ if geom is None or geom.tag == "line":
1199
+ return image_xml
1200
+ if geom.attrs.get("data-pptx-prst") == "rect":
1201
+ return image_xml
1202
+ if geom.tag == "rect" and not geom.attrs.get("rx") and not geom.attrs.get("ry"):
1203
+ return image_xml
1204
+
1205
+ ctx.clip_seq[0] += 1
1206
+ clip_id = f"{ctx.group_id_prefix}clip{ctx.clip_seq[0]}"
1207
+ clip_shape = _geom_to_svg(geom, "")
1208
+ ctx.defs.append(
1209
+ f'<clipPath id="{clip_id}" clipPathUnits="userSpaceOnUse">'
1210
+ f'{clip_shape}</clipPath>'
1211
+ )
1212
+ return _inject_clip_path(image_xml, clip_id)
1213
+
1214
+
1215
+ def _inject_clip_path(image_xml: str, clip_id: str) -> str:
1216
+ clip_attr = f' clip-path="url(#{clip_id})"'
1217
+ if image_xml.startswith("<image"):
1218
+ return image_xml.replace("<image", f"<image{clip_attr}", 1)
1219
+ if image_xml.startswith("<svg"):
1220
+ return image_xml.replace("<svg", f'<svg data-pptx-crop="1"{clip_attr}', 1)
1221
+ return image_xml
1222
+
1223
+
1224
+ # ---------------------------------------------------------------------------
1225
+ # Picture (<p:pic>)
1226
+ # ---------------------------------------------------------------------------
1227
+
1228
+ def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
1229
+ sp_pr = node.xml.find("p:spPr", NS)
1230
+ geom = _resolve_geometry(node, sp_pr)
1231
+ try:
1232
+ result = convert_picture(
1233
+ node.xml, node.xfrm, ctx.slide_part, ctx.pkg,
1234
+ media_subdir=ctx.media_subdir,
1235
+ embed_inline=ctx.embed_images,
1236
+ asset_name_map=ctx.asset_name_map,
1237
+ strict=ctx.strict,
1238
+ )
1239
+ except MediaResolutionError as exc:
1240
+ if ctx.strict:
1241
+ raise
1242
+ ctx.diagnose(
1243
+ "object-replaced",
1244
+ str(exc),
1245
+ "replace only this picture with a visible placeholder",
1246
+ )
1247
+ return _fallback_node_svg(node, ctx, top_level=top_level)
1248
+ if not result.svg:
1249
+ return ""
1250
+ _diagnose_picture_result(ctx, result)
1251
+ ctx.media.update(result.media)
1252
+ effect = convert_effects(
1253
+ sp_pr,
1254
+ ctx.palette,
1255
+ id_prefix="fx",
1256
+ id_seq=ctx.filter_seq,
1257
+ target_rotation_degrees=node.effective_rotation,
1258
+ )
1259
+ ctx.defs.extend(effect.defs)
1260
+ effect_metadata = dict(effect.metadata)
1261
+ _diagnose_unsupported_effect(ctx, effect_metadata)
1262
+ clipped_svg = _clip_blip_image(result.svg, geom, ctx)
1263
+ picture_attrs = {**_object_metadata(node, ctx), **effect_metadata}
1264
+ group_attrs = _metadata_group_attrs(effect_metadata)
1265
+ if effect.filter_id is not None:
1266
+ filter_attr = f"url(#{effect.filter_id})"
1267
+ if (
1268
+ clipped_svg.startswith("<svg")
1269
+ or clipped_svg.startswith("<image clip-path=")
1270
+ ):
1271
+ # Keep the effect outside the crop viewport so shadows and glows
1272
+ # remain visible beyond the picture geometry in SVG previews.
1273
+ group_attrs.append(f'filter="{filter_attr}"')
1274
+ else:
1275
+ picture_attrs["filter"] = filter_attr
1276
+ picture_svg = _inject_root_svg_attrs(
1277
+ clipped_svg,
1278
+ picture_attrs,
1279
+ )
1280
+ return _wrap_shape_group(
1281
+ picture_svg,
1282
+ node,
1283
+ ctx,
1284
+ top_level=top_level,
1285
+ extra_attrs=group_attrs,
1286
+ )
1287
+
1288
+
1289
+ def _inject_root_svg_attrs(markup: str, attrs: dict[str, str]) -> str:
1290
+ """Attach source-object identity to a picture's root SVG element."""
1291
+ attrs_xml = _attrs_to_xml(attrs)
1292
+ for tag in ("image", "svg"):
1293
+ prefix = f"<{tag}"
1294
+ if markup.startswith(prefix):
1295
+ return markup.replace(prefix, f"{prefix}{attrs_xml}", 1)
1296
+ return markup
1297
+
1298
+
1299
+ # ---------------------------------------------------------------------------
1300
+ # Connector (<p:cxnSp>)
1301
+ # ---------------------------------------------------------------------------
1302
+
1303
+ def _convert_connector(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
1304
+ sp_pr = node.xml.find("p:spPr", NS)
1305
+ geom = _resolve_geometry(node, sp_pr)
1306
+ geom_xml = _build_geometry_xml(node, sp_pr, ctx, geom=geom)
1307
+ return _wrap_shape_group(
1308
+ geom_xml,
1309
+ node,
1310
+ ctx,
1311
+ top_level=top_level,
1312
+ extra_attrs=_geometry_group_attrs(geom),
1313
+ )
1314
+
1315
+
1316
+ # ---------------------------------------------------------------------------
1317
+ # Group (<p:grpSp>)
1318
+ # ---------------------------------------------------------------------------
1319
+
1320
+ def _convert_group(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
1321
+ """Render group contents flat (children already remapped to slide space)."""
1322
+ inner_parts: list[str] = []
1323
+ for child in node.children:
1324
+ chunk = _convert_node(child, ctx, top_level=False)
1325
+ if chunk:
1326
+ inner_parts.append(chunk)
1327
+ if not inner_parts:
1328
+ return ""
1329
+ inner = "\n".join(inner_parts)
1330
+ effect_metadata = unsupported_target_effect_metadata(
1331
+ node.xml.find("p:grpSpPr", NS),
1332
+ "group",
1333
+ )
1334
+ _diagnose_unsupported_effect(ctx, effect_metadata)
1335
+ return _wrap_shape_group(
1336
+ inner,
1337
+ node,
1338
+ ctx,
1339
+ top_level=top_level,
1340
+ extra_attrs=_metadata_group_attrs(effect_metadata),
1341
+ )
1342
+
1343
+
1344
+ # ---------------------------------------------------------------------------
1345
+ # Graphic frame fallback (<p:graphicFrame>)
1346
+ # ---------------------------------------------------------------------------
1347
+
1348
+ def _convert_graphic_fallback(node: ShapeNode, ctx: AssemblyContext,
1349
+ *, top_level: bool) -> str:
1350
+ """Render a <p:graphicFrame> by dispatching on its graphicData uri.
1351
+
1352
+ Currently:
1353
+ - ``...drawingml/2006/table`` → real table renderer (`convert_tbl`)
1354
+ - ``...presentationml/2006/ole`` → render the ``mc:Fallback`` preview
1355
+ bitmap that PowerPoint bakes alongside every embedded OLE object.
1356
+ Visually identical to what PowerPoint shows for an unedited embed.
1357
+ - supported classic charts → baked preview plus native chart metadata.
1358
+ - everything else (SmartArt / diagram / unsupported chart) → labelled
1359
+ preview or bounding rectangle plus transparent unsupported metadata.
1360
+ """
1361
+ graphic_data = node.xml.find("a:graphic/a:graphicData", NS)
1362
+ uri = graphic_data.attrib.get("uri", "graphicFrame") if graphic_data is not None else "graphicFrame"
1363
+
1364
+ if uri == "http://schemas.openxmlformats.org/drawingml/2006/table":
1365
+ rendered, replacement_attrs, payload_metadata = _render_graphic_table(
1366
+ node,
1367
+ ctx,
1368
+ graphic_data,
1369
+ )
1370
+ if rendered:
1371
+ inner = (
1372
+ f"{payload_metadata}\n{rendered}"
1373
+ if payload_metadata
1374
+ else rendered
1375
+ )
1376
+ return _wrap_shape_group(
1377
+ inner,
1378
+ node,
1379
+ ctx,
1380
+ top_level=top_level,
1381
+ extra_attrs=replacement_attrs,
1382
+ )
1383
+
1384
+ preview_svg = ""
1385
+ if ctx.render_graphic_previews:
1386
+ try:
1387
+ preview_svg = _render_graphic_preview(node, ctx)
1388
+ except MediaResolutionError as exc:
1389
+ if ctx.strict:
1390
+ raise
1391
+ ctx.diagnose(
1392
+ "preview-omitted",
1393
+ str(exc),
1394
+ "omit the missing baked preview and retain the native, "
1395
+ "normalized, or placeholder fallback",
1396
+ )
1397
+
1398
+ chart_replacement_attrs: list[str] = []
1399
+ chart_payload_metadata = ""
1400
+ if uri in {CHART_URI, CHARTEX_URI}:
1401
+ rendered, chart_replacement_attrs, chart_payload_metadata = (
1402
+ _render_graphic_chart(
1403
+ node,
1404
+ ctx,
1405
+ graphic_data,
1406
+ preview_svg,
1407
+ )
1408
+ )
1409
+ if rendered:
1410
+ inner = (
1411
+ f"{chart_payload_metadata}\n{rendered}"
1412
+ if chart_payload_metadata
1413
+ else rendered
1414
+ )
1415
+ return _wrap_shape_group(
1416
+ inner,
1417
+ node,
1418
+ ctx,
1419
+ top_level=top_level,
1420
+ extra_attrs=chart_replacement_attrs,
1421
+ )
1422
+
1423
+ if uri == "http://schemas.openxmlformats.org/presentationml/2006/ole":
1424
+ if preview_svg:
1425
+ labelled = (
1426
+ preview_svg
1427
+ + "\n"
1428
+ + _graphic_preview_label(node, "ole preview")
1429
+ )
1430
+ return _wrap_shape_group(labelled, node, ctx, top_level=top_level)
1431
+
1432
+ if preview_svg:
1433
+ labelled = (
1434
+ preview_svg
1435
+ + "\n"
1436
+ + _graphic_preview_label(
1437
+ node,
1438
+ f"{uri.rsplit('/', 1)[-1]} preview",
1439
+ )
1440
+ )
1441
+ return _wrap_shape_group(labelled, node, ctx, top_level=top_level)
1442
+
1443
+ label = uri.rsplit("/", 1)[-1]
1444
+ placeholder = (
1445
+ f'<rect x="{fmt_num(node.xfrm.x)}" y="{fmt_num(node.xfrm.y)}" '
1446
+ f'width="{fmt_num(node.xfrm.w)}" height="{fmt_num(node.xfrm.h)}" '
1447
+ f'fill="none" stroke="#999999" stroke-dasharray="4 4"/>'
1448
+ f'<text x="{fmt_num(node.xfrm.x + node.xfrm.w / 2)}" '
1449
+ f'y="{fmt_num(node.xfrm.y + node.xfrm.h / 2)}" '
1450
+ f'text-anchor="middle" font-size="14" fill="#999999">'
1451
+ f"[{_xml_escape(label)}]</text>"
1452
+ )
1453
+ if chart_payload_metadata:
1454
+ placeholder = f"{chart_payload_metadata}\n{placeholder}"
1455
+ return _wrap_shape_group(
1456
+ placeholder,
1457
+ node,
1458
+ ctx,
1459
+ top_level=top_level,
1460
+ extra_attrs=chart_replacement_attrs,
1461
+ )
1462
+
1463
+
1464
+ def _graphic_preview_label(node: ShapeNode, label: str) -> str:
1465
+ return (
1466
+ f'<rect x="{fmt_num(node.xfrm.x)}" y="{fmt_num(node.xfrm.y)}" '
1467
+ f'width="{fmt_num(node.xfrm.w)}" height="22" '
1468
+ f'fill="#FFFFFF" fill-opacity="0.82" stroke="#999999" stroke-width="0.5"/>'
1469
+ f'<text x="{fmt_num(node.xfrm.x + 6)}" y="{fmt_num(node.xfrm.y + 15)}" '
1470
+ f'font-size="11" fill="#666666">[{_xml_escape(label)}]</text>'
1471
+ )
1472
+
1473
+
1474
+ def _replacement_payload_metadata(payload: object) -> str:
1475
+ payload_json = json.dumps(
1476
+ payload,
1477
+ allow_nan=False,
1478
+ ensure_ascii=False,
1479
+ separators=(",", ":"),
1480
+ )
1481
+ return (
1482
+ '<metadata type="application/json">'
1483
+ f'{_xml_text_escape(payload_json)}</metadata>'
1484
+ )
1485
+
1486
+
1487
+ def _render_graphic_table(
1488
+ node: ShapeNode,
1489
+ ctx: AssemblyContext,
1490
+ graphic_data: ET.Element | None,
1491
+ ) -> tuple[str, list[str], str]:
1492
+ """Convert the <a:tbl> child of a graphicFrame to SVG plus metadata."""
1493
+ if graphic_data is None:
1494
+ return "", [], ""
1495
+ tbl = graphic_data.find("a:tbl", NS)
1496
+ if tbl is None:
1497
+ return "", [], ""
1498
+ table_styles_part = ctx.pkg.resolve_table_styles()
1499
+ result = convert_tbl(
1500
+ tbl, node.xfrm, ctx.palette,
1501
+ table_styles=(
1502
+ table_styles_part.xml if table_styles_part is not None else None
1503
+ ),
1504
+ theme_fonts=ctx.theme_fonts,
1505
+ slide_number=ctx.slide_number,
1506
+ id_prefix=f"tbl{ctx.shape_seq[0]}",
1507
+ grad_seq=ctx.grad_seq,
1508
+ marker_seq=ctx.marker_seq,
1509
+ hyperlink_resolver=lambda rid, action: _resolve_svg_hyperlink(
1510
+ ctx,
1511
+ rid,
1512
+ action,
1513
+ ),
1514
+ )
1515
+ if result.defs:
1516
+ ctx.defs.extend(result.defs)
1517
+ replacement_attrs: list[str] = ['data-pptx-import-source="pptx"']
1518
+ payload_metadata = ""
1519
+ if result.native_payload:
1520
+ if node.name and not result.native_payload.get("name"):
1521
+ result.native_payload["name"] = node.name
1522
+ payload_metadata = _replacement_payload_metadata(result.native_payload)
1523
+ replacement_attrs.append('data-pptx-replace-with="table"')
1524
+ elif result.native_status:
1525
+ replacement_attrs.append(
1526
+ 'data-pptx-replacement-status="'
1527
+ f'{_xml_escape(result.native_status)}"'
1528
+ )
1529
+ if result.effect_reason:
1530
+ effect_metadata = unsupported_effect_metadata(result.effect_reason)
1531
+ _diagnose_unsupported_effect(ctx, effect_metadata)
1532
+ replacement_attrs.extend(_metadata_group_attrs(effect_metadata))
1533
+ return result.svg, replacement_attrs, payload_metadata
1534
+
1535
+
1536
+ def _render_graphic_chart(
1537
+ node: ShapeNode,
1538
+ ctx: AssemblyContext,
1539
+ graphic_data: ET.Element | None,
1540
+ preview_svg: str,
1541
+ ) -> tuple[str, list[str], str]:
1542
+ """Return a chart fallback plus native Chart replacement metadata."""
1543
+ result = extract_native_chart_payload(
1544
+ graphic_data,
1545
+ node.xfrm,
1546
+ ctx.slide_part,
1547
+ ctx.pkg,
1548
+ ctx.palette,
1549
+ )
1550
+ replacement_attrs: list[str] = ['data-pptx-import-source="pptx"']
1551
+ payload_metadata = ""
1552
+ if result.native_payload:
1553
+ if node.name and not result.native_payload.get("name"):
1554
+ result.native_payload["name"] = node.name
1555
+ payload_metadata = _replacement_payload_metadata(result.native_payload)
1556
+ replacement_attrs.append('data-pptx-replace-with="chart"')
1557
+ elif result.native_status:
1558
+ replacement_attrs.append(
1559
+ 'data-pptx-replacement-status="'
1560
+ f'{_xml_escape(result.native_status)}"'
1561
+ )
1562
+
1563
+ rendered = preview_svg
1564
+ if rendered:
1565
+ replacement_attrs.append('data-pptx-fallback-kind="source-preview"')
1566
+ elif result.normalized_svg:
1567
+ rendered = result.normalized_svg
1568
+ replacement_attrs.append('data-pptx-fallback-kind="normalized"')
1569
+ else:
1570
+ replacement_attrs.append('data-pptx-fallback-kind="placeholder"')
1571
+ return rendered, replacement_attrs, payload_metadata
1572
+
1573
+
1574
+ def _render_graphic_preview(node: ShapeNode, ctx: AssemblyContext) -> str:
1575
+ """Render a graphicFrame's baked fallback preview bitmap when present.
1576
+
1577
+ PowerPoint stores a static raster preview for many embedded graphics
1578
+ inside ``mc:AlternateContent``. The Fallback branch is normally a plain
1579
+ ``p:pic`` (sometimes nested), so any conformant viewer that can't speak
1580
+ the richer object paints the preview. We do the same for flat preview SVGs.
1581
+
1582
+ Falls back to '' when the deck has no Fallback pic (very old or
1583
+ third-party authoring tools sometimes omit it). Caller then emits the
1584
+ dashed placeholder.
1585
+ """
1586
+ ac = node.xml.find("a:graphic/a:graphicData/mc:AlternateContent", NS)
1587
+ if ac is None:
1588
+ return ""
1589
+ pic = ac.find("mc:Fallback//p:pic", NS)
1590
+ if pic is None:
1591
+ # Some authoring tools put the preview directly in mc:Choice.
1592
+ pic = ac.find("mc:Choice//p:pic", NS)
1593
+ if pic is None:
1594
+ return ""
1595
+
1596
+ # The inner pic carries its own absolute xfrm in this deck (and in every
1597
+ # well-formed PPTX I've seen — PowerPoint copies the graphicFrame xfrm
1598
+ # there during save). If it's missing, fall back to the graphicFrame's
1599
+ # xfrm so the preview at least lands somewhere visible.
1600
+ inner_xfrm = node.xfrm
1601
+ pic_xfrm_elem = pic.find("p:spPr/a:xfrm", NS)
1602
+ if pic_xfrm_elem is not None:
1603
+ from .emu_units import parse_xfrm
1604
+ parsed = parse_xfrm(pic_xfrm_elem)
1605
+ if parsed.w > 0 and parsed.h > 0:
1606
+ inner_xfrm = parsed
1607
+
1608
+ result = convert_picture(
1609
+ pic, inner_xfrm, ctx.slide_part, ctx.pkg,
1610
+ media_subdir=ctx.media_subdir,
1611
+ embed_inline=ctx.embed_images,
1612
+ asset_name_map=ctx.asset_name_map,
1613
+ strict=ctx.strict,
1614
+ )
1615
+ if not result.svg:
1616
+ return ""
1617
+ _diagnose_picture_result(ctx, result)
1618
+ ctx.media.update(result.media)
1619
+ return result.svg
1620
+
1621
+
1622
+ # ---------------------------------------------------------------------------
1623
+ # Background
1624
+ # ---------------------------------------------------------------------------
1625
+
1626
+ def _emit_background(slide: SlideRef, ctx: AssemblyContext,
1627
+ w: float, h: float) -> str:
1628
+ """Inspect <p:bg> on slide / layout / master in inheritance order."""
1629
+ for part in (slide.part, slide.layout, slide.master):
1630
+ if part is None:
1631
+ continue
1632
+ bg = get_background(part.xml)
1633
+ if bg is None:
1634
+ continue
1635
+ bg_pr = bg.find("p:bgPr", NS)
1636
+ bg_ref = bg.find("p:bgRef", NS)
1637
+ placeholder_hex = None
1638
+
1639
+ if bg_pr is None and bg_ref is not None:
1640
+ bg_pr = _theme_background_fill(slide, ctx, bg_ref)
1641
+ color_elem = find_color_elem(bg_ref)
1642
+ placeholder_hex, _ = resolve_color(color_elem, ctx.palette)
1643
+ if bg_pr is None:
1644
+ continue
1645
+
1646
+ bg_image = _emit_background_image(bg_pr, part, ctx, w, h)
1647
+ if bg_image:
1648
+ return bg_image
1649
+
1650
+ fill = resolve_fill(
1651
+ bg_pr, ctx.palette,
1652
+ id_prefix="bg", id_seq=ctx.grad_seq,
1653
+ placeholder_hex=placeholder_hex,
1654
+ )
1655
+ ctx.defs.extend(fill.defs)
1656
+ if not fill.attrs:
1657
+ return ""
1658
+ # Convert dict to attributes
1659
+ attrs_xml = _attrs_to_xml(fill.attrs)
1660
+ return (f'<rect x="0" y="0" width="{fmt_num(w)}" height="{fmt_num(h)}"'
1661
+ f"{attrs_xml}/>")
1662
+ return ""
1663
+
1664
+
1665
+ def _emit_part_background(slide: SlideRef, ctx: AssemblyContext,
1666
+ w: float, h: float) -> str:
1667
+ """Render the background declared on the part itself only.
1668
+
1669
+ Distinct from `_emit_background`, which walks the slide → layout →
1670
+ master inheritance chain. Used by the layered solo renderer so each
1671
+ standalone master / layout SVG carries only its own ``<p:bg>`` — the
1672
+ inheritance is rebuilt by consumers re-stacking the layers, and we'd
1673
+ rather output nothing than have master decoration leak into a layout
1674
+ file.
1675
+ """
1676
+ bg = get_background(slide.part.xml)
1677
+ if bg is None:
1678
+ return ""
1679
+ bg_pr = bg.find("p:bgPr", NS)
1680
+ bg_ref = bg.find("p:bgRef", NS)
1681
+ placeholder_hex = None
1682
+
1683
+ if bg_pr is None and bg_ref is not None:
1684
+ bg_pr = _theme_background_fill(slide, ctx, bg_ref)
1685
+ color_elem = find_color_elem(bg_ref)
1686
+ placeholder_hex, _ = resolve_color(color_elem, ctx.palette)
1687
+ if bg_pr is None:
1688
+ return ""
1689
+
1690
+ bg_image = _emit_background_image(bg_pr, slide.part, ctx, w, h)
1691
+ if bg_image:
1692
+ return bg_image
1693
+
1694
+ fill = resolve_fill(
1695
+ bg_pr, ctx.palette,
1696
+ id_prefix="bg", id_seq=ctx.grad_seq,
1697
+ placeholder_hex=placeholder_hex,
1698
+ )
1699
+ ctx.defs.extend(fill.defs)
1700
+ if not fill.attrs:
1701
+ return ""
1702
+ attrs_xml = _attrs_to_xml(fill.attrs)
1703
+ return (f'<rect x="0" y="0" width="{fmt_num(w)}" height="{fmt_num(h)}"'
1704
+ f"{attrs_xml}/>")
1705
+
1706
+
1707
+ def _emit_background_image(
1708
+ bg_pr: ET.Element,
1709
+ source_part: PartRef,
1710
+ ctx: AssemblyContext,
1711
+ w: float,
1712
+ h: float,
1713
+ ) -> str:
1714
+ """Render a slide/layout/master background image fill as a full-canvas image."""
1715
+ blip_fill = bg_pr.find("a:blipFill", NS)
1716
+ if blip_fill is None:
1717
+ return ""
1718
+
1719
+ result = convert_blip_fill(
1720
+ blip_fill,
1721
+ Xfrm(0.0, 0.0, w, h),
1722
+ source_part,
1723
+ ctx.pkg,
1724
+ media_subdir=ctx.media_subdir,
1725
+ embed_inline=ctx.embed_images,
1726
+ asset_name_map=ctx.asset_name_map,
1727
+ strict=ctx.strict,
1728
+ )
1729
+ _diagnose_picture_result(ctx, result)
1730
+ if result.media:
1731
+ ctx.media.update(result.media)
1732
+ return result.svg
1733
+
1734
+
1735
+ def _theme_background_fill(
1736
+ slide: SlideRef,
1737
+ ctx: AssemblyContext,
1738
+ bg_ref: ET.Element,
1739
+ ) -> ET.Element | None:
1740
+ """Resolve p:bgRef idx into the theme background fill style list."""
1741
+ idx_raw = bg_ref.attrib.get("idx")
1742
+ if not idx_raw:
1743
+ return None
1744
+ try:
1745
+ idx = int(idx_raw)
1746
+ except ValueError:
1747
+ return None
1748
+ # ECMA style matrix background fill references are 1001-based.
1749
+ bg_fill_index = idx - 1001
1750
+ if bg_fill_index < 0:
1751
+ return None
1752
+
1753
+ theme = ctx.pkg.resolve_theme(slide.master)
1754
+ if theme is None:
1755
+ return None
1756
+ fill_list = theme.xml.find(".//a:fmtScheme/a:bgFillStyleLst", NS)
1757
+ if fill_list is None:
1758
+ return None
1759
+ fills = [child for child in list(fill_list) if isinstance(child.tag, str)]
1760
+ if bg_fill_index >= len(fills):
1761
+ return None
1762
+ return fills[bg_fill_index]
1763
+
1764
+
1765
+ def _emit_inherited_shapes(slide: SlideRef, ctx: AssemblyContext) -> list[str]:
1766
+ parts: list[str] = []
1767
+ show_layout_shapes, show_master_shapes = inherited_shape_visibility(slide)
1768
+ inherited_parts = (
1769
+ ("master-", slide.master, show_master_shapes),
1770
+ ("layout-", slide.layout, show_layout_shapes),
1771
+ )
1772
+ for prefix, part, visible in inherited_parts:
1773
+ if part is None or not visible:
1774
+ continue
1775
+ original_part = ctx.slide_part
1776
+ original_prefix = ctx.group_id_prefix
1777
+ ctx.slide_part = part
1778
+ ctx.group_id_prefix = prefix
1779
+ try:
1780
+ for node in walk_sp_tree(part.xml):
1781
+ if _is_placeholder_node(node):
1782
+ continue
1783
+ chunk = _convert_node(node, ctx, top_level=True)
1784
+ if chunk:
1785
+ parts.append(chunk)
1786
+ finally:
1787
+ ctx.slide_part = original_part
1788
+ ctx.group_id_prefix = original_prefix
1789
+ return parts
1790
+
1791
+
1792
+ def _is_placeholder_node(node: ShapeNode) -> bool:
1793
+ if node.placeholder is not None:
1794
+ return True
1795
+ if node.kind == GROUP:
1796
+ return all(_is_placeholder_node(child) for child in node.children)
1797
+ return False
1798
+
1799
+
1800
+ def _convert_placeholder_guide(node: ShapeNode, ctx: AssemblyContext,
1801
+ *, top_level: bool) -> str:
1802
+ """Emit the source-authored appearance of one template placeholder."""
1803
+ return _convert_node(node, ctx, top_level=top_level)
1804
+
1805
+
1806
+ # ---------------------------------------------------------------------------
1807
+ # Wrap / utilities
1808
+ # ---------------------------------------------------------------------------
1809
+
1810
+ def _wrap_shape_group(
1811
+ inner: str,
1812
+ node: ShapeNode,
1813
+ ctx: AssemblyContext,
1814
+ *,
1815
+ top_level: bool,
1816
+ extra_attrs: list[str] | None = None,
1817
+ ) -> str:
1818
+ """Wrap a shape's body in a <g> that carries the transform (rotation /
1819
+ flip) and an id for animation anchoring."""
1820
+ if not inner.strip():
1821
+ return ""
1822
+
1823
+ transform = node.xfrm.to_svg_transform()
1824
+ ctx.shape_seq[0] += 1
1825
+ seq = ctx.shape_seq[0]
1826
+ sid = node.spid or str(seq)
1827
+ g_id = f"{ctx.group_id_prefix}shape-{sid}"
1828
+
1829
+ attrs: list[str] = [f'id="{g_id}"']
1830
+ attrs.extend(
1831
+ f'{key}="{_xml_escape(value)}"'
1832
+ for key, value in _object_metadata(
1833
+ node,
1834
+ ctx,
1835
+ fallback_shape_id=sid,
1836
+ ).items()
1837
+ )
1838
+ if node.name:
1839
+ attrs.append(f'data-name="{_xml_escape(node.name)}"')
1840
+ if node.placeholder is not None and node.placeholder.type:
1841
+ attrs.append(f'data-ph-type="{_xml_escape(node.placeholder.type)}"')
1842
+ if node.placeholder is not None and node.kind == SHAPE:
1843
+ sp_pr = node.xml.find("p:spPr", NS)
1844
+ if sp_pr is not None and any(
1845
+ sp_pr.find(path, NS) is not None
1846
+ for path in ("a:prstGeom", "a:custGeom")
1847
+ ):
1848
+ attrs.append('data-pptx-placeholder-local-geometry="true"')
1849
+ if extra_attrs:
1850
+ attrs.extend(extra_attrs)
1851
+ if any(
1852
+ attribute.split("=", 1)[0] == "data-pptx-replace-with"
1853
+ for attribute in extra_attrs
1854
+ ):
1855
+ fallback_hash = svg_native_fallback_markup_fingerprint(
1856
+ inner,
1857
+ root_transform=transform,
1858
+ external_markup="".join(ctx.defs),
1859
+ )
1860
+ attrs.append(
1861
+ f'{NATIVE_FALLBACK_SHA256_ATTR}="{fallback_hash}"'
1862
+ )
1863
+ if transform:
1864
+ attrs.append(f'transform="{transform}"')
1865
+ group_xml = f"<g {' '.join(attrs)}>\n{inner}\n</g>"
1866
+ if node.hyperlink_rid or node.hyperlink_action:
1867
+ href = _resolve_svg_hyperlink(
1868
+ ctx,
1869
+ node.hyperlink_rid,
1870
+ node.hyperlink_action,
1871
+ )
1872
+ if href is not None and '<a href=' in inner:
1873
+ attrs.append(
1874
+ f'{SHAPE_HYPERLINK_ATTR}="{_xml_escape(href)}"'
1875
+ )
1876
+ return f"<g {' '.join(attrs)}>\n{inner}\n</g>"
1877
+ if href is not None:
1878
+ return f'<a href="{_xml_escape(href)}">{group_xml}</a>'
1879
+ return group_xml
1880
+
1881
+
1882
+ def _attrs_to_xml(attrs: dict[str, str]) -> str:
1883
+ if not attrs:
1884
+ return ""
1885
+ return "".join(f' {key}="{_xml_escape(value)}"' for key, value in attrs.items())
1886
+
1887
+
1888
+ def _metadata_group_attrs(attrs: dict[str, str]) -> list[str]:
1889
+ """Serialize import metadata for a logical object wrapper."""
1890
+ return [
1891
+ f'{key}="{_xml_escape(value)}"'
1892
+ for key, value in attrs.items()
1893
+ ]
1894
+
1895
+
1896
+ def _diagnose_unsupported_effect(
1897
+ ctx: AssemblyContext,
1898
+ metadata: dict[str, str],
1899
+ ) -> None:
1900
+ """Copy an import-only blocking effect marker into the conversion report."""
1901
+ reason = metadata.get(EFFECT_REASON_ATTR)
1902
+ if reason is None:
1903
+ return
1904
+ ctx.diagnose(
1905
+ "effect-unsupported",
1906
+ reason,
1907
+ "retain the base object and record blocking effect metadata",
1908
+ )
1909
+
1910
+
1911
+ def _geometry_group_attrs(geom: GeomResult | None) -> list[str]:
1912
+ """Mirror native geometry semantics onto the logical shape container."""
1913
+ if geom is None:
1914
+ return []
1915
+ keys = (
1916
+ "data-pptx-prst",
1917
+ "data-pptx-geometry-kind",
1918
+ "data-pptx-geometry-sha256",
1919
+ "data-pptx-preview-sha256",
1920
+ "data-pptx-geometry-status",
1921
+ "data-pptx-geometry-reason",
1922
+ EFFECT_STATUS_ATTR,
1923
+ EFFECT_REASON_ATTR,
1924
+ )
1925
+ attrs: list[str] = []
1926
+ for key, value in geom.attrs.items():
1927
+ if key in keys or key.startswith("data-pptx-av-"):
1928
+ attrs.append(f'{key}="{_xml_escape(value)}"')
1929
+ return attrs
1930
+
1931
+
1932
+ def _object_metadata(
1933
+ node: ShapeNode,
1934
+ ctx: AssemblyContext,
1935
+ *,
1936
+ fallback_shape_id: str = "",
1937
+ ) -> dict[str, str]:
1938
+ """Describe the source object without coupling geometry to its SVG bounds."""
1939
+ object_kind = {
1940
+ SHAPE: "shape",
1941
+ PICTURE: "picture",
1942
+ CONNECTOR: "connector",
1943
+ GROUP: "group",
1944
+ GRAPHIC: "graphic-frame",
1945
+ }.get(node.kind, node.kind)
1946
+ shape_id = node.spid or fallback_shape_id
1947
+ frame = " ".join((
1948
+ fmt_num(node.xfrm.x, 8),
1949
+ fmt_num(node.xfrm.y, 8),
1950
+ fmt_num(node.xfrm.w, 8),
1951
+ fmt_num(node.xfrm.h, 8),
1952
+ ))
1953
+ attrs = {
1954
+ "data-pptx-object": object_kind,
1955
+ "data-pptx-shape-id": shape_id,
1956
+ "data-pptx-shape-scope": _shape_scope(ctx),
1957
+ "data-pptx-frame": frame,
1958
+ }
1959
+ if node.name:
1960
+ attrs["data-pptx-shape-name"] = node.name
1961
+ if node.kind == CONNECTOR:
1962
+ attrs.update(_connector_metadata(node, _shape_scope(ctx)))
1963
+ return attrs
1964
+
1965
+
1966
+ def _shape_scope(ctx: AssemblyContext) -> str:
1967
+ if ctx.group_id_prefix.startswith("master-"):
1968
+ return "master"
1969
+ if ctx.group_id_prefix.startswith("layout-"):
1970
+ return "layout"
1971
+ return "slide"
1972
+
1973
+
1974
+ def _connector_metadata(node: ShapeNode, scope: str) -> dict[str, str]:
1975
+ """Preserve connector endpoint references when PowerPoint declares them."""
1976
+ attrs: dict[str, str] = {}
1977
+ cnv = node.xml.find("p:nvCxnSpPr/p:cNvCxnSpPr", NS)
1978
+ if cnv is None:
1979
+ return attrs
1980
+
1981
+ for endpoint, prefix in (("stCxn", "start"), ("endCxn", "end")):
1982
+ connection = cnv.find(f"a:{endpoint}", NS)
1983
+ if connection is None:
1984
+ continue
1985
+ shape_id = connection.attrib.get("id")
1986
+ site = connection.attrib.get("idx")
1987
+ if shape_id is not None:
1988
+ attrs[f"data-pptx-{prefix}-shape-id"] = shape_id
1989
+ attrs[f"data-pptx-{prefix}-shape-scope"] = scope
1990
+ if site is not None:
1991
+ attrs[f"data-pptx-{prefix}-site"] = site
1992
+ return attrs
1993
+
1994
+
1995
+ def _xml_escape(text: str) -> str:
1996
+ return _xml_text_escape(text).replace('"', "&quot;")
1997
+
1998
+
1999
+ def _xml_text_escape(text: str) -> str:
2000
+ return (text.replace("&", "&amp;")
2001
+ .replace("<", "&lt;")
2002
+ .replace(">", "&gt;"))