@hfyjq/crannia 1.0.0 → 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 (221) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +45 -45
  3. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  4. package/THIRD-PARTY-PYTHON.md +162 -153
  5. package/THIRD-PARTY.md +316 -316
  6. package/apps/desktop/quotes.txt +56 -56
  7. package/bus/core.py +671 -671
  8. package/bus/loaders/channel_loader.py +64 -64
  9. package/bus/loaders/skill_md.py +676 -676
  10. package/bus/skill_state.py +124 -124
  11. package/channels/cli_channel/manifest.yaml +5 -5
  12. package/channels/dingtalk_channel/manifest.yaml +12 -12
  13. package/channels/feishu_channel/manifest.yaml +12 -12
  14. package/channels/qq_bot_channel/__init__.py +1 -1
  15. package/channels/qq_bot_channel/handler.py +881 -881
  16. package/channels/qq_bot_channel/manifest.yaml +4 -4
  17. package/channels/telegram_channel/__init__.py +1 -1
  18. package/channels/telegram_channel/handler.py +813 -813
  19. package/channels/telegram_channel/manifest.yaml +4 -4
  20. package/channels/telegram_channel/media.py +231 -231
  21. package/channels/textfmt.py +58 -58
  22. package/channels/wechat_channel/__init__.py +1 -1
  23. package/channels/wechat_channel/auth.py +23 -5
  24. package/channels/wechat_channel/manifest.yaml +5 -5
  25. package/channels/wechat_channel/media.py +178 -178
  26. package/config.yaml +2 -2
  27. package/core/activity.py +3 -0
  28. package/core/agent_loop.py +390 -55
  29. package/core/approval.py +17 -6
  30. package/core/artifacts.py +7 -0
  31. package/core/auto_review.py +23 -5
  32. package/core/channel_configs.py +34 -2
  33. package/core/channel_turns.py +759 -759
  34. package/core/child_approval.py +150 -0
  35. package/core/config_requirements.py +205 -0
  36. package/core/cron/runner.py +118 -6
  37. package/core/cron/store.py +14 -5
  38. package/core/cron/tools.py +17 -5
  39. package/core/endpoint.py +141 -0
  40. package/core/events.py +23 -0
  41. package/core/i18n.py +329 -329
  42. package/core/ice/store.py +191 -191
  43. package/core/inbound.py +193 -193
  44. package/core/jobs.py +19 -3
  45. package/core/last_good.py +150 -150
  46. package/core/llm_errors.py +227 -227
  47. package/core/llm_retry.py +230 -230
  48. package/core/memory/compressor.py +1214 -1214
  49. package/core/memory/manager.py +14 -0
  50. package/core/model_configs.py +80 -0
  51. package/core/pipeline/scheduler.py +2 -2
  52. package/core/pipeline/stages/agent_loop.py +24 -4
  53. package/core/pipeline/stages/pre_process.py +58 -7
  54. package/core/prompt_assembler.py +680 -680
  55. package/core/rg.py +255 -255
  56. package/core/security.py +1544 -1544
  57. package/core/settings_baseline.py +70 -1
  58. package/core/shell.py +5 -17
  59. package/core/skill_settings.py +7 -2
  60. package/core/state_registry.py +19 -0
  61. package/core/subagent.py +64 -3
  62. package/core/task_tool.py +1 -1
  63. package/core/tasks_notify.py +69 -4
  64. package/core/tiers.py +9 -3
  65. package/core/tool_outcome.py +108 -0
  66. package/core/update_tui.py +158 -0
  67. package/core/version.py +2 -2
  68. package/core/web_cache.py +152 -0
  69. package/crannia_tray.py +278 -278
  70. package/creators/models.json +4 -4
  71. package/data/settings.example.json +67 -0
  72. package/licenses/GPL-3.0.txt +619 -619
  73. package/licenses/LGPL-2.1.txt +502 -502
  74. package/licenses/LGPL-3.0.txt +165 -165
  75. package/licenses/MIT-chat-on-wechat.txt +18 -18
  76. package/licenses/MIT-deepseek-harness.txt +21 -21
  77. package/licenses/Molio-LICENSE.txt +44 -44
  78. package/locales/en.json +9 -4
  79. package/main.py +154 -154
  80. package/mcpx/manager.py +522 -522
  81. package/mcpx/servers/__init__.py +22 -22
  82. package/mcpx/servers/web_search.py +321 -33
  83. package/package.json +14 -9
  84. package/providers/anthropic/client.py +772 -772
  85. package/providers/cost_table.json +3779 -3779
  86. package/providers/deepseek/client.py +20 -20
  87. package/providers/deepseek/manifest.yaml +2 -2
  88. package/providers/factory.py +136 -136
  89. package/providers/lmstudio/client.py +2 -2
  90. package/providers/metadata.py +80 -80
  91. package/providers/model_capabilities.json +6665 -6665
  92. package/providers/moonshot/client.py +12 -12
  93. package/providers/ollama/client.py +2 -2
  94. package/providers/openai/client.py +13 -13
  95. package/providers/openrouter/client.py +2 -2
  96. package/providers/qwen/__init__.py +1 -1
  97. package/providers/qwen/client.py +2 -2
  98. package/providers/qwen/manifest.yaml +16 -16
  99. package/providers/rate_limiter.py +144 -144
  100. package/providers/siliconflow/client.py +2 -2
  101. package/providers/validation.py +171 -171
  102. package/providers/window_table.json +8909 -8909
  103. package/sbom.json +4413 -4296
  104. package/skills/entertainment/SKILL.md +35 -35
  105. package/skills/entertainment/__init__.py +1 -1
  106. package/skills/entertainment/handler.py +91 -91
  107. package/skills/entertainment/manifest.yaml +26 -26
  108. package/skills/file_parser/GUIDANCE.md +10 -10
  109. package/skills/file_parser/handler.py +177 -4
  110. package/skills/file_parser/manifest.yaml +22 -1
  111. package/skills/github/SKILL.md +32 -32
  112. package/skills/github/__init__.py +1 -1
  113. package/skills/github/manifest.yaml +5 -0
  114. package/skills/mail_parser/SKILL.md +68 -68
  115. package/skills/mail_parser/__init__.py +1 -1
  116. package/skills/mail_parser/handler.py +806 -806
  117. package/skills/mail_parser/manifest.yaml +5 -0
  118. package/skills/media_gen/GUIDANCE.md +19 -19
  119. package/skills/media_gen/SKILL.md +43 -43
  120. package/skills/media_gen/__init__.py +1 -1
  121. package/skills/media_gen/handler.py +430 -430
  122. package/skills/media_gen/manifest.yaml +93 -88
  123. package/skills/office_parser/cell_validation.py +127 -127
  124. package/skills/office_parser/excel_transform.py +936 -936
  125. package/skills/office_parser/layout_spec.py +243 -243
  126. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  127. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  128. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  129. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
  130. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  131. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
  132. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  133. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  134. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  135. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  136. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  137. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  138. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  139. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  140. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
  141. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  142. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
  143. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  144. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  145. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  146. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  147. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
  148. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  149. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  150. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  151. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  152. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  153. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  154. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  155. package/skills/office_parser/references/layout_library.md +816 -816
  156. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  157. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  158. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  159. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  160. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  161. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  162. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  163. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  164. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  165. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  166. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  167. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  168. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  169. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  170. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  171. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  172. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  173. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  174. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  175. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  176. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  177. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  178. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  179. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  180. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  181. package/skills/office_parser/references/spec_lock.md +235 -235
  182. package/skills/office_parser/soffice.py +68 -68
  183. package/skills/office_parser/word_tools.py +2909 -2909
  184. package/tui/crannia.cmd +134 -0
  185. package/tui/crannia_tui/__init__.py +1 -0
  186. package/tui/crannia_tui/__main__.py +223 -0
  187. package/tui/crannia_tui/app.py +1318 -0
  188. package/tui/crannia_tui/app.tcss +153 -0
  189. package/tui/crannia_tui/approval.py +85 -0
  190. package/tui/crannia_tui/backend.py +279 -0
  191. package/tui/crannia_tui/channel.py +472 -0
  192. package/tui/crannia_tui/client.py +125 -0
  193. package/tui/crannia_tui/clipboard.py +62 -0
  194. package/tui/crannia_tui/commands.py +65 -0
  195. package/tui/crannia_tui/doctor.py +304 -0
  196. package/tui/crannia_tui/events.py +84 -0
  197. package/tui/crannia_tui/headless.py +152 -0
  198. package/tui/crannia_tui/i18n.py +164 -0
  199. package/tui/crannia_tui/locales/en.json +263 -0
  200. package/tui/crannia_tui/outcome.py +62 -0
  201. package/tui/crannia_tui/paths.py +181 -0
  202. package/tui/crannia_tui/probe.py +53 -0
  203. package/tui/crannia_tui/profile.py +169 -0
  204. package/tui/crannia_tui/render.py +209 -0
  205. package/tui/crannia_tui/settings.py +134 -0
  206. package/tui/crannia_tui/setup.py +380 -0
  207. package/tui/crannia_tui/term.py +116 -0
  208. package/tui/crannia_tui/ui.py +1236 -0
  209. package/tui/crannia_tui/update.py +389 -0
  210. package/vendor/ripgrep/COPYING.txt +3 -3
  211. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  212. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  213. package/vendor/ripgrep/README.md +51 -51
  214. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  215. package/vendor/ripgrep/package-source.json +19 -19
  216. package/web/__main__.py +15 -0
  217. package/web/server.py +168 -19
  218. package/web/static/img/channel-telegram.svg +1 -1
  219. package/web/static/img/channel-wechat.svg +1 -1
  220. package/web/templates/logs.html +49 -49
  221. package/web/templates/models.html +46 -46
