@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,366 +1,366 @@
1
- #!/usr/bin/env python3
2
- """
3
- PPT Master - Smart Image Cropping Tool
4
-
5
- Smartly crops images based on the preserveAspectRatio attribute of <image> elements in SVG:
6
- - slice: Crop to fill (similar to CSS object-fit: cover)
7
- - meet: Display fully without cropping (similar to CSS object-fit: contain)
8
-
9
- Supports 9 alignment modes:
10
- - xMinYMin / xMidYMin / xMaxYMin (top alignment)
11
- - xMinYMid / xMidYMid / xMaxYMid (vertical center)
12
- - xMinYMax / xMidYMax / xMaxYMax (bottom alignment)
13
-
14
- Usage:
15
- python3 scripts/svg_finalize/crop_images.py <SVG file or directory> [--dry-run]
16
- """
17
-
18
- import os
19
- import re
20
- import hashlib
21
- import sys
22
- import argparse
23
- from pathlib import Path
24
- from xml.etree import ElementTree as ET
25
- from urllib.parse import unquote
26
-
27
- _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
28
- if str(_SCRIPTS_DIR) not in sys.path:
29
- sys.path.insert(0, str(_SCRIPTS_DIR))
30
-
31
- from console_encoding import configure_utf8_stdio # noqa: E402
32
-
33
- configure_utf8_stdio()
34
-
35
- try:
36
- from PIL import Image
37
- except ImportError:
38
- print("Error: PIL (Pillow) is required. Run: pip install Pillow")
39
- exit(1)
40
-
41
-
42
- def parse_preserve_aspect_ratio(attr: str) -> tuple[str, str]:
43
- """
44
- Parse the preserveAspectRatio attribute.
45
-
46
- Returns: (align, meet_or_slice)
47
- align: e.g. 'xMidYMid'
48
- meet_or_slice: 'meet' or 'slice'
49
- """
50
- if not attr:
51
- return ('xMidYMid', 'meet') # Default value
52
-
53
- parts = attr.strip().split()
54
- align = parts[0] if parts else 'xMidYMid'
55
- meet_or_slice = parts[1] if len(parts) > 1 else 'meet'
56
-
57
- return (align, meet_or_slice)
58
-
59
-
60
- def get_crop_anchor(align: str) -> tuple[float, float]:
61
- """
62
- Return the crop anchor point based on the align value.
63
-
64
- Returns: (x_anchor, y_anchor)
65
- x_anchor: 0.0 (left), 0.5 (center), 1.0 (right)
66
- y_anchor: 0.0 (top), 0.5 (center), 1.0 (bottom)
67
- """
68
- x_map = {'xMin': 0.0, 'xMid': 0.5, 'xMax': 1.0}
69
- y_map = {'YMin': 0.0, 'YMid': 0.5, 'YMax': 1.0}
70
-
71
- x_anchor = 0.5
72
- y_anchor = 0.5
73
-
74
- for key, val in x_map.items():
75
- if key in align:
76
- x_anchor = val
77
- break
78
-
79
- for key, val in y_map.items():
80
- if key in align:
81
- y_anchor = val
82
- break
83
-
84
- return (x_anchor, y_anchor)
85
-
86
-
87
- def crop_image_to_size(
88
- img: Image.Image,
89
- target_width: int,
90
- target_height: int,
91
- x_anchor: float = 0.5,
92
- y_anchor: float = 0.5,
93
- ) -> Image.Image:
94
- """
95
- Crop an image to the target aspect ratio, preserving original resolution (no scaling).
96
-
97
- New logic: Only crops the original image to the target aspect ratio without any scaling,
98
- thus preserving the original resolution and clarity.
99
-
100
- Args:
101
- img: PIL Image object
102
- target_width: Target width (used to calculate ratio)
103
- target_height: Target height (used to calculate ratio)
104
- x_anchor: Horizontal anchor (0=left, 0.5=center, 1=right)
105
- y_anchor: Vertical anchor (0=top, 0.5=center, 1=bottom)
106
-
107
- Returns:
108
- Cropped PIL Image object (preserving original resolution)
109
- """
110
- img_width, img_height = img.size
111
-
112
- # Calculate target aspect ratio
113
- target_ratio = target_width / target_height
114
- img_ratio = img_width / img_height
115
-
116
- # Calculate crop region on the original image based on ratio (no scaling)
117
- if img_ratio > target_ratio:
118
- # Original image is wider; crop left and right sides
119
- crop_height = img_height
120
- crop_width = int(img_height * target_ratio)
121
- else:
122
- # Original image is taller; crop top and bottom sides
123
- crop_width = img_width
124
- crop_height = int(img_width / target_ratio)
125
-
126
- # Calculate crop position based on anchor point
127
- extra_width = img_width - crop_width
128
- extra_height = img_height - crop_height
129
-
130
- left = int(extra_width * x_anchor)
131
- top = int(extra_height * y_anchor)
132
- right = left + crop_width
133
- bottom = top + crop_height
134
-
135
- # Crop only, no scaling
136
- return img.crop((left, top, right, bottom))
137
-
138
-
139
- def process_svg_images(
140
- svg_file: str,
141
- output_dir: str | Path | None = None,
142
- dry_run: bool = False,
143
- verbose: bool = True,
144
- ) -> tuple[int, int]:
145
- """
146
- Process images in an SVG file, cropping based on the preserveAspectRatio attribute.
147
-
148
- Args:
149
- svg_file: SVG file path
150
- output_dir: Output directory for cropped images (default: images/cropped/)
151
- dry_run: Preview only, no actual processing
152
- verbose: Verbose output
153
-
154
- Returns:
155
- (processed_count, error_count)
156
- """
157
- svg_path = Path(svg_file)
158
- svg_dir = svg_path.parent
159
-
160
- # Default output directory
161
- if output_dir is None:
162
- # Find the project's images directory
163
- # Parent directory of svg_output or svg_final, under images
164
- project_dir = svg_dir.parent
165
- output_dir = project_dir / 'images' / 'cropped'
166
- else:
167
- output_dir = Path(output_dir)
168
-
169
- # Parse SVG
170
- try:
171
- ET.register_namespace('', 'http://www.w3.org/2000/svg')
172
- ET.register_namespace('xlink', 'http://www.w3.org/1999/xlink')
173
- tree = ET.parse(str(svg_path))
174
- root = tree.getroot()
175
- except Exception as e:
176
- if verbose:
177
- print(f" [ERROR] Failed to parse SVG: {e}")
178
- return (0, 1)
179
-
180
- ns = {'svg': 'http://www.w3.org/2000/svg', 'xlink': 'http://www.w3.org/1999/xlink'}
181
-
182
- processed_count = 0
183
- error_count = 0
184
- modified = False
185
-
186
- # Find all image elements
187
- for image in root.iter('{http://www.w3.org/2000/svg}image'):
188
- # Get href attribute
189
- href = image.get('{http://www.w3.org/1999/xlink}href') or image.get('href')
190
- if not href:
191
- continue
192
-
193
- # Skip Base64 inline images
194
- if href.startswith('data:'):
195
- continue
196
-
197
- # Get preserveAspectRatio attribute
198
- par = image.get('preserveAspectRatio', '')
199
- align, mode = parse_preserve_aspect_ratio(par)
200
-
201
- # Only process slice mode
202
- if mode != 'slice':
203
- continue
204
-
205
- # Get target dimensions
206
- try:
207
- target_width = int(float(image.get('width', 0)))
208
- target_height = int(float(image.get('height', 0)))
209
- except (ValueError, TypeError):
210
- continue
211
-
212
- if target_width <= 0 or target_height <= 0:
213
- continue
214
-
215
- # Parse image path
216
- href_decoded = unquote(href)
217
- if href_decoded.startswith('../'):
218
- img_path = (svg_dir / href_decoded).resolve()
219
- else:
220
- img_path = (svg_dir / href_decoded).resolve()
221
-
222
- if not img_path.exists():
223
- if verbose:
224
- print(f" [SKIP] Image not found: {href}")
225
- continue
226
-
227
- # Get crop anchor point
228
- x_anchor, y_anchor = get_crop_anchor(align)
229
-
230
- if dry_run:
231
- if verbose:
232
- print(f" [DRY] {img_path.name} -> {target_width}x{target_height} "
233
- f"(align: {align}, anchor: {x_anchor},{y_anchor})")
234
- processed_count += 1
235
- continue
236
-
237
- # Create output directory
238
- output_dir.mkdir(parents=True, exist_ok=True)
239
-
240
- try:
241
- # Open and process image
242
- img = Image.open(img_path)
243
- output_is_png = img_path.suffix.lower() == '.png'
244
-
245
- # Preserve alpha for PNG assets such as translucent overlays.
246
- if output_is_png:
247
- if img.mode == 'P':
248
- img = img.convert('RGBA')
249
- elif img.mode not in ('RGBA', 'LA', 'RGB', 'L'):
250
- img = img.convert('RGBA' if 'A' in img.getbands() else 'RGB')
251
- else:
252
- if img.mode in ('RGBA', 'LA'):
253
- background = Image.new('RGB', img.size, (255, 255, 255))
254
- alpha = img.getchannel('A')
255
- background.paste(img.convert('RGB'), mask=alpha)
256
- img = background
257
- elif img.mode == 'P':
258
- img = img.convert('RGB')
259
- elif img.mode not in ('RGB', 'L'):
260
- img = img.convert('RGB')
261
-
262
- # Crop
263
- cropped = crop_image_to_size(img, target_width, target_height, x_anchor, y_anchor)
264
-
265
- # Generate output filename (keep original name, place in cropped directory)
266
- output_filename = img_path.name
267
- output_path = output_dir / output_filename
268
-
269
- # Save
270
- if output_is_png:
271
- cropped.save(output_path, 'PNG', optimize=True)
272
- else:
273
- cropped.save(output_path, 'JPEG', quality=90, optimize=True)
274
-
275
- if verbose:
276
- print(f" [OK] {img_path.name}: {img.size} -> {target_width}x{target_height} "
277
- f"({align})")
278
-
279
- # Update image path in SVG
280
- new_href = f"../images/cropped/{output_filename}"
281
- if image.get('{http://www.w3.org/1999/xlink}href'):
282
- image.set('{http://www.w3.org/1999/xlink}href', new_href)
283
- else:
284
- image.set('href', new_href)
285
-
286
- # Remove preserveAspectRatio (image is now correctly sized)
287
- if 'preserveAspectRatio' in image.attrib:
288
- del image.attrib['preserveAspectRatio']
289
-
290
- modified = True
291
- processed_count += 1
292
-
293
- except Exception as e:
294
- if verbose:
295
- print(f" [ERROR] {img_path.name}: {e}")
296
- error_count += 1
297
-
298
- # Save modified SVG
299
- if modified and not dry_run:
300
- tree.write(str(svg_path), encoding='unicode', xml_declaration=False)
301
-
302
- return (processed_count, error_count)
303
-
304
-
305
- def process_directory(directory: str, dry_run: bool = False, verbose: bool = True) -> tuple[int, int]:
306
- """Process all SVG files in a directory."""
307
- directory_path = Path(directory)
308
- total_processed = 0
309
- total_errors = 0
310
-
311
- for svg_file in directory_path.glob('*.svg'):
312
- if verbose:
313
- print(f" Processing: {svg_file.name}")
314
- processed, errors = process_svg_images(str(svg_file), dry_run=dry_run, verbose=verbose)
315
- total_processed += processed
316
- total_errors += errors
317
-
318
- return (total_processed, total_errors)
319
-
320
-
321
- def main() -> None:
322
- """Run the CLI entry point."""
323
- parser = argparse.ArgumentParser(
324
- description='PPT Master - Smart Image Cropping Tool',
325
- formatter_class=argparse.RawDescriptionHelpFormatter,
326
- epilog='''
327
- Examples:
328
- %(prog)s projects/my_project/svg_output
329
- %(prog)s page_01.svg --dry-run
330
-
331
- preserveAspectRatio usage:
332
- xMidYMid slice Center crop (default)
333
- xMidYMin slice Keep top
334
- xMidYMax slice Keep bottom
335
- xMinYMid slice Keep left
336
- xMaxYMid slice Keep right
337
- xMidYMid meet Display fully, no cropping
338
- '''
339
- )
340
-
341
- parser.add_argument('path', type=Path, help='SVG file or directory')
342
- parser.add_argument('--dry-run', '-n', action='store_true', help='Preview only, no actual processing')
343
- parser.add_argument('--quiet', '-q', action='store_true', help='Quiet mode')
344
-
345
- args = parser.parse_args()
346
-
347
- if not args.path.exists():
348
- print(f"[ERROR] Path not found: {args.path}")
349
- sys.exit(1)
350
-
351
- print("PPT Master - Smart Image Cropping")
352
- print("=" * 50)
353
-
354
- if args.path.is_file():
355
- processed, errors = process_svg_images(str(args.path), dry_run=args.dry_run,
356
- verbose=not args.quiet)
357
- else:
358
- processed, errors = process_directory(str(args.path), dry_run=args.dry_run,
359
- verbose=not args.quiet)
360
-
361
- print()
362
- print(f"Done: {processed} image(s) cropped, {errors} error(s)")
363
-
364
-
365
- if __name__ == '__main__':
366
- main()
1
+ #!/usr/bin/env python3
2
+ """
3
+ PPT Master - Smart Image Cropping Tool
4
+
5
+ Smartly crops images based on the preserveAspectRatio attribute of <image> elements in SVG:
6
+ - slice: Crop to fill (similar to CSS object-fit: cover)
7
+ - meet: Display fully without cropping (similar to CSS object-fit: contain)
8
+
9
+ Supports 9 alignment modes:
10
+ - xMinYMin / xMidYMin / xMaxYMin (top alignment)
11
+ - xMinYMid / xMidYMid / xMaxYMid (vertical center)
12
+ - xMinYMax / xMidYMax / xMaxYMax (bottom alignment)
13
+
14
+ Usage:
15
+ python3 scripts/svg_finalize/crop_images.py <SVG file or directory> [--dry-run]
16
+ """
17
+
18
+ import os
19
+ import re
20
+ import hashlib
21
+ import sys
22
+ import argparse
23
+ from pathlib import Path
24
+ from xml.etree import ElementTree as ET
25
+ from urllib.parse import unquote
26
+
27
+ _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
28
+ if str(_SCRIPTS_DIR) not in sys.path:
29
+ sys.path.insert(0, str(_SCRIPTS_DIR))
30
+
31
+ from console_encoding import configure_utf8_stdio # noqa: E402
32
+
33
+ configure_utf8_stdio()
34
+
35
+ try:
36
+ from PIL import Image
37
+ except ImportError:
38
+ print("Error: PIL (Pillow) is required. Run: pip install Pillow")
39
+ exit(1)
40
+
41
+
42
+ def parse_preserve_aspect_ratio(attr: str) -> tuple[str, str]:
43
+ """
44
+ Parse the preserveAspectRatio attribute.
45
+
46
+ Returns: (align, meet_or_slice)
47
+ align: e.g. 'xMidYMid'
48
+ meet_or_slice: 'meet' or 'slice'
49
+ """
50
+ if not attr:
51
+ return ('xMidYMid', 'meet') # Default value
52
+
53
+ parts = attr.strip().split()
54
+ align = parts[0] if parts else 'xMidYMid'
55
+ meet_or_slice = parts[1] if len(parts) > 1 else 'meet'
56
+
57
+ return (align, meet_or_slice)
58
+
59
+
60
+ def get_crop_anchor(align: str) -> tuple[float, float]:
61
+ """
62
+ Return the crop anchor point based on the align value.
63
+
64
+ Returns: (x_anchor, y_anchor)
65
+ x_anchor: 0.0 (left), 0.5 (center), 1.0 (right)
66
+ y_anchor: 0.0 (top), 0.5 (center), 1.0 (bottom)
67
+ """
68
+ x_map = {'xMin': 0.0, 'xMid': 0.5, 'xMax': 1.0}
69
+ y_map = {'YMin': 0.0, 'YMid': 0.5, 'YMax': 1.0}
70
+
71
+ x_anchor = 0.5
72
+ y_anchor = 0.5
73
+
74
+ for key, val in x_map.items():
75
+ if key in align:
76
+ x_anchor = val
77
+ break
78
+
79
+ for key, val in y_map.items():
80
+ if key in align:
81
+ y_anchor = val
82
+ break
83
+
84
+ return (x_anchor, y_anchor)
85
+
86
+
87
+ def crop_image_to_size(
88
+ img: Image.Image,
89
+ target_width: int,
90
+ target_height: int,
91
+ x_anchor: float = 0.5,
92
+ y_anchor: float = 0.5,
93
+ ) -> Image.Image:
94
+ """
95
+ Crop an image to the target aspect ratio, preserving original resolution (no scaling).
96
+
97
+ New logic: Only crops the original image to the target aspect ratio without any scaling,
98
+ thus preserving the original resolution and clarity.
99
+
100
+ Args:
101
+ img: PIL Image object
102
+ target_width: Target width (used to calculate ratio)
103
+ target_height: Target height (used to calculate ratio)
104
+ x_anchor: Horizontal anchor (0=left, 0.5=center, 1=right)
105
+ y_anchor: Vertical anchor (0=top, 0.5=center, 1=bottom)
106
+
107
+ Returns:
108
+ Cropped PIL Image object (preserving original resolution)
109
+ """
110
+ img_width, img_height = img.size
111
+
112
+ # Calculate target aspect ratio
113
+ target_ratio = target_width / target_height
114
+ img_ratio = img_width / img_height
115
+
116
+ # Calculate crop region on the original image based on ratio (no scaling)
117
+ if img_ratio > target_ratio:
118
+ # Original image is wider; crop left and right sides
119
+ crop_height = img_height
120
+ crop_width = int(img_height * target_ratio)
121
+ else:
122
+ # Original image is taller; crop top and bottom sides
123
+ crop_width = img_width
124
+ crop_height = int(img_width / target_ratio)
125
+
126
+ # Calculate crop position based on anchor point
127
+ extra_width = img_width - crop_width
128
+ extra_height = img_height - crop_height
129
+
130
+ left = int(extra_width * x_anchor)
131
+ top = int(extra_height * y_anchor)
132
+ right = left + crop_width
133
+ bottom = top + crop_height
134
+
135
+ # Crop only, no scaling
136
+ return img.crop((left, top, right, bottom))
137
+
138
+
139
+ def process_svg_images(
140
+ svg_file: str,
141
+ output_dir: str | Path | None = None,
142
+ dry_run: bool = False,
143
+ verbose: bool = True,
144
+ ) -> tuple[int, int]:
145
+ """
146
+ Process images in an SVG file, cropping based on the preserveAspectRatio attribute.
147
+
148
+ Args:
149
+ svg_file: SVG file path
150
+ output_dir: Output directory for cropped images (default: images/cropped/)
151
+ dry_run: Preview only, no actual processing
152
+ verbose: Verbose output
153
+
154
+ Returns:
155
+ (processed_count, error_count)
156
+ """
157
+ svg_path = Path(svg_file)
158
+ svg_dir = svg_path.parent
159
+
160
+ # Default output directory
161
+ if output_dir is None:
162
+ # Find the project's images directory
163
+ # Parent directory of svg_output or svg_final, under images
164
+ project_dir = svg_dir.parent
165
+ output_dir = project_dir / 'images' / 'cropped'
166
+ else:
167
+ output_dir = Path(output_dir)
168
+
169
+ # Parse SVG
170
+ try:
171
+ ET.register_namespace('', 'http://www.w3.org/2000/svg')
172
+ ET.register_namespace('xlink', 'http://www.w3.org/1999/xlink')
173
+ tree = ET.parse(str(svg_path))
174
+ root = tree.getroot()
175
+ except Exception as e:
176
+ if verbose:
177
+ print(f" [ERROR] Failed to parse SVG: {e}")
178
+ return (0, 1)
179
+
180
+ ns = {'svg': 'http://www.w3.org/2000/svg', 'xlink': 'http://www.w3.org/1999/xlink'}
181
+
182
+ processed_count = 0
183
+ error_count = 0
184
+ modified = False
185
+
186
+ # Find all image elements
187
+ for image in root.iter('{http://www.w3.org/2000/svg}image'):
188
+ # Get href attribute
189
+ href = image.get('{http://www.w3.org/1999/xlink}href') or image.get('href')
190
+ if not href:
191
+ continue
192
+
193
+ # Skip Base64 inline images
194
+ if href.startswith('data:'):
195
+ continue
196
+
197
+ # Get preserveAspectRatio attribute
198
+ par = image.get('preserveAspectRatio', '')
199
+ align, mode = parse_preserve_aspect_ratio(par)
200
+
201
+ # Only process slice mode
202
+ if mode != 'slice':
203
+ continue
204
+
205
+ # Get target dimensions
206
+ try:
207
+ target_width = int(float(image.get('width', 0)))
208
+ target_height = int(float(image.get('height', 0)))
209
+ except (ValueError, TypeError):
210
+ continue
211
+
212
+ if target_width <= 0 or target_height <= 0:
213
+ continue
214
+
215
+ # Parse image path
216
+ href_decoded = unquote(href)
217
+ if href_decoded.startswith('../'):
218
+ img_path = (svg_dir / href_decoded).resolve()
219
+ else:
220
+ img_path = (svg_dir / href_decoded).resolve()
221
+
222
+ if not img_path.exists():
223
+ if verbose:
224
+ print(f" [SKIP] Image not found: {href}")
225
+ continue
226
+
227
+ # Get crop anchor point
228
+ x_anchor, y_anchor = get_crop_anchor(align)
229
+
230
+ if dry_run:
231
+ if verbose:
232
+ print(f" [DRY] {img_path.name} -> {target_width}x{target_height} "
233
+ f"(align: {align}, anchor: {x_anchor},{y_anchor})")
234
+ processed_count += 1
235
+ continue
236
+
237
+ # Create output directory
238
+ output_dir.mkdir(parents=True, exist_ok=True)
239
+
240
+ try:
241
+ # Open and process image
242
+ img = Image.open(img_path)
243
+ output_is_png = img_path.suffix.lower() == '.png'
244
+
245
+ # Preserve alpha for PNG assets such as translucent overlays.
246
+ if output_is_png:
247
+ if img.mode == 'P':
248
+ img = img.convert('RGBA')
249
+ elif img.mode not in ('RGBA', 'LA', 'RGB', 'L'):
250
+ img = img.convert('RGBA' if 'A' in img.getbands() else 'RGB')
251
+ else:
252
+ if img.mode in ('RGBA', 'LA'):
253
+ background = Image.new('RGB', img.size, (255, 255, 255))
254
+ alpha = img.getchannel('A')
255
+ background.paste(img.convert('RGB'), mask=alpha)
256
+ img = background
257
+ elif img.mode == 'P':
258
+ img = img.convert('RGB')
259
+ elif img.mode not in ('RGB', 'L'):
260
+ img = img.convert('RGB')
261
+
262
+ # Crop
263
+ cropped = crop_image_to_size(img, target_width, target_height, x_anchor, y_anchor)
264
+
265
+ # Generate output filename (keep original name, place in cropped directory)
266
+ output_filename = img_path.name
267
+ output_path = output_dir / output_filename
268
+
269
+ # Save
270
+ if output_is_png:
271
+ cropped.save(output_path, 'PNG', optimize=True)
272
+ else:
273
+ cropped.save(output_path, 'JPEG', quality=90, optimize=True)
274
+
275
+ if verbose:
276
+ print(f" [OK] {img_path.name}: {img.size} -> {target_width}x{target_height} "
277
+ f"({align})")
278
+
279
+ # Update image path in SVG
280
+ new_href = f"../images/cropped/{output_filename}"
281
+ if image.get('{http://www.w3.org/1999/xlink}href'):
282
+ image.set('{http://www.w3.org/1999/xlink}href', new_href)
283
+ else:
284
+ image.set('href', new_href)
285
+
286
+ # Remove preserveAspectRatio (image is now correctly sized)
287
+ if 'preserveAspectRatio' in image.attrib:
288
+ del image.attrib['preserveAspectRatio']
289
+
290
+ modified = True
291
+ processed_count += 1
292
+
293
+ except Exception as e:
294
+ if verbose:
295
+ print(f" [ERROR] {img_path.name}: {e}")
296
+ error_count += 1
297
+
298
+ # Save modified SVG
299
+ if modified and not dry_run:
300
+ tree.write(str(svg_path), encoding='unicode', xml_declaration=False)
301
+
302
+ return (processed_count, error_count)
303
+
304
+
305
+ def process_directory(directory: str, dry_run: bool = False, verbose: bool = True) -> tuple[int, int]:
306
+ """Process all SVG files in a directory."""
307
+ directory_path = Path(directory)
308
+ total_processed = 0
309
+ total_errors = 0
310
+
311
+ for svg_file in directory_path.glob('*.svg'):
312
+ if verbose:
313
+ print(f" Processing: {svg_file.name}")
314
+ processed, errors = process_svg_images(str(svg_file), dry_run=dry_run, verbose=verbose)
315
+ total_processed += processed
316
+ total_errors += errors
317
+
318
+ return (total_processed, total_errors)
319
+
320
+
321
+ def main() -> None:
322
+ """Run the CLI entry point."""
323
+ parser = argparse.ArgumentParser(
324
+ description='PPT Master - Smart Image Cropping Tool',
325
+ formatter_class=argparse.RawDescriptionHelpFormatter,
326
+ epilog='''
327
+ Examples:
328
+ %(prog)s projects/my_project/svg_output
329
+ %(prog)s page_01.svg --dry-run
330
+
331
+ preserveAspectRatio usage:
332
+ xMidYMid slice Center crop (default)
333
+ xMidYMin slice Keep top
334
+ xMidYMax slice Keep bottom
335
+ xMinYMid slice Keep left
336
+ xMaxYMid slice Keep right
337
+ xMidYMid meet Display fully, no cropping
338
+ '''
339
+ )
340
+
341
+ parser.add_argument('path', type=Path, help='SVG file or directory')
342
+ parser.add_argument('--dry-run', '-n', action='store_true', help='Preview only, no actual processing')
343
+ parser.add_argument('--quiet', '-q', action='store_true', help='Quiet mode')
344
+
345
+ args = parser.parse_args()
346
+
347
+ if not args.path.exists():
348
+ print(f"[ERROR] Path not found: {args.path}")
349
+ sys.exit(1)
350
+
351
+ print("PPT Master - Smart Image Cropping")
352
+ print("=" * 50)
353
+
354
+ if args.path.is_file():
355
+ processed, errors = process_svg_images(str(args.path), dry_run=args.dry_run,
356
+ verbose=not args.quiet)
357
+ else:
358
+ processed, errors = process_directory(str(args.path), dry_run=args.dry_run,
359
+ verbose=not args.quiet)
360
+
361
+ print()
362
+ print(f"Done: {processed} image(s) cropped, {errors} error(s)")
363
+
364
+
365
+ if __name__ == '__main__':
366
+ main()