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,283 @@
1
+ """Theme-color contracts shared by SVG conversion and PPTX package assembly."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from xml.etree import ElementTree as ET
9
+
10
+ from .utils import parse_hex_color
11
+
12
+
13
+ DML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
14
+ _LOCK_ROW_RE = re.compile(r"^-\s+([A-Za-z0-9_]+)\s*:\s*(.+?)\s*$")
15
+ _SRGB_PAIR_RE = re.compile(
16
+ r"<a:srgbClr\b(?P<attrs>[^>]*?)(?<!/)>(?P<body>.*?)</a:srgbClr>",
17
+ re.DOTALL,
18
+ )
19
+ _SRGB_EMPTY_RE = re.compile(r"<a:srgbClr\b(?P<attrs>[^>]*)/>")
20
+ _VAL_RE = re.compile(r'\bval="(?P<color>[0-9A-Fa-f]{6})"')
21
+
22
+ _OFFICE_DEFAULTS = {
23
+ "dk1": "000000",
24
+ "lt1": "FFFFFF",
25
+ "dk2": "1F497D",
26
+ "lt2": "EEECE1",
27
+ "accent1": "4F81BD",
28
+ "accent2": "C0504D",
29
+ "accent3": "9BBB59",
30
+ "accent4": "8064A2",
31
+ "accent5": "4BACC6",
32
+ "accent6": "F79646",
33
+ "hlink": "0000FF",
34
+ "folHlink": "800080",
35
+ }
36
+ _ROLE_SLOTS = {
37
+ "bg": "lt1",
38
+ "background": "lt1",
39
+ "master_bg": "lt1",
40
+ "secondary_bg": "lt2",
41
+ "bg_secondary": "lt2",
42
+ "text": "dk1",
43
+ "body_text": "dk1",
44
+ "text_secondary": "dk2",
45
+ "primary": "accent1",
46
+ "accent": "accent2",
47
+ "secondary_accent": "accent3",
48
+ "border": "accent4",
49
+ }
50
+ _USAGE_ROLE_ORDER = {
51
+ "background": (
52
+ "bg", "background", "master_bg", "secondary_bg", "bg_secondary",
53
+ "primary", "accent", "secondary_accent",
54
+ ),
55
+ "fill": (
56
+ "primary", "accent", "secondary_accent", "bg", "background",
57
+ "master_bg", "secondary_bg", "bg_secondary", "text", "body_text",
58
+ "text_secondary", "border",
59
+ ),
60
+ "text": (
61
+ "text", "body_text", "text_secondary", "primary", "accent",
62
+ "secondary_accent",
63
+ ),
64
+ "stroke": (
65
+ "border", "primary", "accent", "secondary_accent", "text",
66
+ "body_text", "text_secondary",
67
+ ),
68
+ "chart": ("primary", "accent", "secondary_accent"),
69
+ }
70
+ _BACKGROUND_ROLE_TOKENS = (
71
+ "bg", "background", "surface", "paper", "card", "panel", "tint",
72
+ )
73
+ _TEXT_ROLE_TOKENS = ("text", "ink", "muted")
74
+ _STROKE_ROLE_TOKENS = ("border", "grid", "line", "stroke")
75
+ _BACKGROUND_USAGES = frozenset({"background", "fill"})
76
+ _TEXT_USAGES = frozenset({"text"})
77
+ _STROKE_USAGES = frozenset({"stroke", "fill"})
78
+ _SEMANTIC_USAGES = frozenset({"fill", "text", "stroke"})
79
+
80
+
81
+ class ThemeColorError(RuntimeError):
82
+ """Raised when a project theme-color contract cannot be loaded or applied."""
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class ThemeColorSpec:
87
+ """PowerPoint color scheme derived from one project's color lock."""
88
+
89
+ slots: dict[str, str]
90
+ roles: dict[str, str]
91
+ role_slots: dict[str, str]
92
+ extra_roles: tuple[str, ...] = ()
93
+
94
+ def scheme_for(self, color: str, usage: str) -> str | None:
95
+ """Resolve one concrete color to a safe scheme slot for its usage."""
96
+ normalized = parse_hex_color(color)
97
+ if normalized is None:
98
+ return None
99
+ for role in _USAGE_ROLE_ORDER.get(usage, ()):
100
+ if self.roles.get(role) == normalized:
101
+ slot = self.role_slots[role]
102
+ if self.slots.get(slot) == normalized:
103
+ return slot
104
+ for role in self.extra_roles:
105
+ if usage in _extra_role_usages(role) and self.roles.get(role) == normalized:
106
+ slot = self.role_slots[role]
107
+ if self.slots.get(slot) == normalized:
108
+ return slot
109
+ return None
110
+
111
+
112
+ def _extra_role_usages(role: str) -> frozenset[str]:
113
+ """Limit extra theme slots to contexts implied by their lock role name."""
114
+ normalized = role.lower()
115
+ if any(token in normalized for token in _BACKGROUND_ROLE_TOKENS):
116
+ return _BACKGROUND_USAGES
117
+ if any(token in normalized for token in _TEXT_ROLE_TOKENS):
118
+ return _TEXT_USAGES
119
+ if any(token in normalized for token in _STROKE_ROLE_TOKENS):
120
+ return _STROKE_USAGES
121
+ return _SEMANTIC_USAGES
122
+
123
+
124
+ def _color_rows(lock_path: Path) -> dict[str, str]:
125
+ rows: dict[str, str] = {}
126
+ current_section: str | None = None
127
+ try:
128
+ lines = lock_path.read_text(encoding="utf-8").splitlines()
129
+ except OSError as exc:
130
+ raise ThemeColorError(f"Cannot read {lock_path}: {exc}") from exc
131
+ for raw_line in lines:
132
+ line = raw_line.strip()
133
+ if line.startswith("## "):
134
+ current_section = line[3:].strip()
135
+ continue
136
+ if current_section != "colors":
137
+ continue
138
+ match = _LOCK_ROW_RE.fullmatch(line)
139
+ if not match:
140
+ continue
141
+ raw_color = match.group(2).strip()
142
+ if (
143
+ len(raw_color) >= 2
144
+ and raw_color[0] == raw_color[-1]
145
+ and raw_color[0] in {'"', "'"}
146
+ ):
147
+ raw_color = raw_color[1:-1].strip()
148
+ color = parse_hex_color(raw_color)
149
+ if color is not None:
150
+ rows[match.group(1)] = color
151
+ return rows
152
+
153
+
154
+ def _first_color(roles: dict[str, str], *keys: str, default: str) -> str:
155
+ return next((roles[key] for key in keys if key in roles), default)
156
+
157
+
158
+ def load_theme_color_spec(project_path: Path) -> ThemeColorSpec | None:
159
+ """Load a PowerPoint color scheme from ``spec_lock.md`` color rows."""
160
+ lock_path = project_path / "spec_lock.md"
161
+ if not lock_path.is_file():
162
+ return None
163
+ roles = _color_rows(lock_path)
164
+ if not roles:
165
+ return None
166
+
167
+ extra_roles = tuple(
168
+ key
169
+ for key, color in roles.items()
170
+ if key not in _ROLE_SLOTS and color not in {"000000", "FFFFFF"}
171
+ )[:2]
172
+ extra_slots = dict(zip(extra_roles, ("accent5", "accent6")))
173
+ role_slots = {**_ROLE_SLOTS, **extra_slots}
174
+
175
+ slots = dict(_OFFICE_DEFAULTS)
176
+ slots.update({
177
+ "lt1": _first_color(
178
+ roles,
179
+ "bg", "background", "master_bg",
180
+ default=slots["lt1"],
181
+ ),
182
+ "dk1": _first_color(
183
+ roles,
184
+ "text", "body_text", "primary",
185
+ default=slots["dk1"],
186
+ ),
187
+ "lt2": _first_color(
188
+ roles,
189
+ "secondary_bg", "bg_secondary", "bg", "background", "master_bg",
190
+ default=slots["lt2"],
191
+ ),
192
+ "dk2": _first_color(roles, "text_secondary", "text", default=slots["dk2"]),
193
+ "accent1": _first_color(roles, "primary", "accent", default=slots["accent1"]),
194
+ "accent2": _first_color(
195
+ roles,
196
+ "accent", "secondary_accent", "primary",
197
+ default=slots["accent2"],
198
+ ),
199
+ "accent3": _first_color(roles, "secondary_accent", "accent", default=slots["accent3"]),
200
+ "accent4": _first_color(roles, "border", "primary", default=slots["accent4"]),
201
+ "hlink": _first_color(roles, "accent", "primary", default=slots["hlink"]),
202
+ "folHlink": _first_color(roles, "secondary_accent", "accent", default=slots["folHlink"]),
203
+ })
204
+ for role, slot in extra_slots.items():
205
+ slots[slot] = roles[role]
206
+ return ThemeColorSpec(
207
+ slots=slots,
208
+ roles=roles,
209
+ role_slots=role_slots,
210
+ extra_roles=extra_roles,
211
+ )
212
+
213
+
214
+ def color_node_xml(
215
+ color: str,
216
+ spec: ThemeColorSpec | None,
217
+ usage: str,
218
+ inner_xml: str = "",
219
+ ) -> str:
220
+ """Build an srgbClr or schemeClr node while preserving child transforms."""
221
+ normalized = parse_hex_color(color) or color.strip().lstrip("#").upper()
222
+ scheme = spec.scheme_for(normalized, usage) if spec is not None else None
223
+ if scheme:
224
+ return f'<a:schemeClr val="{scheme}">{inner_xml}</a:schemeClr>'
225
+ return f'<a:srgbClr val="{normalized}">{inner_xml}</a:srgbClr>'
226
+
227
+
228
+ def _set_scheme_color(parent: ET.Element, slot: str, color: str) -> None:
229
+ target = parent.find(f"{{{DML_NS}}}{slot}")
230
+ if target is None:
231
+ target = ET.SubElement(parent, f"{{{DML_NS}}}{slot}")
232
+ for child in list(target):
233
+ target.remove(child)
234
+ ET.SubElement(target, f"{{{DML_NS}}}srgbClr", {"val": color})
235
+
236
+
237
+ def apply_theme_color_spec(extract_dir: Path, spec: ThemeColorSpec) -> None:
238
+ """Install the locked color scheme into every existing PPTX theme part."""
239
+ theme_dir = extract_dir / "ppt" / "theme"
240
+ theme_paths = sorted(theme_dir.glob("theme*.xml"))
241
+ if not theme_paths:
242
+ raise ThemeColorError(f"PPTX package has no theme part under {theme_dir}")
243
+
244
+ ET.register_namespace("a", DML_NS)
245
+ for theme_path in theme_paths:
246
+ try:
247
+ tree = ET.parse(theme_path)
248
+ except (OSError, ET.ParseError) as exc:
249
+ raise ThemeColorError(f"Cannot parse {theme_path}: {exc}") from exc
250
+ color_scheme = tree.getroot().find(f".//{{{DML_NS}}}clrScheme")
251
+ if color_scheme is None:
252
+ raise ThemeColorError(f"Theme has no clrScheme: {theme_path}")
253
+ color_scheme.set("name", "PPT Master")
254
+ for slot, color in spec.slots.items():
255
+ _set_scheme_color(color_scheme, slot, color)
256
+ tree.write(theme_path, encoding="utf-8", xml_declaration=True)
257
+
258
+
259
+ def rewrite_chart_accent_colors(data: bytes, spec: ThemeColorSpec | None) -> bytes:
260
+ """Promote exact locked accent colors inside native chart XML."""
261
+ if spec is None or b"<a:srgbClr" not in data:
262
+ return data
263
+ try:
264
+ text = data.decode("utf-8")
265
+ except UnicodeDecodeError:
266
+ return data
267
+
268
+ def replacement(match: re.Match[str], *, paired: bool) -> str:
269
+ attrs = match.group("attrs")
270
+ value_match = _VAL_RE.search(attrs)
271
+ if value_match is None:
272
+ return match.group(0)
273
+ scheme = spec.scheme_for(value_match.group("color"), "chart")
274
+ if scheme is None:
275
+ return match.group(0)
276
+ new_attrs = _VAL_RE.sub(f'val="{scheme}"', attrs, count=1)
277
+ if paired:
278
+ return f'<a:schemeClr{new_attrs}>{match.group("body")}</a:schemeClr>'
279
+ return f'<a:schemeClr{new_attrs}/>'
280
+
281
+ text = _SRGB_PAIR_RE.sub(lambda match: replacement(match, paired=True), text)
282
+ text = _SRGB_EMPTY_RE.sub(lambda match: replacement(match, paired=False), text)
283
+ return text.encode("utf-8")
@@ -0,0 +1,330 @@
1
+ """Theme typography contracts shared by SVG conversion and PPTX assembly."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from xml.etree import ElementTree as ET
9
+
10
+ from .utils import font_px_to_hpt, parse_font_family
11
+
12
+
13
+ DML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
14
+ PML_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"
15
+ _LOCK_ROW_RE = re.compile(r"^-\s+([A-Za-z0-9_]+)\s*:\s*(.+?)\s*$")
16
+ _CJK_THEME_SCRIPTS = frozenset({"Hans", "Hant", "Jpan", "Hang"})
17
+
18
+
19
+ class ThemeFontError(RuntimeError):
20
+ """Raised when a project theme-font contract cannot be loaded or applied."""
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ThemeFontFace:
25
+ """Concrete Latin, East Asian, and complex-script theme faces."""
26
+
27
+ latin: str
28
+ ea: str
29
+ cs: str
30
+
31
+ def matches(self, fonts: dict[str, str]) -> bool:
32
+ """Return whether resolved SVG fonts represent this theme face."""
33
+ return fonts.get("latin") == self.latin and fonts.get("ea") == self.ea
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class ThemeFontSpec:
38
+ """Major/minor theme fonts derived from one project's typography lock."""
39
+
40
+ major: ThemeFontFace
41
+ minor: ThemeFontFace
42
+ major_family: str
43
+ minor_family: str
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class MasterTextStyleSpec:
48
+ """Title/body defaults written to one generated slide master's txStyles."""
49
+
50
+ title_hpt: int
51
+ body_hpt: int
52
+
53
+ @property
54
+ def body_levels_hpt(self) -> tuple[int, ...]:
55
+ """Return a deterministic nine-level PowerPoint body-size hierarchy."""
56
+ factors = (16, 15, 14, 13, 12, 11, 10, 9, 8)
57
+ minimum = min(self.body_hpt, 800)
58
+ sizes = []
59
+ for factor in factors:
60
+ scaled = round((self.body_hpt * factor / 16) / 50) * 50
61
+ sizes.append(max(minimum, scaled))
62
+ return tuple(sizes)
63
+
64
+
65
+ def _font_face(font_family: str) -> ThemeFontFace:
66
+ fonts = parse_font_family(font_family)
67
+ return ThemeFontFace(
68
+ latin=fonts["latin"],
69
+ ea=fonts["ea"],
70
+ cs=fonts["latin"],
71
+ )
72
+
73
+
74
+ def _typography_rows(lock_path: Path) -> dict[str, str]:
75
+ rows: dict[str, str] = {}
76
+ current_section: str | None = None
77
+ try:
78
+ lines = lock_path.read_text(encoding="utf-8").splitlines()
79
+ except OSError as exc:
80
+ raise ThemeFontError(f"Cannot read {lock_path}: {exc}") from exc
81
+
82
+ for raw_line in lines:
83
+ line = raw_line.strip()
84
+ if line.startswith("## "):
85
+ current_section = line[3:].strip()
86
+ continue
87
+ if current_section != "typography":
88
+ continue
89
+ match = _LOCK_ROW_RE.fullmatch(line)
90
+ if match:
91
+ rows[match.group(1)] = match.group(2)
92
+ return rows
93
+
94
+
95
+ def load_theme_font_spec(project_path: Path) -> ThemeFontSpec | None:
96
+ """Load major/minor theme fonts from ``spec_lock.md`` typography rows."""
97
+ lock_path = project_path / "spec_lock.md"
98
+ if not lock_path.is_file():
99
+ return None
100
+ rows = _typography_rows(lock_path)
101
+ default_family = rows.get("font_family")
102
+ major_family = rows.get("title_family") or default_family
103
+ minor_family = rows.get("body_family") or default_family
104
+ if not major_family or not minor_family:
105
+ return None
106
+ return ThemeFontSpec(
107
+ major=_font_face(major_family),
108
+ minor=_font_face(minor_family),
109
+ major_family=major_family,
110
+ minor_family=minor_family,
111
+ )
112
+
113
+
114
+ def _font_size_hpt(raw: str, field: str) -> int:
115
+ try:
116
+ px = float(raw)
117
+ except (TypeError, ValueError, OverflowError) as exc:
118
+ raise ThemeFontError(
119
+ f"spec_lock.md typography {field} must be a numeric px value: {raw!r}"
120
+ ) from exc
121
+ try:
122
+ size = font_px_to_hpt(px)
123
+ except ValueError as exc:
124
+ raise ThemeFontError(
125
+ f"spec_lock.md typography {field} is outside the PowerPoint "
126
+ f"font-size range: {raw!r}"
127
+ ) from exc
128
+ return size
129
+
130
+
131
+ def load_master_text_style_spec(project_path: Path) -> MasterTextStyleSpec:
132
+ """Load required title/body defaults for generated Master text styles."""
133
+ lock_path = project_path / "spec_lock.md"
134
+ if not lock_path.is_file():
135
+ raise ThemeFontError(
136
+ "Master export requires spec_lock.md typography title and body rows"
137
+ )
138
+ rows = _typography_rows(lock_path)
139
+ missing = [field for field in ("title", "body") if field not in rows]
140
+ if missing:
141
+ raise ThemeFontError(
142
+ "Master export requires spec_lock.md typography rows: "
143
+ + ", ".join(missing)
144
+ )
145
+ return MasterTextStyleSpec(
146
+ title_hpt=_font_size_hpt(rows["title"], "title"),
147
+ body_hpt=_font_size_hpt(rows["body"], "body"),
148
+ )
149
+
150
+
151
+ def theme_font_tokens(
152
+ fonts: dict[str, str],
153
+ spec: ThemeFontSpec | None,
154
+ ) -> dict[str, str] | None:
155
+ """Return DrawingML major/minor tokens for a locked SVG font face."""
156
+ if spec is None:
157
+ return None
158
+ major_match = spec.major.matches(fonts)
159
+ minor_match = spec.minor.matches(fonts)
160
+ if major_match and not minor_match:
161
+ prefix = "+mj"
162
+ elif minor_match:
163
+ # When title/body use the same family, minor is the least surprising
164
+ # default for ordinary text boxes. Template assembly forces semantic
165
+ # title placeholders to the major role after SVG conversion.
166
+ prefix = "+mn"
167
+ else:
168
+ return None
169
+ return {
170
+ "latin": f"{prefix}-lt",
171
+ "ea": f"{prefix}-ea",
172
+ "cs": f"{prefix}-cs",
173
+ }
174
+
175
+
176
+ def _patch_font_collection(collection: ET.Element, face: ThemeFontFace) -> None:
177
+ for tag, value in (("latin", face.latin), ("ea", face.ea), ("cs", face.cs)):
178
+ elem = collection.find(f"{{{DML_NS}}}{tag}")
179
+ if elem is None:
180
+ elem = ET.SubElement(collection, f"{{{DML_NS}}}{tag}")
181
+ elem.set("typeface", value)
182
+ for supplemental in collection.findall(f"{{{DML_NS}}}font"):
183
+ if supplemental.get("script") in _CJK_THEME_SCRIPTS:
184
+ supplemental.set("typeface", face.ea)
185
+
186
+
187
+ def apply_theme_font_spec(extract_dir: Path, spec: ThemeFontSpec) -> None:
188
+ """Install locked major/minor fonts into every existing PPTX theme part."""
189
+ theme_dir = extract_dir / "ppt" / "theme"
190
+ theme_paths = sorted(theme_dir.glob("theme*.xml"))
191
+ if not theme_paths:
192
+ raise ThemeFontError(f"PPTX package has no theme part under {theme_dir}")
193
+
194
+ ET.register_namespace("a", DML_NS)
195
+ for theme_path in theme_paths:
196
+ try:
197
+ tree = ET.parse(theme_path)
198
+ except (OSError, ET.ParseError) as exc:
199
+ raise ThemeFontError(f"Cannot parse {theme_path}: {exc}") from exc
200
+ font_scheme = tree.getroot().find(f".//{{{DML_NS}}}fontScheme")
201
+ if font_scheme is None:
202
+ raise ThemeFontError(f"Theme has no fontScheme: {theme_path}")
203
+ major = font_scheme.find(f"{{{DML_NS}}}majorFont")
204
+ minor = font_scheme.find(f"{{{DML_NS}}}minorFont")
205
+ if major is None or minor is None:
206
+ raise ThemeFontError(f"Theme has no major/minor font collection: {theme_path}")
207
+ font_scheme.set("name", "PPT Master")
208
+ _patch_font_collection(major, spec.major)
209
+ _patch_font_collection(minor, spec.minor)
210
+ tree.write(theme_path, encoding="utf-8", xml_declaration=True)
211
+
212
+
213
+ def _style_run_properties(style: ET.Element, label: str) -> list[ET.Element]:
214
+ run_properties = list(style.iter(f"{{{DML_NS}}}defRPr"))
215
+ if not run_properties:
216
+ raise ThemeFontError(f"slide master {label} has no a:defRPr entries")
217
+ return run_properties
218
+
219
+
220
+ def _style_level_run_properties(
221
+ style: ET.Element,
222
+ label: str,
223
+ ) -> tuple[ET.Element, ...]:
224
+ """Return direct level 1-9 defaults from one Master text style."""
225
+ levels: list[ET.Element] = []
226
+ for level in range(1, 10):
227
+ run_properties = style.find(
228
+ f"{{{DML_NS}}}lvl{level}pPr/{{{DML_NS}}}defRPr"
229
+ )
230
+ if run_properties is None:
231
+ raise ThemeFontError(
232
+ f"slide master {label} has no level-{level} a:defRPr"
233
+ )
234
+ levels.append(run_properties)
235
+ return tuple(levels)
236
+
237
+
238
+ def apply_master_text_style_spec(
239
+ extract_dir: Path,
240
+ spec: MasterTextStyleSpec,
241
+ ) -> int:
242
+ """Install declared title/body anchors into generated slide-master txStyles."""
243
+ master_dir = extract_dir / "ppt" / "slideMasters"
244
+ master_paths = sorted(master_dir.glob("slideMaster*.xml"))
245
+ if not master_paths:
246
+ raise ThemeFontError(f"PPTX package has no slide master under {master_dir}")
247
+
248
+ ET.register_namespace("a", DML_NS)
249
+ ET.register_namespace("p", PML_NS)
250
+ for master_path in master_paths:
251
+ try:
252
+ tree = ET.parse(master_path)
253
+ except (OSError, ET.ParseError) as exc:
254
+ raise ThemeFontError(f"Cannot parse {master_path}: {exc}") from exc
255
+ text_styles = tree.getroot().find(f"{{{PML_NS}}}txStyles")
256
+ if text_styles is None:
257
+ raise ThemeFontError(f"Slide master has no p:txStyles: {master_path}")
258
+
259
+ title_style = text_styles.find(f"{{{PML_NS}}}titleStyle")
260
+ if title_style is None:
261
+ raise ThemeFontError(
262
+ f"Slide master has no p:titleStyle: {master_path}"
263
+ )
264
+ for run_properties in _style_run_properties(
265
+ title_style,
266
+ "p:titleStyle",
267
+ ):
268
+ run_properties.set("sz", str(spec.title_hpt))
269
+
270
+ body_levels = spec.body_levels_hpt
271
+ for style_name in ("bodyStyle", "otherStyle"):
272
+ style = text_styles.find(f"{{{PML_NS}}}{style_name}")
273
+ if style is None:
274
+ raise ThemeFontError(
275
+ f"Slide master has no p:{style_name}: {master_path}"
276
+ )
277
+ for run_properties, size in zip(
278
+ _style_level_run_properties(
279
+ style,
280
+ f"p:{style_name}",
281
+ ),
282
+ body_levels,
283
+ ):
284
+ run_properties.set("sz", str(size))
285
+
286
+ style_sizes = (
287
+ ("titleStyle", (spec.title_hpt,)),
288
+ ("bodyStyle", body_levels),
289
+ ("otherStyle", body_levels),
290
+ )
291
+
292
+ tree.write(master_path, encoding="utf-8", xml_declaration=True)
293
+
294
+ try:
295
+ read_back = ET.parse(master_path).getroot()
296
+ except (OSError, ET.ParseError) as exc:
297
+ raise ThemeFontError(
298
+ f"Cannot read back slide master {master_path}: {exc}"
299
+ ) from exc
300
+ read_back_styles = read_back.find(f"{{{PML_NS}}}txStyles")
301
+ if read_back_styles is None:
302
+ raise ThemeFontError(
303
+ f"Slide master lost p:txStyles after update: {master_path}"
304
+ )
305
+ for style_name, expected_sizes in style_sizes:
306
+ style = read_back_styles.find(f"{{{PML_NS}}}{style_name}")
307
+ if style is None:
308
+ actual_sizes: tuple[str | None, ...] = ()
309
+ elif style_name == "titleStyle":
310
+ actual_sizes = tuple(
311
+ item.get("sz")
312
+ for item in _style_run_properties(
313
+ style,
314
+ f"p:{style_name}",
315
+ )
316
+ )
317
+ else:
318
+ actual_sizes = tuple(
319
+ item.get("sz")
320
+ for item in _style_level_run_properties(
321
+ style,
322
+ f"p:{style_name}",
323
+ )
324
+ )
325
+ if actual_sizes != tuple(str(size) for size in expected_sizes):
326
+ raise ThemeFontError(
327
+ f"Slide master p:{style_name} size read-back failed: "
328
+ f"{master_path}"
329
+ )
330
+ return len(master_paths)