@@ -1,498 +1,498 @@
1
- #!/usr/bin/env python3
2
- """
3
- SVG Icon Embedding Tool
4
-
5
- Replaces icon placeholders in SVG files with actual icon code.
6
-
7
- Placeholder syntax (new SVGs must include a library prefix):
8
- <use data-icon="chunk-filled/rocket" x="100" y="200" width="48" height="48" fill="#0076A8"/>
9
- <use data-icon="tabler-filled/home" x="100" y="200" width="48" height="48" fill="#0076A8"/>
10
- <use data-icon="tabler-outline/home" x="100" y="200" width="48" height="48" fill="#0076A8"/>
11
- <use data-icon="tabler-outline/home" x="100" y="200" width="48" height="48" fill="#0076A8" stroke-width="3"/>
12
- <use data-icon="layered_slide_06_ill01"/>
13
-
14
- Legacy compatibility accepted by the resolver:
15
- <use data-icon="rocket" .../> -> chunk-filled/rocket
16
- <use data-icon="chunk/rocket" .../> -> chunk-filled/rocket
17
-
18
- Optional `stroke-width` (stroke-style libraries only — e.g. tabler-outline):
19
- Default 2 (matches the source). Pass 1.5 for thin, 3 for bold.
20
- Ignored on fill-style libraries.
21
-
22
- After replacement:
23
- <g transform="translate(100, 200) scale(3)" fill="#0076A8">
24
- <path d="..."/>
25
- </g>
26
-
27
- Icon libraries (subdirectories of templates/icons/):
28
- chunk-filled/ - 640+ fill icons, 16x16 viewBox (use prefix: chunk-filled/name; legacy 'chunk/' also accepted)
29
- tabler-filled/ - 1000+ fill icons, 24x24 viewBox (use prefix: tabler-filled/name)
30
- tabler-outline/ - 5000+ stroke icons, 24x24 viewBox (use prefix: tabler-outline/name)
31
- phosphor-duotone/ - 1200+ duotone icons, 256x256 viewBox (single color + 0.2-opacity backplate)
32
- simple-icons/ - 3400+ brand logos, 24x24 viewBox (brand-inset library — used alongside the chosen primary library, NOT as a standalone library for generic icons)
33
- <asset_id>.svg - project-local extracted vector illustrations with data-icon-style="preserve-color"; preserve source colors and natural viewBox aspect ratio
34
-
35
- Usage:
36
- python3 scripts/svg_finalize/embed_icons.py <svg_file> [svg_file2] ...
37
- python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
38
-
39
- Options:
40
- --icons-dir <path> Icon directory path (default: templates/icons/)
41
- --dry-run Only show what would be replaced, without modifying files
42
- --verbose Show detailed information
43
- """
44
-
45
- from __future__ import annotations
46
-
47
- import os
48
- import re
49
- import sys
50
- import argparse
51
- from pathlib import Path
52
- from xml.etree import ElementTree as ET
53
-
54
- _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
55
- if str(_SCRIPTS_DIR) not in sys.path:
56
- sys.path.insert(0, str(_SCRIPTS_DIR))
57
-
58
- from console_encoding import configure_utf8_stdio # noqa: E402
59
-
60
- configure_utf8_stdio()
61
-
62
-
63
- # Default icon directory
64
- DEFAULT_ICONS_DIR = Path(__file__).parent.parent.parent / 'templates' / 'icons'
65
-
66
- # Icon base size per library
67
- ICON_BASE_SIZES = {
68
- 'chunk-filled': 16,
69
- 'chunk': 16, # backward compat alias → chunk-filled/
70
- 'tabler-filled': 24,
71
- 'tabler-outline': 24,
72
- 'phosphor-duotone': 256,
73
- 'simple-icons': 24,
74
- }
75
- DEFAULT_ICON_BASE_SIZE = 24
76
- BaseGeometry = float | tuple[float, float, float, float]
77
-
78
-
79
- def _get_viewbox_size(content: str) -> float:
80
- """Extract the width from viewBox attribute (assumed square). Returns 0 if not found."""
81
- m = re.search(r'viewBox=["\']0 0 ([\d.]+)', content)
82
- if m:
83
- return float(m.group(1))
84
- return 0
85
-
86
-
87
- def _get_viewbox_geometry(content: str) -> tuple[float, float, float, float] | None:
88
- """Extract full viewBox geometry as (min_x, min_y, width, height)."""
89
- match = re.search(r'viewBox=["\']([^"\']+)["\']', content)
90
- if not match:
91
- return None
92
- parts = re.split(r'[\s,]+', match.group(1).strip())
93
- if len(parts) < 4:
94
- return None
95
- try:
96
- min_x, min_y, width, height = [float(part) for part in parts[:4]]
97
- except ValueError:
98
- return None
99
- if width <= 0 or height <= 0:
100
- return None
101
- return min_x, min_y, width, height
102
-
103
-
104
- def _format_number(value: object) -> str:
105
- """Format SVG numeric values compactly without losing meaningful precision."""
106
- if isinstance(value, float):
107
- return f'{value:g}'
108
- return str(value)
109
-
110
-
111
- def _base_geometry(base_size: BaseGeometry) -> tuple[float, float, float, float]:
112
- """Normalize legacy square icon size and full viewBox geometry."""
113
- if isinstance(base_size, tuple):
114
- return base_size
115
- return 0.0, 0.0, float(base_size), float(base_size)
116
-
117
-
118
- def _is_preserve_color_asset(content: str) -> bool:
119
- """Project illustrations are vector assets, not recolorable monochrome icons.
120
-
121
- The `data-icon-style="preserve-color"` marker is stamped by
122
- extract_svg_assets.py and is the single source of truth — hand-authored
123
- multi-color assets must carry it to keep their colors and aspect ratio.
124
- """
125
- return 'data-icon-style="preserve-color"' in content
126
-
127
-
128
- def _detect_icon_style(content: str) -> str:
129
- """Detect whether an icon is fill-based or stroke-based."""
130
- # stroke="currentColor" with fill="none" → stroke style
131
- if 'stroke="currentColor"' in content and 'fill="none"' in content:
132
- return 'stroke'
133
- return 'fill'
134
-
135
-
136
- def _extract_svg_body(content: str) -> list[str]:
137
- """Return the root SVG body for preserve-color assets without editing attrs."""
138
- match = re.search(r'<svg\b[^>]*>(.*)</svg>\s*$', content, re.DOTALL)
139
- if not match:
140
- return []
141
- body = match.group(1).strip()
142
- return [body] if body else []
143
-
144
-
145
- def _extract_shape_elements(content: str, color: str) -> list[str]:
146
- """
147
- Extract all drawable shape elements from an icon SVG, replacing
148
- fill/stroke color references (currentColor or #xxxxxx) with the target color.
149
-
150
- Supports: <path>, <circle>, <rect>, <line>, <polyline>, <polygon>, <ellipse>
151
- """
152
- shape_tags = ('path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'ellipse')
153
- pattern = r'<(' + '|'.join(shape_tags) + r')(\s[^>]*)?(?:/>|></\1>)'
154
- matches = re.findall(pattern, content, re.DOTALL)
155
-
156
- elements = []
157
- for tag, attrs in matches:
158
- # Remove standalone fill/stroke color attrs so outer <g> controls color.
159
- # Also strip stroke-width so the outer <g> can override it (otherwise the
160
- # icon's source stroke-width="2" would shadow any caller-specified value).
161
- attrs_clean = re.sub(r'\s*fill="(?:currentColor|#[0-9a-fA-F]{3,6}|none)"', '', attrs)
162
- attrs_clean = re.sub(r'\s*stroke="(?:currentColor|#[0-9a-fA-F]{3,6}|none)"', '', attrs_clean)
163
- attrs_clean = re.sub(r'\s*stroke-width="[^"]*"', '', attrs_clean)
164
- elements.append(f'<{tag}{attrs_clean}/>')
165
-
166
- return elements
167
-
168
-
169
- def _resolve_in_dir(icon_name: str, icons_dir: Path) -> tuple[Path, float]:
170
- """Resolve `icon_name` against a single icons dir (no fallback)."""
171
- # Backward compat: 'chunk/name' → 'chunk-filled/name'
172
- _LIB_ALIASES = {'chunk': 'chunk-filled'}
173
-
174
- if '/' in icon_name:
175
- lib, name = icon_name.split('/', 1)
176
- lib = _LIB_ALIASES.get(lib, lib) # resolve aliases
177
- icon_path = icons_dir / lib / f'{name}.svg'
178
- base_size = ICON_BASE_SIZES.get(lib, 24)
179
- else:
180
- # Backward compatibility: un-prefixed names fall back to legacy chunk-filled/ library
181
- icon_path = icons_dir / 'chunk-filled' / f'{icon_name}.svg'
182
- base_size = 16
183
- if not icon_path.exists():
184
- icon_path = icons_dir / f'{icon_name}.svg' # legacy flat layout
185
- base_size = 16
186
-
187
- return icon_path, base_size
188
-
189
-
190
- def resolve_icon_path(icon_name: str, icons_dir: Path, fallback_dir: Path | None = None) -> tuple[Path, float]:
191
- """
192
- Resolve icon name to file path and base size, e.g. "chunk-filled/home" →
193
- icons_dir/chunk-filled/home.svg. "chunk/" is a backward-compat alias; an
194
- un-prefixed name falls back to chunk-filled/ then a legacy flat layout.
195
-
196
- Resolution is project-first: if the icon is absent under `icons_dir` and a
197
- `fallback_dir` (the global library) is given, the fallback's path is
198
- returned instead. Returns (path, base_size); the path may not exist when
199
- neither dir has the icon.
200
- """
201
- icon_path, base_size = _resolve_in_dir(icon_name, icons_dir)
202
- if fallback_dir is not None and not icon_path.exists():
203
- fb_path, fb_size = _resolve_in_dir(icon_name, fallback_dir)
204
- if fb_path.exists():
205
- return fb_path, fb_size
206
- return icon_path, base_size
207
-
208
-
209
- def extract_paths_from_icon(icon_path: Path, target_color: str = '#000000') -> tuple[list[str], str, BaseGeometry]:
210
- """
211
- Extract drawable elements from an icon SVG file.
212
-
213
- Returns:
214
- (elements, style, base_size)
215
- style: 'fill', 'stroke', or 'preserve'
216
- base_size: square icon size, or full viewBox geometry for preserve assets
217
- """
218
- if not icon_path.exists():
219
- return [], 'fill', 16
220
-
221
- content = icon_path.read_text(encoding='utf-8')
222
- if _is_preserve_color_asset(content):
223
- geometry = _get_viewbox_geometry(content) or (0.0, 0.0, DEFAULT_ICON_BASE_SIZE, DEFAULT_ICON_BASE_SIZE)
224
- elements = _extract_svg_body(content)
225
- return elements, 'preserve', geometry
226
-
227
- style = _detect_icon_style(content)
228
- base_size = _get_viewbox_size(content) or 16
229
- elements = _extract_shape_elements(content, target_color)
230
- return elements, style, base_size
231
-
232
-
233
- def _attr_value(tag_text: str, attr: str) -> str | None:
234
- """Return an attribute value from a raw tag, accepting either quote style."""
235
- match = re.search(
236
- rf'\b{re.escape(attr)}\s*=\s*(["\'])(.*?)\1',
237
- tag_text,
238
- re.DOTALL,
239
- )
240
- return match.group(2) if match else None
241
-
242
-
243
- def parse_use_element(use_match: str) -> dict[str, str | float]:
244
- """
245
- Parse attributes of a use element.
246
-
247
- Args:
248
- use_match: Complete string of the use element
249
-
250
- Returns:
251
- Attribute dictionary
252
- """
253
- attrs: dict[str, str | float] = {}
254
-
255
- # Extract data-icon
256
- icon_value = _attr_value(use_match, 'data-icon')
257
- if icon_value:
258
- attrs['icon'] = icon_value
259
-
260
- # Extract numeric attributes
261
- for attr in ['x', 'y', 'width', 'height']:
262
- value = _attr_value(use_match, attr)
263
- if value is not None:
264
- attrs[attr] = float(value)
265
-
266
- # Extract fill color
267
- fill_value = _attr_value(use_match, 'fill')
268
- if fill_value is not None:
269
- attrs['fill'] = fill_value
270
-
271
- # Stroke-style icons may be authored with natural SVG semantics:
272
- # fill="none" stroke="#HEX". Keep accepting fill as the canonical color
273
- # carrier, but preserve stroke so outline icons do not collapse to none.
274
- stroke_value = _attr_value(use_match, 'stroke')
275
- if stroke_value is not None:
276
- attrs['stroke'] = stroke_value
277
-
278
- # Live preview direct edits may write an absolute transform matrix back to
279
- # the placeholder. Preserve it so the expanded icon matches the edited
280
- # browser geometry instead of falling back to the original x/y placement.
281
- transform_value = _attr_value(use_match, 'transform')
282
- if transform_value is not None:
283
- attrs['transform'] = transform_value
284
-
285
- # Extract optional stroke-width override (stroke-style icons only).
286
- # Tabler-outline ships at stroke-width=2; passing 1.5 reads thin, 3 reads bold.
287
- stroke_width_value = _attr_value(use_match, 'stroke-width')
288
- if stroke_width_value is not None:
289
- attrs['stroke-width'] = stroke_width_value
290
-
291
- return attrs
292
-
293
-
294
- def resolve_icon_color(attrs: dict[str, str | float], style: str) -> str:
295
- """Resolve the caller-provided color for fill or stroke icon libraries."""
296
- if style == 'preserve':
297
- return 'preserve'
298
-
299
- fill = str(attrs.get('fill', '')).strip()
300
- stroke = str(attrs.get('stroke', '')).strip()
301
-
302
- if style == 'stroke':
303
- if fill and fill != 'none':
304
- return fill
305
- if stroke and stroke != 'none':
306
- return stroke
307
- return '#000000'
308
-
309
- if fill:
310
- return fill
311
- if stroke and stroke != 'none':
312
- return stroke
313
- return '#000000'
314
-
315
-
316
- def generate_icon_group(attrs: dict[str, str | float], elements: list[str], style: str, base_size: BaseGeometry) -> str:
317
- """
318
- Generate the icon's <g> element.
319
-
320
- Args:
321
- attrs: Attributes of the use element
322
- elements: List of drawable SVG elements
323
- style: 'fill', 'stroke', or 'preserve'
324
- base_size: Icon's natural size, or full viewBox geometry for preserve assets
325
-
326
- Returns:
327
- Complete <g> element string
328
- """
329
- min_x, min_y, base_width, base_height = _base_geometry(base_size)
330
- x = attrs.get('x', 0)
331
- y = attrs.get('y', 0)
332
- width = attrs.get('width', base_width)
333
- height = attrs.get('height', base_height)
334
- color = resolve_icon_color(attrs, style)
335
- icon_name = attrs.get('icon', 'unknown')
336
-
337
- scale_x = float(width) / base_width
338
- scale_y = float(height) / base_height
339
-
340
- if attrs.get('transform'):
341
- # This transform is authoritative: the editor computes it from the
342
- # expanded <g>, so composing it with x/y would apply placement twice.
343
- transform = str(attrs['transform'])
344
- elif abs(scale_x - 1) < 1e-6 and abs(scale_y - 1) < 1e-6:
345
- transform = f'translate({_format_number(x)}, {_format_number(y)})'
346
- elif abs(scale_x - scale_y) < 1e-6:
347
- transform = f'translate({_format_number(x)}, {_format_number(y)}) scale({_format_number(scale_x)})'
348
- else:
349
- transform = (
350
- f'translate({_format_number(x)}, {_format_number(y)}) '
351
- f'scale({_format_number(scale_x)}, {_format_number(scale_y)})'
352
- )
353
-
354
- elements_str = '\n '.join(elements)
355
-
356
- if style == 'preserve':
357
- if min_x or min_y:
358
- inner_transform = f'translate({_format_number(-min_x)}, {_format_number(-min_y)})'
359
- elements_str = f'<g transform="{inner_transform}">\n {elements_str}\n </g>'
360
- return f'''<!-- icon: {icon_name} -->
361
- <g transform="{transform}">
362
- {elements_str}
363
- </g>'''
364
-
365
- if style == 'stroke':
366
- # Default to 2 — matches the source stroke-width baked into tabler-outline
367
- # (and any other stroke library) so omitting the attribute reproduces
368
- # pre-change visual output.
369
- stroke_width = attrs.get('stroke-width', '2')
370
- color_attrs = f'fill="none" stroke="{color}" stroke-width="{stroke_width}"'
371
- else:
372
- color_attrs = f'fill="{color}"'
373
-
374
- return f'''<!-- icon: {icon_name} -->
375
- <g transform="{transform}" {color_attrs}>
376
- {elements_str}
377
- </g>'''
378
-
379
-
380
- def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, verbose: bool = False, fallback_dir: Path | None = None) -> int:
381
- """
382
- Process a single SVG file, replacing all icon placeholders.
383
-
384
- Args:
385
- svg_path: SVG file path
386
- icons_dir: Icon directory path
387
- dry_run: Whether to only preview without modifying
388
- verbose: Whether to show detailed information
389
-
390
- Returns:
391
- Number of icons replaced
392
- """
393
- if not svg_path.exists():
394
- print(f"[ERROR] File not found: {svg_path}")
395
- return 0
396
-
397
- content = svg_path.read_text(encoding='utf-8')
398
-
399
- # Match self-closing <use data-icon="..."/> placeholders. Attribute
400
- # parsing below accepts both single and double quotes.
401
- use_pattern = r'<use\b(?=[^>]*\bdata-icon\s*=)[^>]*/>'
402
- matches = list(re.finditer(use_pattern, content, re.IGNORECASE | re.DOTALL))
403
-
404
- if not matches:
405
- if verbose:
406
- print(f"[SKIP] No icon placeholders: {svg_path}")
407
- return 0
408
-
409
- replaced_count = 0
410
- new_content = content
411
-
412
- # Replace from back to front to avoid position offset
413
- for match in reversed(matches):
414
- use_str = match.group(0)
415
- attrs = parse_use_element(use_str)
416
-
417
- icon_name = attrs.get('icon')
418
- if not icon_name:
419
- continue
420
-
421
- icon_path, _ = resolve_icon_path(str(icon_name), icons_dir, fallback_dir)
422
- elements, style, base_size = extract_paths_from_icon(icon_path)
423
- color = resolve_icon_color(attrs, style)
424
-
425
- if not elements:
426
- print(f"[WARN] Icon not found: {icon_name} (in {svg_path.name})")
427
- continue
428
-
429
- replacement = generate_icon_group(attrs, elements, style, base_size)
430
-
431
- if verbose or dry_run:
432
- print(f" [*] {icon_name}: x={attrs.get('x', 0)}, y={attrs.get('y', 0)}, "
433
- f"size={attrs.get('width', base_size)}, fill={color}, style={style}")
434
-
435
- new_content = new_content[:match.start()] + replacement + new_content[match.end():]
436
- replaced_count += 1
437
-
438
- if not dry_run and replaced_count > 0:
439
- svg_path.write_text(new_content, encoding='utf-8')
440
-
441
- status = "[PREVIEW]" if dry_run else "[OK]"
442
- print(f"{status} {svg_path.name} ({replaced_count} icons)")
443
-
444
- return replaced_count
445
-
446
-
447
- def main() -> None:
448
- """Run the CLI entry point."""
449
- parser = argparse.ArgumentParser(
450
- description='Replace icon placeholders in SVG files with actual icon code',
451
- formatter_class=argparse.RawDescriptionHelpFormatter,
452
- epilog='''
453
- Examples:
454
- python3 scripts/svg_finalize/embed_icons.py svg_output/01_cover.svg
455
- python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
456
- python3 scripts/svg_finalize/embed_icons.py --dry-run svg_output/*.svg
457
- python3 scripts/svg_finalize/embed_icons.py --icons-dir my_icons/ output.svg
458
- '''
459
- )
460
-
461
- parser.add_argument('files', nargs='+', help='SVG files to process')
462
- parser.add_argument('--icons-dir', type=Path, default=DEFAULT_ICONS_DIR,
463
- help=f'Icon directory path (default: {DEFAULT_ICONS_DIR})')
464
- parser.add_argument('--dry-run', action='store_true',
465
- help='Only show what would be replaced, without modifying files')
466
- parser.add_argument('--verbose', '-v', action='store_true',
467
- help='Show detailed information')
468
-
469
- args = parser.parse_args()
470
-
471
- # Validate icon directory
472
- if not args.icons_dir.exists():
473
- print(f"[ERROR] Icon directory not found: {args.icons_dir}")
474
- sys.exit(1)
475
-
476
- print(f"[DIR] Icon directory: {args.icons_dir}")
477
- if args.dry_run:
478
- print("[PREVIEW] Preview mode (no files will be modified)")
479
- print()
480
-
481
- total_replaced = 0
482
- total_files = 0
483
-
484
- for file_pattern in args.files:
485
- svg_path = Path(file_pattern)
486
- if svg_path.exists():
487
- count = process_svg_file(svg_path, args.icons_dir, args.dry_run, args.verbose)
488
- total_replaced += count
489
- if count > 0:
490
- total_files += 1
491
-
492
- print()
493
- print(f"[Summary] Total: {total_files} file(s), {total_replaced} icon(s)" +
494
- (" (preview)" if args.dry_run else " replaced"))
495
-
496
-
497
- if __name__ == '__main__':
498
- main()
1
+ #!/usr/bin/env python3
2
+ """
3
+ SVG Icon Embedding Tool
4
+
5
+ Replaces icon placeholders in SVG files with actual icon code.
6
+
7
+ Placeholder syntax (new SVGs must include a library prefix):
8
+ <use data-icon="chunk-filled/rocket" x="100" y="200" width="48" height="48" fill="#0076A8"/>
9
+ <use data-icon="tabler-filled/home" x="100" y="200" width="48" height="48" fill="#0076A8"/>
10
+ <use data-icon="tabler-outline/home" x="100" y="200" width="48" height="48" fill="#0076A8"/>
11
+ <use data-icon="tabler-outline/home" x="100" y="200" width="48" height="48" fill="#0076A8" stroke-width="3"/>
12
+ <use data-icon="layered_slide_06_ill01"/>
13
+
14
+ Legacy compatibility accepted by the resolver:
15
+ <use data-icon="rocket" .../> -> chunk-filled/rocket
16
+ <use data-icon="chunk/rocket" .../> -> chunk-filled/rocket
17
+
18
+ Optional `stroke-width` (stroke-style libraries only — e.g. tabler-outline):
19
+ Default 2 (matches the source). Pass 1.5 for thin, 3 for bold.
20
+ Ignored on fill-style libraries.
21
+
22
+ After replacement:
23
+ <g transform="translate(100, 200) scale(3)" fill="#0076A8">
24
+ <path d="..."/>
25
+ </g>
26
+
27
+ Icon libraries (subdirectories of templates/icons/):
28
+ chunk-filled/ - 640+ fill icons, 16x16 viewBox (use prefix: chunk-filled/name; legacy 'chunk/' also accepted)
29
+ tabler-filled/ - 1000+ fill icons, 24x24 viewBox (use prefix: tabler-filled/name)
30
+ tabler-outline/ - 5000+ stroke icons, 24x24 viewBox (use prefix: tabler-outline/name)
31
+ phosphor-duotone/ - 1200+ duotone icons, 256x256 viewBox (single color + 0.2-opacity backplate)
32
+ simple-icons/ - 3400+ brand logos, 24x24 viewBox (brand-inset library — used alongside the chosen primary library, NOT as a standalone library for generic icons)
33
+ <asset_id>.svg - project-local extracted vector illustrations with data-icon-style="preserve-color"; preserve source colors and natural viewBox aspect ratio
34
+
35
+ Usage:
36
+ python3 scripts/svg_finalize/embed_icons.py <svg_file> [svg_file2] ...
37
+ python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
38
+
39
+ Options:
40
+ --icons-dir <path> Icon directory path (default: templates/icons/)
41
+ --dry-run Only show what would be replaced, without modifying files
42
+ --verbose Show detailed information
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import os
48
+ import re
49
+ import sys
50
+ import argparse
51
+ from pathlib import Path
52
+ from xml.etree import ElementTree as ET
53
+
54
+ _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
55
+ if str(_SCRIPTS_DIR) not in sys.path:
56
+ sys.path.insert(0, str(_SCRIPTS_DIR))
57
+
58
+ from console_encoding import configure_utf8_stdio # noqa: E402
59
+
60
+ configure_utf8_stdio()
61
+
62
+
63
+ # Default icon directory
64
+ DEFAULT_ICONS_DIR = Path(__file__).parent.parent.parent / 'templates' / 'icons'
65
+
66
+ # Icon base size per library
67
+ ICON_BASE_SIZES = {
68
+ 'chunk-filled': 16,
69
+ 'chunk': 16, # backward compat alias → chunk-filled/
70
+ 'tabler-filled': 24,
71
+ 'tabler-outline': 24,
72
+ 'phosphor-duotone': 256,
73
+ 'simple-icons': 24,
74
+ }
75
+ DEFAULT_ICON_BASE_SIZE = 24
76
+ BaseGeometry = float | tuple[float, float, float, float]
77
+
78
+
79
+ def _get_viewbox_size(content: str) -> float:
80
+ """Extract the width from viewBox attribute (assumed square). Returns 0 if not found."""
81
+ m = re.search(r'viewBox=["\']0 0 ([\d.]+)', content)
82
+ if m:
83
+ return float(m.group(1))
84
+ return 0
85
+
86
+
87
+ def _get_viewbox_geometry(content: str) -> tuple[float, float, float, float] | None:
88
+ """Extract full viewBox geometry as (min_x, min_y, width, height)."""
89
+ match = re.search(r'viewBox=["\']([^"\']+)["\']', content)
90
+ if not match:
91
+ return None
92
+ parts = re.split(r'[\s,]+', match.group(1).strip())
93
+ if len(parts) < 4:
94
+ return None
95
+ try:
96
+ min_x, min_y, width, height = [float(part) for part in parts[:4]]
97
+ except ValueError:
98
+ return None
99
+ if width <= 0 or height <= 0:
100
+ return None
101
+ return min_x, min_y, width, height
102
+
103
+
104
+ def _format_number(value: object) -> str:
105
+ """Format SVG numeric values compactly without losing meaningful precision."""
106
+ if isinstance(value, float):
107
+ return f'{value:g}'
108
+ return str(value)
109
+
110
+
111
+ def _base_geometry(base_size: BaseGeometry) -> tuple[float, float, float, float]:
112
+ """Normalize legacy square icon size and full viewBox geometry."""
113
+ if isinstance(base_size, tuple):
114
+ return base_size
115
+ return 0.0, 0.0, float(base_size), float(base_size)
116
+
117
+
118
+ def _is_preserve_color_asset(content: str) -> bool:
119
+ """Project illustrations are vector assets, not recolorable monochrome icons.
120
+
121
+ The `data-icon-style="preserve-color"` marker is stamped by
122
+ extract_svg_assets.py and is the single source of truth — hand-authored
123
+ multi-color assets must carry it to keep their colors and aspect ratio.
124
+ """
125
+ return 'data-icon-style="preserve-color"' in content
126
+
127
+
128
+ def _detect_icon_style(content: str) -> str:
129
+ """Detect whether an icon is fill-based or stroke-based."""
130
+ # stroke="currentColor" with fill="none" → stroke style
131
+ if 'stroke="currentColor"' in content and 'fill="none"' in content:
132
+ return 'stroke'
133
+ return 'fill'
134
+
135
+
136
+ def _extract_svg_body(content: str) -> list[str]:
137
+ """Return the root SVG body for preserve-color assets without editing attrs."""
138
+ match = re.search(r'<svg\b[^>]*>(.*)</svg>\s*$', content, re.DOTALL)
139
+ if not match:
140
+ return []
141
+ body = match.group(1).strip()
142
+ return [body] if body else []
143
+
144
+
145
+ def _extract_shape_elements(content: str, color: str) -> list[str]:
146
+ """
147
+ Extract all drawable shape elements from an icon SVG, replacing
148
+ fill/stroke color references (currentColor or #xxxxxx) with the target color.
149
+
150
+ Supports: <path>, <circle>, <rect>, <line>, <polyline>, <polygon>, <ellipse>
151
+ """
152
+ shape_tags = ('path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'ellipse')
153
+ pattern = r'<(' + '|'.join(shape_tags) + r')(\s[^>]*)?(?:/>|></\1>)'
154
+ matches = re.findall(pattern, content, re.DOTALL)
155
+
156
+ elements = []
157
+ for tag, attrs in matches:
158
+ # Remove standalone fill/stroke color attrs so outer <g> controls color.
159
+ # Also strip stroke-width so the outer <g> can override it (otherwise the
160
+ # icon's source stroke-width="2" would shadow any caller-specified value).
161
+ attrs_clean = re.sub(r'\s*fill="(?:currentColor|#[0-9a-fA-F]{3,6}|none)"', '', attrs)
162
+ attrs_clean = re.sub(r'\s*stroke="(?:currentColor|#[0-9a-fA-F]{3,6}|none)"', '', attrs_clean)
163
+ attrs_clean = re.sub(r'\s*stroke-width="[^"]*"', '', attrs_clean)
164
+ elements.append(f'<{tag}{attrs_clean}/>')
165
+
166
+ return elements
167
+
168
+
169
+ def _resolve_in_dir(icon_name: str, icons_dir: Path) -> tuple[Path, float]:
170
+ """Resolve `icon_name` against a single icons dir (no fallback)."""
171
+ # Backward compat: 'chunk/name' → 'chunk-filled/name'
172
+ _LIB_ALIASES = {'chunk': 'chunk-filled'}
173
+
174
+ if '/' in icon_name:
175
+ lib, name = icon_name.split('/', 1)
176
+ lib = _LIB_ALIASES.get(lib, lib) # resolve aliases
177
+ icon_path = icons_dir / lib / f'{name}.svg'
178
+ base_size = ICON_BASE_SIZES.get(lib, 24)
179
+ else:
180
+ # Backward compatibility: un-prefixed names fall back to legacy chunk-filled/ library
181
+ icon_path = icons_dir / 'chunk-filled' / f'{icon_name}.svg'
182
+ base_size = 16
183
+ if not icon_path.exists():
184
+ icon_path = icons_dir / f'{icon_name}.svg' # legacy flat layout
185
+ base_size = 16
186
+
187
+ return icon_path, base_size
188
+
189
+
190
+ def resolve_icon_path(icon_name: str, icons_dir: Path, fallback_dir: Path | None = None) -> tuple[Path, float]:
191
+ """
192
+ Resolve icon name to file path and base size, e.g. "chunk-filled/home" →
193
+ icons_dir/chunk-filled/home.svg. "chunk/" is a backward-compat alias; an
194
+ un-prefixed name falls back to chunk-filled/ then a legacy flat layout.
195
+
196
+ Resolution is project-first: if the icon is absent under `icons_dir` and a
197
+ `fallback_dir` (the global library) is given, the fallback's path is
198
+ returned instead. Returns (path, base_size); the path may not exist when
199
+ neither dir has the icon.
200
+ """
201
+ icon_path, base_size = _resolve_in_dir(icon_name, icons_dir)
202
+ if fallback_dir is not None and not icon_path.exists():
203
+ fb_path, fb_size = _resolve_in_dir(icon_name, fallback_dir)
204
+ if fb_path.exists():
205
+ return fb_path, fb_size
206
+ return icon_path, base_size
207
+
208
+
209
+ def extract_paths_from_icon(icon_path: Path, target_color: str = '#000000') -> tuple[list[str], str, BaseGeometry]:
210
+ """
211
+ Extract drawable elements from an icon SVG file.
212
+
213
+ Returns:
214
+ (elements, style, base_size)
215
+ style: 'fill', 'stroke', or 'preserve'
216
+ base_size: square icon size, or full viewBox geometry for preserve assets
217
+ """
218
+ if not icon_path.exists():
219
+ return [], 'fill', 16
220
+
221
+ content = icon_path.read_text(encoding='utf-8')
222
+ if _is_preserve_color_asset(content):
223
+ geometry = _get_viewbox_geometry(content) or (0.0, 0.0, DEFAULT_ICON_BASE_SIZE, DEFAULT_ICON_BASE_SIZE)
224
+ elements = _extract_svg_body(content)
225
+ return elements, 'preserve', geometry
226
+
227
+ style = _detect_icon_style(content)
228
+ base_size = _get_viewbox_size(content) or 16
229
+ elements = _extract_shape_elements(content, target_color)
230
+ return elements, style, base_size
231
+
232
+
233
+ def _attr_value(tag_text: str, attr: str) -> str | None:
234
+ """Return an attribute value from a raw tag, accepting either quote style."""
235
+ match = re.search(
236
+ rf'\b{re.escape(attr)}\s*=\s*(["\'])(.*?)\1',
237
+ tag_text,
238
+ re.DOTALL,
239
+ )
240
+ return match.group(2) if match else None
241
+
242
+
243
+ def parse_use_element(use_match: str) -> dict[str, str | float]:
244
+ """
245
+ Parse attributes of a use element.
246
+
247
+ Args:
248
+ use_match: Complete string of the use element
249
+
250
+ Returns:
251
+ Attribute dictionary
252
+ """
253
+ attrs: dict[str, str | float] = {}
254
+
255
+ # Extract data-icon
256
+ icon_value = _attr_value(use_match, 'data-icon')
257
+ if icon_value:
258
+ attrs['icon'] = icon_value
259
+
260
+ # Extract numeric attributes
261
+ for attr in ['x', 'y', 'width', 'height']:
262
+ value = _attr_value(use_match, attr)
263
+ if value is not None:
264
+ attrs[attr] = float(value)
265
+
266
+ # Extract fill color
267
+ fill_value = _attr_value(use_match, 'fill')
268
+ if fill_value is not None:
269
+ attrs['fill'] = fill_value
270
+
271
+ # Stroke-style icons may be authored with natural SVG semantics:
272
+ # fill="none" stroke="#HEX". Keep accepting fill as the canonical color
273
+ # carrier, but preserve stroke so outline icons do not collapse to none.
274
+ stroke_value = _attr_value(use_match, 'stroke')
275
+ if stroke_value is not None:
276
+ attrs['stroke'] = stroke_value
277
+
278
+ # Live preview direct edits may write an absolute transform matrix back to
279
+ # the placeholder. Preserve it so the expanded icon matches the edited
280
+ # browser geometry instead of falling back to the original x/y placement.
281
+ transform_value = _attr_value(use_match, 'transform')
282
+ if transform_value is not None:
283
+ attrs['transform'] = transform_value
284
+
285
+ # Extract optional stroke-width override (stroke-style icons only).
286
+ # Tabler-outline ships at stroke-width=2; passing 1.5 reads thin, 3 reads bold.
287
+ stroke_width_value = _attr_value(use_match, 'stroke-width')
288
+ if stroke_width_value is not None:
289
+ attrs['stroke-width'] = stroke_width_value
290
+
291
+ return attrs
292
+
293
+
294
+ def resolve_icon_color(attrs: dict[str, str | float], style: str) -> str:
295
+ """Resolve the caller-provided color for fill or stroke icon libraries."""
296
+ if style == 'preserve':
297
+ return 'preserve'
298
+
299
+ fill = str(attrs.get('fill', '')).strip()
300
+ stroke = str(attrs.get('stroke', '')).strip()
301
+
302
+ if style == 'stroke':
303
+ if fill and fill != 'none':
304
+ return fill
305
+ if stroke and stroke != 'none':
306
+ return stroke
307
+ return '#000000'
308
+
309
+ if fill:
310
+ return fill
311
+ if stroke and stroke != 'none':
312
+ return stroke
313
+ return '#000000'
314
+
315
+
316
+ def generate_icon_group(attrs: dict[str, str | float], elements: list[str], style: str, base_size: BaseGeometry) -> str:
317
+ """
318
+ Generate the icon's <g> element.
319
+
320
+ Args:
321
+ attrs: Attributes of the use element
322
+ elements: List of drawable SVG elements
323
+ style: 'fill', 'stroke', or 'preserve'
324
+ base_size: Icon's natural size, or full viewBox geometry for preserve assets
325
+
326
+ Returns:
327
+ Complete <g> element string
328
+ """
329
+ min_x, min_y, base_width, base_height = _base_geometry(base_size)
330
+ x = attrs.get('x', 0)
331
+ y = attrs.get('y', 0)
332
+ width = attrs.get('width', base_width)
333
+ height = attrs.get('height', base_height)
334
+ color = resolve_icon_color(attrs, style)
335
+ icon_name = attrs.get('icon', 'unknown')
336
+
337
+ scale_x = float(width) / base_width
338
+ scale_y = float(height) / base_height
339
+
340
+ if attrs.get('transform'):
341
+ # This transform is authoritative: the editor computes it from the
342
+ # expanded <g>, so composing it with x/y would apply placement twice.
343
+ transform = str(attrs['transform'])
344
+ elif abs(scale_x - 1) < 1e-6 and abs(scale_y - 1) < 1e-6:
345
+ transform = f'translate({_format_number(x)}, {_format_number(y)})'
346
+ elif abs(scale_x - scale_y) < 1e-6:
347
+ transform = f'translate({_format_number(x)}, {_format_number(y)}) scale({_format_number(scale_x)})'
348
+ else:
349
+ transform = (
350
+ f'translate({_format_number(x)}, {_format_number(y)}) '
351
+ f'scale({_format_number(scale_x)}, {_format_number(scale_y)})'
352
+ )
353
+
354
+ elements_str = '\n '.join(elements)
355
+
356
+ if style == 'preserve':
357
+ if min_x or min_y:
358
+ inner_transform = f'translate({_format_number(-min_x)}, {_format_number(-min_y)})'
359
+ elements_str = f'<g transform="{inner_transform}">\n {elements_str}\n </g>'
360
+ return f'''<!-- icon: {icon_name} -->
361
+ <g transform="{transform}">
362
+ {elements_str}
363
+ </g>'''
364
+
365
+ if style == 'stroke':
366
+ # Default to 2 — matches the source stroke-width baked into tabler-outline
367
+ # (and any other stroke library) so omitting the attribute reproduces
368
+ # pre-change visual output.
369
+ stroke_width = attrs.get('stroke-width', '2')
370
+ color_attrs = f'fill="none" stroke="{color}" stroke-width="{stroke_width}"'
371
+ else:
372
+ color_attrs = f'fill="{color}"'
373
+
374
+ return f'''<!-- icon: {icon_name} -->
375
+ <g transform="{transform}" {color_attrs}>
376
+ {elements_str}
377
+ </g>'''
378
+
379
+
380
+ def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, verbose: bool = False, fallback_dir: Path | None = None) -> int:
381
+ """
382
+ Process a single SVG file, replacing all icon placeholders.
383
+
384
+ Args:
385
+ svg_path: SVG file path
386
+ icons_dir: Icon directory path
387
+ dry_run: Whether to only preview without modifying
388
+ verbose: Whether to show detailed information
389
+
390
+ Returns:
391
+ Number of icons replaced
392
+ """
393
+ if not svg_path.exists():
394
+ print(f"[ERROR] File not found: {svg_path}")
395
+ return 0
396
+
397
+ content = svg_path.read_text(encoding='utf-8')
398
+
399
+ # Match self-closing <use data-icon="..."/> placeholders. Attribute
400
+ # parsing below accepts both single and double quotes.
401
+ use_pattern = r'<use\b(?=[^>]*\bdata-icon\s*=)[^>]*/>'
402
+ matches = list(re.finditer(use_pattern, content, re.IGNORECASE | re.DOTALL))
403
+
404
+ if not matches:
405
+ if verbose:
406
+ print(f"[SKIP] No icon placeholders: {svg_path}")
407
+ return 0
408
+
409
+ replaced_count = 0
410
+ new_content = content
411
+
412
+ # Replace from back to front to avoid position offset
413
+ for match in reversed(matches):
414
+ use_str = match.group(0)
415
+ attrs = parse_use_element(use_str)
416
+
417
+ icon_name = attrs.get('icon')
418
+ if not icon_name:
419
+ continue
420
+
421
+ icon_path, _ = resolve_icon_path(str(icon_name), icons_dir, fallback_dir)
422
+ elements, style, base_size = extract_paths_from_icon(icon_path)
423
+ color = resolve_icon_color(attrs, style)
424
+
425
+ if not elements:
426
+ print(f"[WARN] Icon not found: {icon_name} (in {svg_path.name})")
427
+ continue
428
+
429
+ replacement = generate_icon_group(attrs, elements, style, base_size)
430
+
431
+ if verbose or dry_run:
432
+ print(f" [*] {icon_name}: x={attrs.get('x', 0)}, y={attrs.get('y', 0)}, "
433
+ f"size={attrs.get('width', base_size)}, fill={color}, style={style}")
434
+
435
+ new_content = new_content[:match.start()] + replacement + new_content[match.end():]
436
+ replaced_count += 1
437
+
438
+ if not dry_run and replaced_count > 0:
439
+ svg_path.write_text(new_content, encoding='utf-8')
440
+
441
+ status = "[PREVIEW]" if dry_run else "[OK]"
442
+ print(f"{status} {svg_path.name} ({replaced_count} icons)")
443
+
444
+ return replaced_count
445
+
446
+
447
+ def main() -> None:
448
+ """Run the CLI entry point."""
449
+ parser = argparse.ArgumentParser(
450
+ description='Replace icon placeholders in SVG files with actual icon code',
451
+ formatter_class=argparse.RawDescriptionHelpFormatter,
452
+ epilog='''
453
+ Examples:
454
+ python3 scripts/svg_finalize/embed_icons.py svg_output/01_cover.svg
455
+ python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
456
+ python3 scripts/svg_finalize/embed_icons.py --dry-run svg_output/*.svg
457
+ python3 scripts/svg_finalize/embed_icons.py --icons-dir my_icons/ output.svg
458
+ '''
459
+ )
460
+
461
+ parser.add_argument('files', nargs='+', help='SVG files to process')
462
+ parser.add_argument('--icons-dir', type=Path, default=DEFAULT_ICONS_DIR,
463
+ help=f'Icon directory path (default: {DEFAULT_ICONS_DIR})')
464
+ parser.add_argument('--dry-run', action='store_true',
465
+ help='Only show what would be replaced, without modifying files')
466
+ parser.add_argument('--verbose', '-v', action='store_true',
467
+ help='Show detailed information')
468
+
469
+ args = parser.parse_args()
470
+
471
+ # Validate icon directory
472
+ if not args.icons_dir.exists():
473
+ print(f"[ERROR] Icon directory not found: {args.icons_dir}")
474
+ sys.exit(1)
475
+
476
+ print(f"[DIR] Icon directory: {args.icons_dir}")
477
+ if args.dry_run:
478
+ print("[PREVIEW] Preview mode (no files will be modified)")
479
+ print()
480
+
481
+ total_replaced = 0
482
+ total_files = 0
483
+
484
+ for file_pattern in args.files:
485
+ svg_path = Path(file_pattern)
486
+ if svg_path.exists():
487
+ count = process_svg_file(svg_path, args.icons_dir, args.dry_run, args.verbose)
488
+ total_replaced += count
489
+ if count > 0:
490
+ total_files += 1
491
+
492
+ print()
493
+ print(f"[Summary] Total: {total_files} file(s), {total_replaced} icon(s)" +
494
+ (" (preview)" if args.dry_run else " replaced"))
495
+
496
+
497
+ if __name__ == '__main__':
498
+ main()