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,506 @@
1
+ """OOXML loader: read .pptx zip package, resolve relationships, expose
2
+ slide / layout / master / theme / media as a navigable structure.
3
+
4
+ Mirrors what manifest.py does for analysis, but keeps the parsed XML roots
5
+ accessible for downstream shape conversion.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import posixpath
11
+ import re
12
+ import zipfile
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path, PurePosixPath
15
+ from typing import Iterator
16
+ from xml.etree import ElementTree as ET
17
+
18
+ from .emu_units import NS, emu_attr_to_px
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Relationship parsing
23
+ # ---------------------------------------------------------------------------
24
+
25
+ REL_NS = NS["rel"]
26
+ PACKAGE_REL = "_rels/.rels"
27
+ PRESENTATION_REL_PREFIX = "ppt/_rels/presentation.xml.rels"
28
+
29
+
30
+ def _normalize_part_path(target: str, base: str | None = None) -> str:
31
+ """Resolve a relationship target against its rels source.
32
+
33
+ PPTX rels typically use paths relative to the rels file's parent directory,
34
+ e.g. slide1.xml.rels says target="../theme/theme1.xml". The result is
35
+ normalized to a posix path with no leading slash and no '..'.
36
+ """
37
+ target = target.replace("\\", "/")
38
+ if target.startswith("/"):
39
+ return target.lstrip("/")
40
+ if base is None:
41
+ return target
42
+ base_dir = posixpath.dirname(base.rstrip("/"))
43
+ joined = posixpath.normpath(posixpath.join(base_dir, target))
44
+ return joined.lstrip("/")
45
+
46
+
47
+ def _rels_path_for(part_path: str) -> str:
48
+ """Given a part path 'ppt/slides/slide1.xml', return its rels path."""
49
+ parent, name = posixpath.split(part_path)
50
+ if not parent:
51
+ return f"_rels/{name}.rels"
52
+ return f"{parent}/_rels/{name}.rels"
53
+
54
+
55
+ def _parse_rels(zf: zipfile.ZipFile, rels_path: str) -> dict[str, dict[str, str]]:
56
+ """Parse a .rels file. Returns {rId: {'type': ..., 'target': absolute_part_path}}."""
57
+ if rels_path not in zf.namelist():
58
+ return {}
59
+ try:
60
+ root = ET.fromstring(zf.read(rels_path))
61
+ except ET.ParseError as exc:
62
+ raise RuntimeError(f"Invalid relationships XML in {rels_path}: {exc}") from exc
63
+
64
+ base = rels_path.replace("/_rels/", "/") # source part path
65
+ base = base[:-len(".rels")] # strip .rels suffix
66
+ rels: dict[str, dict[str, str]] = {}
67
+ for child in root.findall(f"{{{REL_NS}}}Relationship"):
68
+ rid = child.attrib.get("Id", "")
69
+ rtype = child.attrib.get("Type", "")
70
+ target = child.attrib.get("Target", "")
71
+ target_mode = child.attrib.get("TargetMode", "")
72
+ # External relationships (e.g. hyperlinks) keep the raw target.
73
+ if target_mode == "External":
74
+ rels[rid] = {"type": rtype, "target": target, "external": "1"}
75
+ continue
76
+ absolute = _normalize_part_path(target, base)
77
+ rels[rid] = {"type": rtype, "target": absolute}
78
+ return rels
79
+
80
+
81
+ def _load_xml(zf: zipfile.ZipFile, part_path: str) -> ET.Element | None:
82
+ if part_path not in zf.namelist():
83
+ return None
84
+ try:
85
+ return ET.fromstring(zf.read(part_path))
86
+ except ET.ParseError as exc:
87
+ raise RuntimeError(f"Invalid OOXML part {part_path}: {exc}") from exc
88
+
89
+
90
+ def blip_embed_relationship_ids(blip: ET.Element) -> tuple[str, ...]:
91
+ """Return embedded image relationships in fidelity-preferred order.
92
+
93
+ Modern Office stores an editable SVG relationship in ``asvg:svgBlip``
94
+ while keeping a raster fallback on the owning ``a:blip``. Consumers must
95
+ try the SVG relationship first and retain the raster relationship only as
96
+ a compatibility fallback.
97
+ """
98
+ embed_attr = f"{{{NS['r']}}}embed"
99
+ candidates = [
100
+ node.attrib.get(embed_attr)
101
+ for node in blip.findall(".//asvg:svgBlip", NS)
102
+ ]
103
+ candidates.append(blip.attrib.get(embed_attr))
104
+
105
+ ordered: list[str] = []
106
+ for rel_id in candidates:
107
+ if rel_id and rel_id not in ordered:
108
+ ordered.append(rel_id)
109
+ return tuple(ordered)
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # Data classes for navigable parts
114
+ # ---------------------------------------------------------------------------
115
+
116
+ @dataclass
117
+ class PartRef:
118
+ """A loaded XML part with its rels resolved."""
119
+
120
+ path: str
121
+ xml: ET.Element
122
+ rels: dict[str, dict[str, str]] = field(default_factory=dict)
123
+
124
+ def resolve_rel(self, rid: str) -> str | None:
125
+ """Resolve an rId to an absolute part path. Returns None if missing."""
126
+ info = self.rels.get(rid)
127
+ if info is None:
128
+ return None
129
+ if info.get("external"):
130
+ return None
131
+ return info.get("target")
132
+
133
+
134
+ @dataclass
135
+ class SlideRef:
136
+ """One slide, with its layout / master chain attached."""
137
+
138
+ index: int # 1-based
139
+ part: PartRef
140
+ layout: PartRef | None
141
+ master: PartRef | None
142
+
143
+
144
+ def parse_ooxml_boolean(
145
+ raw: str | None,
146
+ *,
147
+ default: bool,
148
+ context: str,
149
+ ) -> bool:
150
+ """Parse one XML Schema boolean without silently accepting bad OOXML."""
151
+ if raw is None:
152
+ return default
153
+ token = raw.strip()
154
+ if token in {"1", "true"}:
155
+ return True
156
+ if token in {"0", "false"}:
157
+ return False
158
+ raise RuntimeError(f"{context}: invalid boolean value {raw!r}")
159
+
160
+
161
+ def part_show_master_sp(part: PartRef) -> bool:
162
+ """Return one slide/layout part's raw ``showMasterSp`` semantic value."""
163
+ return parse_ooxml_boolean(
164
+ part.xml.attrib.get("showMasterSp"),
165
+ default=True,
166
+ context=f"{part.path} showMasterSp",
167
+ )
168
+
169
+
170
+ def inherited_shape_visibility(slide: SlideRef) -> tuple[bool, bool]:
171
+ """Return effective ``(layout_shapes, master_shapes)`` visibility.
172
+
173
+ A slide-level false value suppresses both inherited shape trees. A
174
+ layout-level false value suppresses only its parent Master's shape tree.
175
+ Background inheritance is separate and intentionally not represented by
176
+ these booleans.
177
+ """
178
+ show_layout_shapes = part_show_master_sp(slide.part)
179
+ layout_shows_master_shapes = (
180
+ part_show_master_sp(slide.layout)
181
+ if slide.layout is not None else True
182
+ )
183
+ show_master_shapes = (
184
+ show_layout_shapes
185
+ and slide.master is not None
186
+ and layout_shows_master_shapes
187
+ )
188
+ return show_layout_shapes, show_master_shapes
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # OoxmlPackage
193
+ # ---------------------------------------------------------------------------
194
+
195
+ # Relationship type constants
196
+ REL_TYPES = {
197
+ "presentation": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
198
+ "slide": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide",
199
+ "slideLayout": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout",
200
+ "slideMaster": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster",
201
+ "theme": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
202
+ "tableStyles": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles",
203
+ "image": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
204
+ "media": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/media",
205
+ }
206
+
207
+
208
+ class OoxmlPackage:
209
+ """Loaded .pptx ready for shape walking.
210
+
211
+ Usage:
212
+ with OoxmlPackage(Path("foo.pptx")) as pkg:
213
+ for slide in pkg.iter_slides():
214
+ root = slide.part.xml
215
+ ...
216
+ """
217
+
218
+ def __init__(self, pptx_path: Path) -> None:
219
+ self.path = pptx_path
220
+ self.zip: zipfile.ZipFile | None = None
221
+ self.presentation: PartRef | None = None
222
+ self.slide_size_px: tuple[float, float] = (1280.0, 720.0)
223
+ self.slide_size_emu: tuple[int, int] = (12192000, 6858000)
224
+ self.first_slide_number: int = 1
225
+ self._slides: list[SlideRef] = []
226
+ self._layouts: dict[str, PartRef] = {}
227
+ self._masters: dict[str, PartRef] = {}
228
+ self._themes: dict[str, PartRef] = {}
229
+ self._table_styles: PartRef | None = None
230
+ self._table_styles_loaded = False
231
+
232
+ # ------------------- context manager -------------------
233
+
234
+ def __enter__(self) -> "OoxmlPackage":
235
+ self.open()
236
+ return self
237
+
238
+ def __exit__(self, exc_type, exc, tb) -> None:
239
+ self.close()
240
+
241
+ def open(self) -> None:
242
+ if self.zip is not None:
243
+ return
244
+ self.zip = zipfile.ZipFile(self.path, "r")
245
+ self._load_presentation()
246
+ self._load_slides()
247
+
248
+ def close(self) -> None:
249
+ if self.zip is not None:
250
+ self.zip.close()
251
+ self.zip = None
252
+
253
+ # ------------------- low-level helpers -------------------
254
+
255
+ def _load_part(self, part_path: str) -> PartRef | None:
256
+ assert self.zip is not None
257
+ xml = _load_xml(self.zip, part_path)
258
+ if xml is None:
259
+ return None
260
+ rels = _parse_rels(self.zip, _rels_path_for(part_path))
261
+ return PartRef(path=part_path, xml=xml, rels=rels)
262
+
263
+ def load_part(self, part_path: str) -> PartRef | None:
264
+ """Load an arbitrary XML part by package path."""
265
+ return self._load_part(part_path)
266
+
267
+ def read_part_bytes(self, part_path: str) -> bytes | None:
268
+ """Return the unchanged bytes of one internal package part."""
269
+ assert self.zip is not None
270
+ if part_path not in self.zip.namelist():
271
+ return None
272
+ return self.zip.read(part_path)
273
+
274
+ def read_media(self, part_path: str) -> bytes | None:
275
+ """Return raw bytes of an embedded media part (e.g. ppt/media/image1.png)."""
276
+ return self.read_part_bytes(part_path)
277
+
278
+ def media_filename(self, part_path: str) -> str:
279
+ """Last segment of the media path, e.g. 'image1.png'."""
280
+ return PurePosixPath(part_path).name
281
+
282
+ # ------------------- loading sequence -------------------
283
+
284
+ def _load_presentation(self) -> None:
285
+ assert self.zip is not None
286
+ # /_rels/.rels -> presentation.xml
287
+ package_rels = _parse_rels(self.zip, PACKAGE_REL)
288
+ pres_path = None
289
+ for info in package_rels.values():
290
+ if info.get("type") == REL_TYPES["presentation"]:
291
+ pres_path = info["target"]
292
+ break
293
+ if pres_path is None:
294
+ pres_path = "ppt/presentation.xml"
295
+
296
+ self.presentation = self._load_part(pres_path)
297
+ if self.presentation is None:
298
+ raise RuntimeError(f"presentation.xml missing in {self.path}")
299
+
300
+ raw_first_slide_number = self.presentation.xml.attrib.get("firstSlideNum")
301
+ if raw_first_slide_number is not None:
302
+ first_slide_token = raw_first_slide_number.strip(" \t\r\n")
303
+ if re.fullmatch(r"[+-]?[0-9]+", first_slide_token) is None:
304
+ raise RuntimeError(
305
+ f"Invalid presentation firstSlideNum: {raw_first_slide_number!r}"
306
+ )
307
+ digits = first_slide_token.lstrip("+-").lstrip("0") or "0"
308
+ if len(digits) > 10:
309
+ raise RuntimeError("Presentation firstSlideNum is outside xsd:int")
310
+ first_slide_number = int(digits)
311
+ if first_slide_token.startswith("-"):
312
+ first_slide_number = -first_slide_number
313
+ if not -(2**31) <= first_slide_number <= 2**31 - 1:
314
+ raise RuntimeError(
315
+ f"Presentation firstSlideNum is outside xsd:int: {first_slide_number}"
316
+ )
317
+ self.first_slide_number = first_slide_number
318
+
319
+ # slide size
320
+ size = self.presentation.xml.find("p:sldSz", NS)
321
+ if size is not None:
322
+ cx = int(size.attrib.get("cx", "12192000"))
323
+ cy = int(size.attrib.get("cy", "6858000"))
324
+ self.slide_size_emu = (cx, cy)
325
+ self.slide_size_px = (cx / 9525.0, cy / 9525.0)
326
+
327
+ def _load_slides(self) -> None:
328
+ assert self.zip is not None and self.presentation is not None
329
+ # presentation.xml has <p:sldIdLst><p:sldId r:id="rId..."/></p:sldIdLst>
330
+ # in document order.
331
+ sld_id_lst = self.presentation.xml.find("p:sldIdLst", NS)
332
+ if sld_id_lst is None:
333
+ return
334
+
335
+ for index, sld_id in enumerate(sld_id_lst.findall("p:sldId", NS), start=1):
336
+ rid = sld_id.attrib.get(f"{{{NS['r']}}}id")
337
+ if not rid:
338
+ continue
339
+ slide_path = self.presentation.resolve_rel(rid)
340
+ if not slide_path:
341
+ continue
342
+ slide_part = self._load_part(slide_path)
343
+ if slide_part is None:
344
+ continue
345
+ layout = self._resolve_layout(slide_part)
346
+ master = self._resolve_master(layout) if layout else None
347
+ self._slides.append(SlideRef(
348
+ index=index, part=slide_part, layout=layout, master=master,
349
+ ))
350
+
351
+ def _resolve_layout(self, slide: PartRef) -> PartRef | None:
352
+ for info in slide.rels.values():
353
+ if info.get("type") == REL_TYPES["slideLayout"]:
354
+ target = info["target"]
355
+ cached = self._layouts.get(target)
356
+ if cached is None:
357
+ cached = self._load_part(target)
358
+ if cached is not None:
359
+ self._layouts[target] = cached
360
+ return cached
361
+ return None
362
+
363
+ def _resolve_master(self, layout: PartRef) -> PartRef | None:
364
+ for info in layout.rels.values():
365
+ if info.get("type") == REL_TYPES["slideMaster"]:
366
+ target = info["target"]
367
+ cached = self._masters.get(target)
368
+ if cached is None:
369
+ cached = self._load_part(target)
370
+ if cached is not None:
371
+ self._masters[target] = cached
372
+ return cached
373
+ return None
374
+
375
+ def resolve_theme(self, master: PartRef | None) -> PartRef | None:
376
+ """Return the theme part referenced by a slide master."""
377
+ if master is None:
378
+ return None
379
+ for info in master.rels.values():
380
+ if info.get("type") == REL_TYPES["theme"]:
381
+ target = info["target"]
382
+ cached = self._themes.get(target)
383
+ if cached is None:
384
+ cached = self._load_part(target)
385
+ if cached is not None:
386
+ self._themes[target] = cached
387
+ return cached
388
+ return None
389
+
390
+ def resolve_table_styles(self) -> PartRef | None:
391
+ """Return the presentation-level table style list, when usable.
392
+
393
+ Table style definitions are optional and some producers emit only the
394
+ built-in style id. A missing or malformed style part must therefore
395
+ not prevent otherwise valid slides from being converted.
396
+ """
397
+ if self._table_styles_loaded:
398
+ return self._table_styles
399
+ self._table_styles_loaded = True
400
+
401
+ target: str | None = None
402
+ if self.presentation is not None:
403
+ for info in self.presentation.rels.values():
404
+ if info.get("type") == REL_TYPES["tableStyles"]:
405
+ target = info.get("target")
406
+ break
407
+ if target is None:
408
+ target = "ppt/tableStyles.xml"
409
+
410
+ try:
411
+ self._table_styles = self._load_part(target)
412
+ except RuntimeError:
413
+ self._table_styles = None
414
+ return self._table_styles
415
+
416
+ # ------------------- public iteration -------------------
417
+
418
+ def iter_slides(self) -> Iterator[SlideRef]:
419
+ yield from self._slides
420
+
421
+ @property
422
+ def slide_count(self) -> int:
423
+ return len(self._slides)
424
+
425
+ def get_slide(self, index: int) -> SlideRef | None:
426
+ """1-based index lookup."""
427
+ if 1 <= index <= len(self._slides):
428
+ return self._slides[index - 1]
429
+ return None
430
+
431
+ @property
432
+ def slide_index_by_part(self) -> dict[str, int]:
433
+ """Return final presentation-order indices keyed by slide part path."""
434
+ return {slide.part.path: slide.index for slide in self._slides}
435
+
436
+ def iter_all_masters(self) -> Iterator[PartRef]:
437
+ """Yield every slideMaster declared in presentation.xml, regardless of
438
+ whether any slide currently uses it.
439
+
440
+ Template decks routinely ship more masters than the visible sample
441
+ slides reference (one master per "style"). The slide-driven traversal
442
+ in ``_load_slides`` only caches masters that are actually consumed by
443
+ a slide — fine for an authoring deck, but it drops 90% of the design
444
+ intent for a multi-style template package. This iterator hits the
445
+ presentation's ``sldMasterIdLst`` directly so callers (e.g. the
446
+ layered template export) can preserve the full template library.
447
+ """
448
+ if self.presentation is None:
449
+ return
450
+ master_id_lst = self.presentation.xml.find("p:sldMasterIdLst", NS)
451
+ if master_id_lst is None:
452
+ return
453
+ for master_id in master_id_lst.findall("p:sldMasterId", NS):
454
+ rid = master_id.attrib.get(f"{{{NS['r']}}}id")
455
+ if not rid:
456
+ continue
457
+ target = self.presentation.resolve_rel(rid)
458
+ if not target:
459
+ continue
460
+ cached = self._masters.get(target)
461
+ if cached is None:
462
+ cached = self._load_part(target)
463
+ if cached is None:
464
+ continue
465
+ self._masters[target] = cached
466
+ yield cached
467
+
468
+ def iter_all_layouts(self) -> Iterator[PartRef]:
469
+ """Yield every slideLayout reachable from any master, regardless of
470
+ slide usage. Layouts live under ``master.sldLayoutIdLst`` in document
471
+ order; we walk every master so the export reflects the full set.
472
+
473
+ See :meth:`iter_all_layouts_with_parent` when you need each layout's
474
+ owning master alongside the layout itself (e.g. for theme-fill
475
+ resolution during standalone rendering).
476
+ """
477
+ for layout, _master in self.iter_all_layouts_with_parent():
478
+ yield layout
479
+
480
+ def iter_all_layouts_with_parent(self) -> Iterator[tuple[PartRef, PartRef]]:
481
+ """Like :meth:`iter_all_layouts` but yields ``(layout, parent_master)``
482
+ pairs. The parent master is the one whose ``sldLayoutIdLst`` contains
483
+ the layout, which is the source of truth for theme-style resolution
484
+ (e.g. ``<p:bgRef idx=...>`` on the layout still hops through the
485
+ master's theme).
486
+ """
487
+ seen: set[str] = set()
488
+ for master in self.iter_all_masters():
489
+ layout_id_lst = master.xml.find("p:sldLayoutIdLst", NS)
490
+ if layout_id_lst is None:
491
+ continue
492
+ for layout_id in layout_id_lst.findall("p:sldLayoutId", NS):
493
+ rid = layout_id.attrib.get(f"{{{NS['r']}}}id")
494
+ if not rid:
495
+ continue
496
+ target = master.resolve_rel(rid)
497
+ if not target or target in seen:
498
+ continue
499
+ seen.add(target)
500
+ cached = self._layouts.get(target)
501
+ if cached is None:
502
+ cached = self._load_part(target)
503
+ if cached is None:
504
+ continue
505
+ self._layouts[target] = cached
506
+ yield cached, master