@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,575 +1,575 @@
1
- #!/usr/bin/env python3
2
- """PPT Master — single-pass image alignment + Base64 embedding.
3
-
4
- Replaces the previous three independent finalize_svg steps:
5
-
6
- crop-images → for each <image preserveAspectRatio="… slice"/>, crop the
7
- source bitmap to the target aspect ratio at the given
8
- anchor and write to `images/cropped/` so the SVG
9
- reference points to a pre-cropped asset.
10
- fix-aspect → for each <image>, read the source bitmap dimensions and
11
- adjust x/y/width/height so the rendered box matches the
12
- image aspect ratio (PowerPoint's "Convert to Shape"
13
- ignores preserveAspectRatio and stretches otherwise).
14
- embed-images → Base64-inline every external image reference so the
15
- legacy/preview pptx (which packages the SVG verbatim)
16
- can resolve them — pptx-internal SVG cannot follow
17
- `../images/…` relative URIs.
18
-
19
- Why merge: each step independently parsed + serialized the SVG, each step
20
- re-read the same bitmap from disk, and the two spatial transforms (crop and
21
- fit-box) are mutually exclusive yet were sequenced one after the other.
22
- The fix-aspect default preserveAspectRatio = "xMidYMid meet" could
23
- also kick in on rects already cropped by crop-images (whose par was
24
- already removed), with the only thing keeping it from corrupting the
25
- geometry being that crop and fix-aspect happened to produce numerically
26
- equal box dimensions — a brittle accident.
27
-
28
- The merged pipeline:
29
-
30
- for image in svg:
31
- if href starts with data: → skip (already inline)
32
- if href is unresolvable / external URL → skip
33
- if href points to EMF/WMF → skip (native PPTX passthrough only)
34
- if missing preserveAspectRatio → just embed (do not assume meet)
35
- if align == none → just embed (no spatial transform)
36
- if mode == slice → crop in memory, embed cropped bytes
37
- if mode == meet → adjust x/y/w/h, embed original bytes
38
- write SVG once
39
-
40
- Bonus: the cropped bitmap is base64-inlined directly without going through
41
- `images/cropped/`, so that intermediate directory disappears and stale
42
- crops can no longer accumulate across re-runs.
43
- """
44
-
45
- from __future__ import annotations
46
-
47
- import base64
48
- import io
49
- import os
50
- import re
51
- import sys
52
- from pathlib import Path
53
- from typing import TYPE_CHECKING
54
- from urllib.parse import unquote
55
- from xml.etree import ElementTree as ET
56
-
57
- _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
58
- if str(_SCRIPTS_DIR) not in sys.path:
59
- sys.path.insert(0, str(_SCRIPTS_DIR))
60
-
61
- from console_encoding import configure_utf8_stdio # noqa: E402
62
-
63
- configure_utf8_stdio()
64
-
65
- if __package__ in {None, ''}:
66
- import types
67
-
68
- package = types.ModuleType('svg_finalize')
69
- package.__path__ = [str(Path(__file__).resolve().parent)] # type: ignore[attr-defined]
70
- sys.modules.setdefault('svg_finalize', package)
71
- __package__ = 'svg_finalize'
72
-
73
- # Reuse helpers from the previous standalone modules.
74
- from .crop_images import crop_image_to_size, get_crop_anchor, parse_preserve_aspect_ratio
75
- from .embed_images import _optimize_image_bytes, get_mime_type
76
- from .fix_image_aspect import calculate_fitted_dimensions
77
-
78
- if TYPE_CHECKING: # pragma: no cover
79
- from PIL import Image as PILImage # noqa: F401
80
-
81
-
82
- SVG_NS = 'http://www.w3.org/2000/svg'
83
- XLINK_NS = 'http://www.w3.org/1999/xlink'
84
-
85
- # PIL save format is named slightly differently from the file extension /
86
- # MIME type set we expose elsewhere; this map covers the formats we accept.
87
- _PIL_FORMAT_BY_MIME = {
88
- 'image/png': 'PNG',
89
- 'image/jpeg': 'JPEG',
90
- 'image/gif': 'GIF',
91
- 'image/webp': 'WEBP',
92
- }
93
- _OFFICE_VECTOR_EXTENSIONS = {'.emf', '.wmf'}
94
-
95
-
96
- def _parse_float(val: str | None, default: float = 0.0) -> float:
97
- """Best-effort float parse, tolerating trailing `px` etc."""
98
- if val is None or val == '':
99
- return default
100
- try:
101
- return float(re.sub(r'(px|pt|em|%|rem)$', '', val.strip()))
102
- except (ValueError, AttributeError):
103
- return default
104
-
105
-
106
- def _format_number(n: float) -> str:
107
- """Format a float for compact SVG attribute output."""
108
- if abs(n - round(n)) < 1e-6:
109
- return str(int(round(n)))
110
- s = f"{n:.2f}".rstrip('0').rstrip('.')
111
- return s or '0'
112
-
113
-
114
- def _resolve_image_path(href: str, svg_dir: Path) -> Path | None:
115
- """Resolve an <image> href to a local filesystem path.
116
-
117
- Returns None for unresolvable references (http/https/etc.) so callers
118
- can leave those refs untouched.
119
- """
120
- if not href:
121
- return None
122
- decoded = unquote(href)
123
- if decoded.startswith(('http://', 'https://', 'file://')):
124
- return None
125
- if os.path.isabs(decoded):
126
- candidate = Path(decoded)
127
- else:
128
- candidate = (svg_dir / decoded).resolve()
129
- return candidate if candidate.exists() else None
130
-
131
-
132
- def _is_svg_image(img_path: Path, raw_bytes: bytes) -> bool:
133
- """Return True when an image reference is an SVG document."""
134
- if img_path.suffix.lower() == '.svg':
135
- return True
136
- head = raw_bytes.lstrip()[:512].lower()
137
- return head.startswith(b'<svg') or (head.startswith(b'<?xml') and b'<svg' in head)
138
-
139
-
140
- def _embed_raw_image(image: ET.Element, img_path: Path, raw_bytes: bytes) -> None:
141
- """Embed raw image bytes without PIL transforms."""
142
- mime_type = get_mime_type(img_path.name, raw_bytes)
143
- b64 = base64.b64encode(raw_bytes).decode('ascii')
144
- _set_href(image, f'data:{mime_type};base64,{b64}')
145
-
146
-
147
- def _load_pil_image(img_path: Path) -> 'PILImage' | None:
148
- """Open an image with PIL, returning None on any failure."""
149
- try:
150
- from PIL import Image
151
- except ImportError:
152
- return None
153
- try:
154
- return Image.open(img_path)
155
- except (OSError, ValueError):
156
- return None
157
-
158
-
159
- def _normalize_for_save(img: 'PILImage', mime_type: str) -> 'PILImage':
160
- """Coerce a PIL image into a mode that the target format can save.
161
-
162
- JPEG cannot store alpha — flatten to white background. Other formats
163
- keep alpha when present.
164
- """
165
- if mime_type == 'image/jpeg':
166
- if img.mode in ('RGBA', 'LA'):
167
- from PIL import Image
168
- background = Image.new('RGB', img.size, (255, 255, 255))
169
- alpha = img.getchannel('A') if img.mode == 'RGBA' else None
170
- background.paste(img.convert('RGB'), mask=alpha)
171
- return background
172
- if img.mode != 'RGB':
173
- return img.convert('RGB')
174
- return img
175
- # PNG / GIF / WEBP — preserve alpha if present
176
- if img.mode == 'P':
177
- return img.convert('RGBA' if 'A' in img.getbands() else 'RGB')
178
- return img
179
-
180
-
181
- def _has_alpha(img: 'PILImage') -> bool:
182
- """Return whether a PIL image has transparency."""
183
- if img.mode in ('RGBA', 'LA'):
184
- return True
185
- if img.mode == 'P':
186
- return 'transparency' in getattr(img, 'info', {})
187
- return False
188
-
189
-
190
- def _target_size(
191
- box_w: float,
192
- box_h: float,
193
- *,
194
- max_dimension: int | None,
195
- image_scale: float,
196
- ) -> tuple[int, int]:
197
- """Resolve the pixel budget for a rendered SVG image box."""
198
- target_w = max(1, int(round(box_w * max(image_scale, 1.0))))
199
- target_h = max(1, int(round(box_h * max(image_scale, 1.0))))
200
- if max_dimension and max(target_w, target_h) > max_dimension:
201
- ratio = max_dimension / max(target_w, target_h)
202
- target_w = max(1, int(round(target_w * ratio)))
203
- target_h = max(1, int(round(target_h * ratio)))
204
- return target_w, target_h
205
-
206
-
207
- def _downscale_to_target(img: 'PILImage', target_w: int, target_h: int) -> tuple['PILImage', bool]:
208
- """Downscale without upsampling."""
209
- width, height = img.size
210
- ratio = min(target_w / width, target_h / height, 1.0)
211
- if ratio >= 1.0:
212
- return img, False
213
- from PIL import Image
214
- new_size = (max(1, int(round(width * ratio))), max(1, int(round(height * ratio))))
215
- return img.resize(new_size, Image.Resampling.LANCZOS), True
216
-
217
-
218
- def _encode_pil_to_data_uri(
219
- img: 'PILImage',
220
- src_path: Path,
221
- *,
222
- compress: bool,
223
- max_dimension: int | None,
224
- fallback_bytes: bytes | None,
225
- ) -> tuple[str, int] | None:
226
- """Serialize *img* to a base64 data URI.
227
-
228
- If the image hasn't been transformed (slice crop or meet fit), prefer
229
- re-encoding the original file bytes so we don't risk mutating an
230
- already-optimized asset. *fallback_bytes* carries the raw on-disk
231
- bytes for that path.
232
- """
233
- original_mime_type = get_mime_type(src_path.name, fallback_bytes)
234
- mime_type = original_mime_type
235
- if compress and mime_type == 'image/png' and not _has_alpha(img):
236
- mime_type = 'image/jpeg'
237
- pil_format = _PIL_FORMAT_BY_MIME.get(mime_type, 'PNG')
238
-
239
- # Encode current PIL image
240
- try:
241
- prepared = _normalize_for_save(img, mime_type)
242
- buf = io.BytesIO()
243
- save_kwargs: dict = {'format': pil_format}
244
- if pil_format == 'JPEG':
245
- save_kwargs['quality'] = 95
246
- save_kwargs['optimize'] = True
247
- elif pil_format == 'PNG':
248
- save_kwargs['optimize'] = True
249
- prepared.save(buf, **save_kwargs)
250
- encoded_bytes = buf.getvalue()
251
- except (OSError, ValueError):
252
- return None
253
-
254
- # If caller passed the original bytes and they're smaller (because PIL
255
- # round-tripping an asset that was already well-compressed inflates it),
256
- # fall back to those.
257
- chosen = encoded_bytes
258
- if fallback_bytes and mime_type == original_mime_type and len(fallback_bytes) < len(encoded_bytes):
259
- chosen = fallback_bytes
260
-
261
- chosen = _optimize_image_bytes(
262
- chosen, mime_type, compress=compress, max_dimension=max_dimension,
263
- )
264
-
265
- b64 = base64.b64encode(chosen).decode('ascii')
266
- return f'data:{mime_type};base64,{b64}', len(chosen)
267
-
268
-
269
- def _iter_image_elements(root: ET.Element):
270
- """Yield every <image> in the tree regardless of namespace prefix."""
271
- for image in root.iter(f'{{{SVG_NS}}}image'):
272
- yield image
273
- # Also catch namespace-stripped trees just in case
274
- for image in root.iter('image'):
275
- yield image
276
-
277
-
278
- def _get_href(image: ET.Element) -> str | None:
279
- """Return the image href, supporting both `href` and `xlink:href`."""
280
- return image.get('href') or image.get(f'{{{XLINK_NS}}}href')
281
-
282
-
283
- def _set_href(image: ET.Element, value: str) -> None:
284
- """Write the data URI back to whichever href attribute the image used."""
285
- if image.get(f'{{{XLINK_NS}}}href') is not None:
286
- image.set(f'{{{XLINK_NS}}}href', value)
287
- else:
288
- image.set('href', value)
289
-
290
-
291
- def _process_one_image(
292
- image: ET.Element,
293
- svg_dir: Path,
294
- *,
295
- compress: bool,
296
- max_dimension: int | None,
297
- image_scale: float,
298
- verbose: bool,
299
- ) -> tuple[bool, str | None]:
300
- """Align (slice/meet) and embed a single <image>.
301
-
302
- Returns (processed, error) where *processed* is True iff the image
303
- was rewritten and *error* is a short message when something went wrong
304
- (the image is left untouched in that case).
305
- """
306
- href = _get_href(image)
307
- if not href:
308
- return False, None
309
- if href.startswith('data:'):
310
- return False, None # already inline
311
-
312
- img_path = _resolve_image_path(href, svg_dir)
313
- if img_path is None:
314
- return False, f'unresolved href: {href[:60]}'
315
-
316
- try:
317
- with open(img_path, 'rb') as fh:
318
- raw_bytes = fh.read()
319
- except OSError as exc:
320
- return False, f'read failed: {exc}'
321
-
322
- if img_path.suffix.lower() in _OFFICE_VECTOR_EXTENSIONS:
323
- if verbose:
324
- print(f' [INFO] {img_path.name}: Office vector left external for native PPTX passthrough')
325
- return False, None
326
-
327
- if _is_svg_image(img_path, raw_bytes):
328
- _embed_raw_image(image, img_path, raw_bytes)
329
- if verbose:
330
- print(f' [OK] {img_path.name} (svg, embedded as-is)')
331
- return True, None
332
-
333
- img = _load_pil_image(img_path)
334
- if img is None:
335
- return False, 'PIL open failed'
336
-
337
- # Multi-frame images (animated GIF / WebP / APNG): every PIL transform
338
- # and re-save below operates on frame 0 only, silently flattening the
339
- # animation — and the "original bytes are smaller" fallback never fires
340
- # because one frame is always smaller than all frames. Embed the raw
341
- # bytes untouched and keep the geometry attributes (including
342
- # preserveAspectRatio, which the native converter maps to srcRect
343
- # non-destructively). Animated assets skip re-encode, resize, and the
344
- # size cap.
345
- if getattr(img, 'is_animated', False):
346
- _embed_raw_image(image, img_path, raw_bytes)
347
- if max_dimension and max(img.size) > max_dimension:
348
- print(f' [WARN] {img_path.name}: animated image kept as-is '
349
- f'({img.size[0]}x{img.size[1]} exceeds max dimension '
350
- f'{max_dimension}px); animations are exempt from size limits')
351
- if verbose:
352
- print(f' [OK] {img_path.name} (animated, embedded as-is)')
353
- return True, None
354
-
355
- box_x = _parse_float(image.get('x'))
356
- box_y = _parse_float(image.get('y'))
357
- box_w = _parse_float(image.get('width'))
358
- box_h = _parse_float(image.get('height'))
359
- if box_w <= 0 or box_h <= 0:
360
- return False, 'zero-sized box'
361
-
362
- par_attr = image.get('preserveAspectRatio') or ''
363
- par_attr = par_attr.strip()
364
-
365
- # ------------------------------------------------------------------
366
- # Decide the spatial transform
367
- # ------------------------------------------------------------------
368
- final_img: 'PILImage' = img
369
- new_x, new_y, new_w, new_h = box_x, box_y, box_w, box_h
370
- transformed = False # True iff bitmap content changed (crop happened)
371
- target_box_w, target_box_h = box_w, box_h
372
-
373
- if not par_attr:
374
- # No preserveAspectRatio at all. The previous pipeline's fix-aspect
375
- # step assumed "xMidYMid meet" here, which silently re-fit images
376
- # that crop-images had already shaped. Treat absence as "leave it
377
- # alone": embed bytes, keep box.
378
- pass
379
- else:
380
- align, mode = parse_preserve_aspect_ratio(par_attr)
381
- if align == 'none':
382
- # Author wants stretch-to-box; preserve geometry, embed bytes.
383
- pass
384
- elif mode == 'slice':
385
- x_anchor, y_anchor = get_crop_anchor(align)
386
- cropped = crop_image_to_size(img, int(box_w), int(box_h),
387
- x_anchor, y_anchor)
388
- final_img = cropped
389
- transformed = True
390
- else: # meet (or any other mode → treat as meet)
391
- new_w_calc, new_h_calc, off_x, off_y = calculate_fitted_dimensions(
392
- img.size[0], img.size[1], box_w, box_h, mode='meet',
393
- )
394
- new_x = box_x + off_x
395
- new_y = box_y + off_y
396
- new_w = new_w_calc
397
- new_h = new_h_calc
398
- target_box_w, target_box_h = new_w, new_h
399
-
400
- target_w, target_h = _target_size(
401
- target_box_w,
402
- target_box_h,
403
- max_dimension=max_dimension,
404
- image_scale=image_scale,
405
- )
406
- final_img, resized = _downscale_to_target(final_img, target_w, target_h)
407
- transformed = transformed or resized
408
-
409
- # ------------------------------------------------------------------
410
- # Encode and rewrite
411
- # ------------------------------------------------------------------
412
- encoded = _encode_pil_to_data_uri(
413
- final_img,
414
- img_path,
415
- compress=compress,
416
- max_dimension=max_dimension,
417
- fallback_bytes=raw_bytes if not transformed else None,
418
- )
419
- if encoded is None:
420
- return False, 'encode failed'
421
- data_uri, _ = encoded
422
-
423
- _set_href(image, data_uri)
424
- image.set('x', _format_number(new_x))
425
- image.set('y', _format_number(new_y))
426
- image.set('width', _format_number(new_w))
427
- image.set('height', _format_number(new_h))
428
- if 'preserveAspectRatio' in image.attrib:
429
- del image.attrib['preserveAspectRatio']
430
-
431
- if verbose:
432
- suffix = ' (cropped)' if transformed else ''
433
- print(f' [OK] {img_path.name}{suffix}')
434
- return True, None
435
-
436
-
437
- def count_office_vector_refs_in_svg(svg_path: str | Path) -> int:
438
- """Count local EMF/WMF image refs that the embed pass intentionally skips."""
439
- svg_path = Path(svg_path)
440
- svg_dir = svg_path.parent.resolve()
441
- try:
442
- tree = ET.parse(svg_path)
443
- except ET.ParseError:
444
- return 0
445
- count = 0
446
- seen: set[int] = set()
447
- for image in _iter_image_elements(tree.getroot()):
448
- ident = id(image)
449
- if ident in seen:
450
- continue
451
- seen.add(ident)
452
- href = _get_href(image)
453
- if not href or href.startswith('data:'):
454
- continue
455
- img_path = _resolve_image_path(href, svg_dir)
456
- if img_path and img_path.suffix.lower() in _OFFICE_VECTOR_EXTENSIONS:
457
- count += 1
458
- return count
459
-
460
-
461
- def align_and_embed_images_in_svg(
462
- svg_path: str | Path,
463
- *,
464
- dry_run: bool = False,
465
- verbose: bool = False,
466
- compress: bool = True,
467
- max_dimension: int | None = 2560,
468
- image_scale: float = 2.0,
469
- ) -> tuple[int, int]:
470
- """Run the merged align + embed pass on a single SVG file.
471
-
472
- Returns (processed_count, error_count).
473
- """
474
- svg_path = Path(svg_path)
475
- svg_dir = svg_path.parent.resolve()
476
-
477
- # Register namespaces for clean serialization
478
- ET.register_namespace('', SVG_NS)
479
- ET.register_namespace('xlink', XLINK_NS)
480
-
481
- try:
482
- tree = ET.parse(svg_path)
483
- except ET.ParseError as exc:
484
- if verbose:
485
- print(f' [ERROR] {svg_path.name}: parse failed ({exc})')
486
- return (0, 1)
487
- root = tree.getroot()
488
-
489
- # Avoid double-iteration if an element matches both namespaced and
490
- # bare-tag iteration paths.
491
- seen: set[int] = set()
492
- processed = 0
493
- errors = 0
494
-
495
- for image in _iter_image_elements(root):
496
- ident = id(image)
497
- if ident in seen:
498
- continue
499
- seen.add(ident)
500
-
501
- if dry_run:
502
- processed += 1
503
- continue
504
-
505
- ok, err = _process_one_image(
506
- image, svg_dir,
507
- compress=compress, max_dimension=max_dimension,
508
- image_scale=image_scale, verbose=verbose,
509
- )
510
- if ok:
511
- processed += 1
512
- elif err:
513
- errors += 1
514
- if verbose:
515
- print(f' [WARN] {svg_path.name}: {err}')
516
-
517
- if processed > 0 and not dry_run:
518
- tree.write(svg_path, encoding='utf-8', xml_declaration=False)
519
-
520
- return (processed, errors)
521
-
522
-
523
- # ---------------------------------------------------------------------------
524
- # Standalone CLI (rare; the main entry point is finalize_svg.py)
525
- # ---------------------------------------------------------------------------
526
-
527
- def build_parser() -> argparse.ArgumentParser:
528
- """Build the standalone diagnostic parser."""
529
- import argparse
530
- parser = argparse.ArgumentParser(
531
- description='Align (slice/meet) and Base64-embed all <image> refs in an SVG.',
532
- )
533
- parser.add_argument('svg', type=Path, help='SVG file to process in place')
534
- parser.add_argument('-n', '--dry-run', action='store_true')
535
- parser.add_argument('-v', '--verbose', action='store_true')
536
- parser.add_argument('--compress', dest='compress', action='store_true', default=True,
537
- help='Compress images before embedding (default)')
538
- parser.add_argument('--no-compress', dest='compress', action='store_false',
539
- help='Disable image compression')
540
- parser.add_argument('--max-dimension', type=int, default=2560,
541
- help='Downscale images larger than this on either axis (default: 2560)')
542
- parser.add_argument('--image-scale', type=float, default=2.0,
543
- help='Target pixels per rendered SVG pixel')
544
- return parser
545
-
546
-
547
- def main(argv: list[str] | None = None) -> int:
548
- """Run the standalone diagnostic CLI."""
549
- parser = build_parser()
550
- args = parser.parse_args(argv)
551
-
552
- if not args.svg.exists():
553
- print(f'Error: file not found: {args.svg}', file=sys.stderr)
554
- return 1
555
- if args.max_dimension < 1:
556
- print('Error: --max-dimension must be >= 1', file=sys.stderr)
557
- return 1
558
- if args.image_scale < 1:
559
- print('Error: --image-scale must be >= 1', file=sys.stderr)
560
- return 1
561
-
562
- proc, err = align_and_embed_images_in_svg(
563
- args.svg,
564
- dry_run=args.dry_run,
565
- verbose=args.verbose,
566
- compress=args.compress,
567
- max_dimension=args.max_dimension,
568
- image_scale=args.image_scale,
569
- )
570
- print(f'Processed {proc} image(s), {err} error(s)')
571
- return 1 if err else 0
572
-
573
-
574
- if __name__ == '__main__':
575
- raise SystemExit(main())
1
+ #!/usr/bin/env python3
2
+ """PPT Master — single-pass image alignment + Base64 embedding.
3
+
4
+ Replaces the previous three independent finalize_svg steps:
5
+
6
+ crop-images → for each <image preserveAspectRatio="… slice"/>, crop the
7
+ source bitmap to the target aspect ratio at the given
8
+ anchor and write to `images/cropped/` so the SVG
9
+ reference points to a pre-cropped asset.
10
+ fix-aspect → for each <image>, read the source bitmap dimensions and
11
+ adjust x/y/width/height so the rendered box matches the
12
+ image aspect ratio (PowerPoint's "Convert to Shape"
13
+ ignores preserveAspectRatio and stretches otherwise).
14
+ embed-images → Base64-inline every external image reference so the
15
+ legacy/preview pptx (which packages the SVG verbatim)
16
+ can resolve them — pptx-internal SVG cannot follow
17
+ `../images/…` relative URIs.
18
+
19
+ Why merge: each step independently parsed + serialized the SVG, each step
20
+ re-read the same bitmap from disk, and the two spatial transforms (crop and
21
+ fit-box) are mutually exclusive yet were sequenced one after the other.
22
+ The fix-aspect default preserveAspectRatio = "xMidYMid meet" could
23
+ also kick in on rects already cropped by crop-images (whose par was
24
+ already removed), with the only thing keeping it from corrupting the
25
+ geometry being that crop and fix-aspect happened to produce numerically
26
+ equal box dimensions — a brittle accident.
27
+
28
+ The merged pipeline:
29
+
30
+ for image in svg:
31
+ if href starts with data: → skip (already inline)
32
+ if href is unresolvable / external URL → skip
33
+ if href points to EMF/WMF → skip (native PPTX passthrough only)
34
+ if missing preserveAspectRatio → just embed (do not assume meet)
35
+ if align == none → just embed (no spatial transform)
36
+ if mode == slice → crop in memory, embed cropped bytes
37
+ if mode == meet → adjust x/y/w/h, embed original bytes
38
+ write SVG once
39
+
40
+ Bonus: the cropped bitmap is base64-inlined directly without going through
41
+ `images/cropped/`, so that intermediate directory disappears and stale
42
+ crops can no longer accumulate across re-runs.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import base64
48
+ import io
49
+ import os
50
+ import re
51
+ import sys
52
+ from pathlib import Path
53
+ from typing import TYPE_CHECKING
54
+ from urllib.parse import unquote
55
+ from xml.etree import ElementTree as ET
56
+
57
+ _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
58
+ if str(_SCRIPTS_DIR) not in sys.path:
59
+ sys.path.insert(0, str(_SCRIPTS_DIR))
60
+
61
+ from console_encoding import configure_utf8_stdio # noqa: E402
62
+
63
+ configure_utf8_stdio()
64
+
65
+ if __package__ in {None, ''}:
66
+ import types
67
+
68
+ package = types.ModuleType('svg_finalize')
69
+ package.__path__ = [str(Path(__file__).resolve().parent)] # type: ignore[attr-defined]
70
+ sys.modules.setdefault('svg_finalize', package)
71
+ __package__ = 'svg_finalize'
72
+
73
+ # Reuse helpers from the previous standalone modules.
74
+ from .crop_images import crop_image_to_size, get_crop_anchor, parse_preserve_aspect_ratio
75
+ from .embed_images import _optimize_image_bytes, get_mime_type
76
+ from .fix_image_aspect import calculate_fitted_dimensions
77
+
78
+ if TYPE_CHECKING: # pragma: no cover
79
+ from PIL import Image as PILImage # noqa: F401
80
+
81
+
82
+ SVG_NS = 'http://www.w3.org/2000/svg'
83
+ XLINK_NS = 'http://www.w3.org/1999/xlink'
84
+
85
+ # PIL save format is named slightly differently from the file extension /
86
+ # MIME type set we expose elsewhere; this map covers the formats we accept.
87
+ _PIL_FORMAT_BY_MIME = {
88
+ 'image/png': 'PNG',
89
+ 'image/jpeg': 'JPEG',
90
+ 'image/gif': 'GIF',
91
+ 'image/webp': 'WEBP',
92
+ }
93
+ _OFFICE_VECTOR_EXTENSIONS = {'.emf', '.wmf'}
94
+
95
+
96
+ def _parse_float(val: str | None, default: float = 0.0) -> float:
97
+ """Best-effort float parse, tolerating trailing `px` etc."""
98
+ if val is None or val == '':
99
+ return default
100
+ try:
101
+ return float(re.sub(r'(px|pt|em|%|rem)$', '', val.strip()))
102
+ except (ValueError, AttributeError):
103
+ return default
104
+
105
+
106
+ def _format_number(n: float) -> str:
107
+ """Format a float for compact SVG attribute output."""
108
+ if abs(n - round(n)) < 1e-6:
109
+ return str(int(round(n)))
110
+ s = f"{n:.2f}".rstrip('0').rstrip('.')
111
+ return s or '0'
112
+
113
+
114
+ def _resolve_image_path(href: str, svg_dir: Path) -> Path | None:
115
+ """Resolve an <image> href to a local filesystem path.
116
+
117
+ Returns None for unresolvable references (http/https/etc.) so callers
118
+ can leave those refs untouched.
119
+ """
120
+ if not href:
121
+ return None
122
+ decoded = unquote(href)
123
+ if decoded.startswith(('http://', 'https://', 'file://')):
124
+ return None
125
+ if os.path.isabs(decoded):
126
+ candidate = Path(decoded)
127
+ else:
128
+ candidate = (svg_dir / decoded).resolve()
129
+ return candidate if candidate.exists() else None
130
+
131
+
132
+ def _is_svg_image(img_path: Path, raw_bytes: bytes) -> bool:
133
+ """Return True when an image reference is an SVG document."""
134
+ if img_path.suffix.lower() == '.svg':
135
+ return True
136
+ head = raw_bytes.lstrip()[:512].lower()
137
+ return head.startswith(b'<svg') or (head.startswith(b'<?xml') and b'<svg' in head)
138
+
139
+
140
+ def _embed_raw_image(image: ET.Element, img_path: Path, raw_bytes: bytes) -> None:
141
+ """Embed raw image bytes without PIL transforms."""
142
+ mime_type = get_mime_type(img_path.name, raw_bytes)
143
+ b64 = base64.b64encode(raw_bytes).decode('ascii')
144
+ _set_href(image, f'data:{mime_type};base64,{b64}')
145
+
146
+
147
+ def _load_pil_image(img_path: Path) -> 'PILImage' | None:
148
+ """Open an image with PIL, returning None on any failure."""
149
+ try:
150
+ from PIL import Image
151
+ except ImportError:
152
+ return None
153
+ try:
154
+ return Image.open(img_path)
155
+ except (OSError, ValueError):
156
+ return None
157
+
158
+
159
+ def _normalize_for_save(img: 'PILImage', mime_type: str) -> 'PILImage':
160
+ """Coerce a PIL image into a mode that the target format can save.
161
+
162
+ JPEG cannot store alpha — flatten to white background. Other formats
163
+ keep alpha when present.
164
+ """
165
+ if mime_type == 'image/jpeg':
166
+ if img.mode in ('RGBA', 'LA'):
167
+ from PIL import Image
168
+ background = Image.new('RGB', img.size, (255, 255, 255))
169
+ alpha = img.getchannel('A') if img.mode == 'RGBA' else None
170
+ background.paste(img.convert('RGB'), mask=alpha)
171
+ return background
172
+ if img.mode != 'RGB':
173
+ return img.convert('RGB')
174
+ return img
175
+ # PNG / GIF / WEBP — preserve alpha if present
176
+ if img.mode == 'P':
177
+ return img.convert('RGBA' if 'A' in img.getbands() else 'RGB')
178
+ return img
179
+
180
+
181
+ def _has_alpha(img: 'PILImage') -> bool:
182
+ """Return whether a PIL image has transparency."""
183
+ if img.mode in ('RGBA', 'LA'):
184
+ return True
185
+ if img.mode == 'P':
186
+ return 'transparency' in getattr(img, 'info', {})
187
+ return False
188
+
189
+
190
+ def _target_size(
191
+ box_w: float,
192
+ box_h: float,
193
+ *,
194
+ max_dimension: int | None,
195
+ image_scale: float,
196
+ ) -> tuple[int, int]:
197
+ """Resolve the pixel budget for a rendered SVG image box."""
198
+ target_w = max(1, int(round(box_w * max(image_scale, 1.0))))
199
+ target_h = max(1, int(round(box_h * max(image_scale, 1.0))))
200
+ if max_dimension and max(target_w, target_h) > max_dimension:
201
+ ratio = max_dimension / max(target_w, target_h)
202
+ target_w = max(1, int(round(target_w * ratio)))
203
+ target_h = max(1, int(round(target_h * ratio)))
204
+ return target_w, target_h
205
+
206
+
207
+ def _downscale_to_target(img: 'PILImage', target_w: int, target_h: int) -> tuple['PILImage', bool]:
208
+ """Downscale without upsampling."""
209
+ width, height = img.size
210
+ ratio = min(target_w / width, target_h / height, 1.0)
211
+ if ratio >= 1.0:
212
+ return img, False
213
+ from PIL import Image
214
+ new_size = (max(1, int(round(width * ratio))), max(1, int(round(height * ratio))))
215
+ return img.resize(new_size, Image.Resampling.LANCZOS), True
216
+
217
+
218
+ def _encode_pil_to_data_uri(
219
+ img: 'PILImage',
220
+ src_path: Path,
221
+ *,
222
+ compress: bool,
223
+ max_dimension: int | None,
224
+ fallback_bytes: bytes | None,
225
+ ) -> tuple[str, int] | None:
226
+ """Serialize *img* to a base64 data URI.
227
+
228
+ If the image hasn't been transformed (slice crop or meet fit), prefer
229
+ re-encoding the original file bytes so we don't risk mutating an
230
+ already-optimized asset. *fallback_bytes* carries the raw on-disk
231
+ bytes for that path.
232
+ """
233
+ original_mime_type = get_mime_type(src_path.name, fallback_bytes)
234
+ mime_type = original_mime_type
235
+ if compress and mime_type == 'image/png' and not _has_alpha(img):
236
+ mime_type = 'image/jpeg'
237
+ pil_format = _PIL_FORMAT_BY_MIME.get(mime_type, 'PNG')
238
+
239
+ # Encode current PIL image
240
+ try:
241
+ prepared = _normalize_for_save(img, mime_type)
242
+ buf = io.BytesIO()
243
+ save_kwargs: dict = {'format': pil_format}
244
+ if pil_format == 'JPEG':
245
+ save_kwargs['quality'] = 95
246
+ save_kwargs['optimize'] = True
247
+ elif pil_format == 'PNG':
248
+ save_kwargs['optimize'] = True
249
+ prepared.save(buf, **save_kwargs)
250
+ encoded_bytes = buf.getvalue()
251
+ except (OSError, ValueError):
252
+ return None
253
+
254
+ # If caller passed the original bytes and they're smaller (because PIL
255
+ # round-tripping an asset that was already well-compressed inflates it),
256
+ # fall back to those.
257
+ chosen = encoded_bytes
258
+ if fallback_bytes and mime_type == original_mime_type and len(fallback_bytes) < len(encoded_bytes):
259
+ chosen = fallback_bytes
260
+
261
+ chosen = _optimize_image_bytes(
262
+ chosen, mime_type, compress=compress, max_dimension=max_dimension,
263
+ )
264
+
265
+ b64 = base64.b64encode(chosen).decode('ascii')
266
+ return f'data:{mime_type};base64,{b64}', len(chosen)
267
+
268
+
269
+ def _iter_image_elements(root: ET.Element):
270
+ """Yield every <image> in the tree regardless of namespace prefix."""
271
+ for image in root.iter(f'{{{SVG_NS}}}image'):
272
+ yield image
273
+ # Also catch namespace-stripped trees just in case
274
+ for image in root.iter('image'):
275
+ yield image
276
+
277
+
278
+ def _get_href(image: ET.Element) -> str | None:
279
+ """Return the image href, supporting both `href` and `xlink:href`."""
280
+ return image.get('href') or image.get(f'{{{XLINK_NS}}}href')
281
+
282
+
283
+ def _set_href(image: ET.Element, value: str) -> None:
284
+ """Write the data URI back to whichever href attribute the image used."""
285
+ if image.get(f'{{{XLINK_NS}}}href') is not None:
286
+ image.set(f'{{{XLINK_NS}}}href', value)
287
+ else:
288
+ image.set('href', value)
289
+
290
+
291
+ def _process_one_image(
292
+ image: ET.Element,
293
+ svg_dir: Path,
294
+ *,
295
+ compress: bool,
296
+ max_dimension: int | None,
297
+ image_scale: float,
298
+ verbose: bool,
299
+ ) -> tuple[bool, str | None]:
300
+ """Align (slice/meet) and embed a single <image>.
301
+
302
+ Returns (processed, error) where *processed* is True iff the image
303
+ was rewritten and *error* is a short message when something went wrong
304
+ (the image is left untouched in that case).
305
+ """
306
+ href = _get_href(image)
307
+ if not href:
308
+ return False, None
309
+ if href.startswith('data:'):
310
+ return False, None # already inline
311
+
312
+ img_path = _resolve_image_path(href, svg_dir)
313
+ if img_path is None:
314
+ return False, f'unresolved href: {href[:60]}'
315
+
316
+ try:
317
+ with open(img_path, 'rb') as fh:
318
+ raw_bytes = fh.read()
319
+ except OSError as exc:
320
+ return False, f'read failed: {exc}'
321
+
322
+ if img_path.suffix.lower() in _OFFICE_VECTOR_EXTENSIONS:
323
+ if verbose:
324
+ print(f' [INFO] {img_path.name}: Office vector left external for native PPTX passthrough')
325
+ return False, None
326
+
327
+ if _is_svg_image(img_path, raw_bytes):
328
+ _embed_raw_image(image, img_path, raw_bytes)
329
+ if verbose:
330
+ print(f' [OK] {img_path.name} (svg, embedded as-is)')
331
+ return True, None
332
+
333
+ img = _load_pil_image(img_path)
334
+ if img is None:
335
+ return False, 'PIL open failed'
336
+
337
+ # Multi-frame images (animated GIF / WebP / APNG): every PIL transform
338
+ # and re-save below operates on frame 0 only, silently flattening the
339
+ # animation — and the "original bytes are smaller" fallback never fires
340
+ # because one frame is always smaller than all frames. Embed the raw
341
+ # bytes untouched and keep the geometry attributes (including
342
+ # preserveAspectRatio, which the native converter maps to srcRect
343
+ # non-destructively). Animated assets skip re-encode, resize, and the
344
+ # size cap.
345
+ if getattr(img, 'is_animated', False):
346
+ _embed_raw_image(image, img_path, raw_bytes)
347
+ if max_dimension and max(img.size) > max_dimension:
348
+ print(f' [WARN] {img_path.name}: animated image kept as-is '
349
+ f'({img.size[0]}x{img.size[1]} exceeds max dimension '
350
+ f'{max_dimension}px); animations are exempt from size limits')
351
+ if verbose:
352
+ print(f' [OK] {img_path.name} (animated, embedded as-is)')
353
+ return True, None
354
+
355
+ box_x = _parse_float(image.get('x'))
356
+ box_y = _parse_float(image.get('y'))
357
+ box_w = _parse_float(image.get('width'))
358
+ box_h = _parse_float(image.get('height'))
359
+ if box_w <= 0 or box_h <= 0:
360
+ return False, 'zero-sized box'
361
+
362
+ par_attr = image.get('preserveAspectRatio') or ''
363
+ par_attr = par_attr.strip()
364
+
365
+ # ------------------------------------------------------------------
366
+ # Decide the spatial transform
367
+ # ------------------------------------------------------------------
368
+ final_img: 'PILImage' = img
369
+ new_x, new_y, new_w, new_h = box_x, box_y, box_w, box_h
370
+ transformed = False # True iff bitmap content changed (crop happened)
371
+ target_box_w, target_box_h = box_w, box_h
372
+
373
+ if not par_attr:
374
+ # No preserveAspectRatio at all. The previous pipeline's fix-aspect
375
+ # step assumed "xMidYMid meet" here, which silently re-fit images
376
+ # that crop-images had already shaped. Treat absence as "leave it
377
+ # alone": embed bytes, keep box.
378
+ pass
379
+ else:
380
+ align, mode = parse_preserve_aspect_ratio(par_attr)
381
+ if align == 'none':
382
+ # Author wants stretch-to-box; preserve geometry, embed bytes.
383
+ pass
384
+ elif mode == 'slice':
385
+ x_anchor, y_anchor = get_crop_anchor(align)
386
+ cropped = crop_image_to_size(img, int(box_w), int(box_h),
387
+ x_anchor, y_anchor)
388
+ final_img = cropped
389
+ transformed = True
390
+ else: # meet (or any other mode → treat as meet)
391
+ new_w_calc, new_h_calc, off_x, off_y = calculate_fitted_dimensions(
392
+ img.size[0], img.size[1], box_w, box_h, mode='meet',
393
+ )
394
+ new_x = box_x + off_x
395
+ new_y = box_y + off_y
396
+ new_w = new_w_calc
397
+ new_h = new_h_calc
398
+ target_box_w, target_box_h = new_w, new_h
399
+
400
+ target_w, target_h = _target_size(
401
+ target_box_w,
402
+ target_box_h,
403
+ max_dimension=max_dimension,
404
+ image_scale=image_scale,
405
+ )
406
+ final_img, resized = _downscale_to_target(final_img, target_w, target_h)
407
+ transformed = transformed or resized
408
+
409
+ # ------------------------------------------------------------------
410
+ # Encode and rewrite
411
+ # ------------------------------------------------------------------
412
+ encoded = _encode_pil_to_data_uri(
413
+ final_img,
414
+ img_path,
415
+ compress=compress,
416
+ max_dimension=max_dimension,
417
+ fallback_bytes=raw_bytes if not transformed else None,
418
+ )
419
+ if encoded is None:
420
+ return False, 'encode failed'
421
+ data_uri, _ = encoded
422
+
423
+ _set_href(image, data_uri)
424
+ image.set('x', _format_number(new_x))
425
+ image.set('y', _format_number(new_y))
426
+ image.set('width', _format_number(new_w))
427
+ image.set('height', _format_number(new_h))
428
+ if 'preserveAspectRatio' in image.attrib:
429
+ del image.attrib['preserveAspectRatio']
430
+
431
+ if verbose:
432
+ suffix = ' (cropped)' if transformed else ''
433
+ print(f' [OK] {img_path.name}{suffix}')
434
+ return True, None
435
+
436
+
437
+ def count_office_vector_refs_in_svg(svg_path: str | Path) -> int:
438
+ """Count local EMF/WMF image refs that the embed pass intentionally skips."""
439
+ svg_path = Path(svg_path)
440
+ svg_dir = svg_path.parent.resolve()
441
+ try:
442
+ tree = ET.parse(svg_path)
443
+ except ET.ParseError:
444
+ return 0
445
+ count = 0
446
+ seen: set[int] = set()
447
+ for image in _iter_image_elements(tree.getroot()):
448
+ ident = id(image)
449
+ if ident in seen:
450
+ continue
451
+ seen.add(ident)
452
+ href = _get_href(image)
453
+ if not href or href.startswith('data:'):
454
+ continue
455
+ img_path = _resolve_image_path(href, svg_dir)
456
+ if img_path and img_path.suffix.lower() in _OFFICE_VECTOR_EXTENSIONS:
457
+ count += 1
458
+ return count
459
+
460
+
461
+ def align_and_embed_images_in_svg(
462
+ svg_path: str | Path,
463
+ *,
464
+ dry_run: bool = False,
465
+ verbose: bool = False,
466
+ compress: bool = True,
467
+ max_dimension: int | None = 2560,
468
+ image_scale: float = 2.0,
469
+ ) -> tuple[int, int]:
470
+ """Run the merged align + embed pass on a single SVG file.
471
+
472
+ Returns (processed_count, error_count).
473
+ """
474
+ svg_path = Path(svg_path)
475
+ svg_dir = svg_path.parent.resolve()
476
+
477
+ # Register namespaces for clean serialization
478
+ ET.register_namespace('', SVG_NS)
479
+ ET.register_namespace('xlink', XLINK_NS)
480
+
481
+ try:
482
+ tree = ET.parse(svg_path)
483
+ except ET.ParseError as exc:
484
+ if verbose:
485
+ print(f' [ERROR] {svg_path.name}: parse failed ({exc})')
486
+ return (0, 1)
487
+ root = tree.getroot()
488
+
489
+ # Avoid double-iteration if an element matches both namespaced and
490
+ # bare-tag iteration paths.
491
+ seen: set[int] = set()
492
+ processed = 0
493
+ errors = 0
494
+
495
+ for image in _iter_image_elements(root):
496
+ ident = id(image)
497
+ if ident in seen:
498
+ continue
499
+ seen.add(ident)
500
+
501
+ if dry_run:
502
+ processed += 1
503
+ continue
504
+
505
+ ok, err = _process_one_image(
506
+ image, svg_dir,
507
+ compress=compress, max_dimension=max_dimension,
508
+ image_scale=image_scale, verbose=verbose,
509
+ )
510
+ if ok:
511
+ processed += 1
512
+ elif err:
513
+ errors += 1
514
+ if verbose:
515
+ print(f' [WARN] {svg_path.name}: {err}')
516
+
517
+ if processed > 0 and not dry_run:
518
+ tree.write(svg_path, encoding='utf-8', xml_declaration=False)
519
+
520
+ return (processed, errors)
521
+
522
+
523
+ # ---------------------------------------------------------------------------
524
+ # Standalone CLI (rare; the main entry point is finalize_svg.py)
525
+ # ---------------------------------------------------------------------------
526
+
527
+ def build_parser() -> argparse.ArgumentParser:
528
+ """Build the standalone diagnostic parser."""
529
+ import argparse
530
+ parser = argparse.ArgumentParser(
531
+ description='Align (slice/meet) and Base64-embed all <image> refs in an SVG.',
532
+ )
533
+ parser.add_argument('svg', type=Path, help='SVG file to process in place')
534
+ parser.add_argument('-n', '--dry-run', action='store_true')
535
+ parser.add_argument('-v', '--verbose', action='store_true')
536
+ parser.add_argument('--compress', dest='compress', action='store_true', default=True,
537
+ help='Compress images before embedding (default)')
538
+ parser.add_argument('--no-compress', dest='compress', action='store_false',
539
+ help='Disable image compression')
540
+ parser.add_argument('--max-dimension', type=int, default=2560,
541
+ help='Downscale images larger than this on either axis (default: 2560)')
542
+ parser.add_argument('--image-scale', type=float, default=2.0,
543
+ help='Target pixels per rendered SVG pixel')
544
+ return parser
545
+
546
+
547
+ def main(argv: list[str] | None = None) -> int:
548
+ """Run the standalone diagnostic CLI."""
549
+ parser = build_parser()
550
+ args = parser.parse_args(argv)
551
+
552
+ if not args.svg.exists():
553
+ print(f'Error: file not found: {args.svg}', file=sys.stderr)
554
+ return 1
555
+ if args.max_dimension < 1:
556
+ print('Error: --max-dimension must be >= 1', file=sys.stderr)
557
+ return 1
558
+ if args.image_scale < 1:
559
+ print('Error: --image-scale must be >= 1', file=sys.stderr)
560
+ return 1
561
+
562
+ proc, err = align_and_embed_images_in_svg(
563
+ args.svg,
564
+ dry_run=args.dry_run,
565
+ verbose=args.verbose,
566
+ compress=args.compress,
567
+ max_dimension=args.max_dimension,
568
+ image_scale=args.image_scale,
569
+ )
570
+ print(f'Processed {proc} image(s), {err} error(s)')
571
+ return 1 if err else 0
572
+
573
+
574
+ if __name__ == '__main__':
575
+ raise SystemExit(main())