@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.7

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 (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
  4. package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
  5. package/bundled-assets/skill/LICENSE +21 -0
  6. package/bundled-assets/skill/README.md +61 -0
  7. package/bundled-assets/skill/SKILL.md +185 -0
  8. package/bundled-assets/skill/references/art-directions.md +99 -0
  9. package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
  10. package/bundled-assets/skill/references/design-baseline.txt +1 -0
  11. package/bundled-assets/skill/references/prompt-compiler.md +99 -0
  12. package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
  13. package/bundled-assets/skill/references/staged-pptx.md +71 -0
  14. package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
  15. package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
  16. package/bundled-assets/skill/scripts/brand_ref.py +776 -0
  17. package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
  18. package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
  19. package/bundled-assets/skill/scripts/export_images.py +280 -0
  20. package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
  21. package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
  22. package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
  23. package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
  24. package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
  25. package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
  26. package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
  27. package/bundled-assets/skill/scripts/render_gradient.py +258 -0
  28. package/bundled-assets/skill/scripts/slide_brand.py +111 -0
  29. package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
  30. package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
  31. package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
  32. package/bundled-assets/skill/vendor/README.md +4 -0
  33. package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
  34. package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
  35. package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
  36. package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
  37. package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
  38. package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
  39. package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
  40. package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
  41. package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
  42. package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
  43. package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
  44. package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
  45. package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
  46. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
  47. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
  48. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
  49. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
  50. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
  51. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
  52. package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
  53. package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
  54. package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
  55. package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
  56. package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
  57. package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
  58. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
  59. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
  60. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
  61. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
  62. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
  63. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
  64. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
  65. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
  66. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
  67. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
  68. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
  69. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
  70. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
  71. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
  72. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
  73. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
  74. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
  75. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
  76. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
  77. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
  78. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
  79. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
  80. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
  81. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
  82. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
  83. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
  84. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
  85. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
  86. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
  87. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
  88. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
  89. package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
  90. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
  91. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
  92. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
  93. package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
  94. package/cordis.patch.yml +3 -0
  95. package/lib/client.js +11282 -0
  96. package/lib/index.js +2638 -0
  97. package/package.json +140 -4
@@ -0,0 +1,528 @@
1
+ #!/usr/bin/env python3
2
+ """Prepare image-to-image asset sheet prompts and slice transparent PNGs."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageOps
12
+
13
+ _GRID = {
14
+ 1: (1, 1, "1024x1024"),
15
+ 2: (2, 1, "1536x1024"),
16
+ 3: (3, 1, "1536x1024"),
17
+ 4: (2, 2, "1536x1024"),
18
+ 5: (3, 2, "1536x1024"),
19
+ 6: (3, 2, "1536x1024"),
20
+ }
21
+ _GRID_BY_RATIO = {
22
+ "16:9": _GRID,
23
+ "3:4": {
24
+ 1: (1, 1, "1104x1472"),
25
+ 2: (1, 2, "1104x1472"),
26
+ 3: (1, 3, "1104x1472"),
27
+ 4: (2, 2, "1104x1472"),
28
+ 5: (2, 3, "1104x1472"),
29
+ 6: (2, 3, "1104x1472"),
30
+ },
31
+ "9:16": {
32
+ 1: (1, 1, "864x1536"),
33
+ 2: (1, 2, "864x1536"),
34
+ 3: (1, 3, "864x1536"),
35
+ 4: (2, 2, "1104x1472"),
36
+ 5: (2, 3, "1104x1472"),
37
+ 6: (2, 3, "1104x1472"),
38
+ },
39
+ "1:1": {
40
+ 1: (1, 1, "1024x1024"),
41
+ 2: (2, 1, "1536x1024"),
42
+ 3: (3, 1, "1536x1024"),
43
+ 4: (2, 2, "1024x1024"),
44
+ 5: (3, 2, "1536x1024"),
45
+ 6: (3, 2, "1536x1024"),
46
+ },
47
+ }
48
+ _SAFE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}")
49
+ _SOLID_RUN = re.compile(rb"\xff+")
50
+ _EDGE_MARGIN = 4
51
+
52
+
53
+ def _normalize_ratio(ratio: str | None) -> str:
54
+ if not ratio:
55
+ return "16:9"
56
+ tok = str(ratio).strip().lower().replace("×", "x").replace("/", ":")
57
+ aliases = {
58
+ "1920x1080": "16:9",
59
+ "1536x864": "16:9",
60
+ "1536x1024": "16:9",
61
+ "1080x1440": "3:4",
62
+ "1104x1472": "3:4",
63
+ "1080x1920": "9:16",
64
+ "864x1536": "9:16",
65
+ "1440x1440": "1:1",
66
+ "1024x1024": "1:1",
67
+ }
68
+ tok = aliases.get(tok, tok)
69
+ if tok not in _GRID_BY_RATIO:
70
+ raise ValueError(f"Unsupported ratio: {ratio!r} (expected '16:9', '3:4', '9:16', or '1:1').")
71
+ return tok
72
+
73
+
74
+ def grid_for(n: int, ratio: str | None = None) -> tuple[int, int, str]:
75
+ table = _GRID_BY_RATIO[_normalize_ratio(ratio)]
76
+ if n not in table:
77
+ raise ValueError("Expected 1–6 items per asset sheet.")
78
+ return table[n]
79
+
80
+
81
+ def _valid_grids_for(n: int) -> set[tuple[int, int]]:
82
+ return {tbl[n][:2] for tbl in _GRID_BY_RATIO.values() if n in tbl}
83
+
84
+
85
+ def _validate_names(names: list[str]) -> None:
86
+ if any(not isinstance(name, str) or not _SAFE_NAME.fullmatch(name) for name in names):
87
+ raise ValueError("Names must start with an ASCII letter or digit and contain only letters, digits, underscores, or hyphens (up to 64 characters).")
88
+ if len({name.lower() for name in names}) != len(names):
89
+ raise ValueError("Item names must be unique, ignoring case.")
90
+
91
+
92
+ def build_prompt(items: list[dict[str, str]], cols: int, rows: int) -> str:
93
+ if not isinstance(items, list) or not all(isinstance(item, dict) for item in items):
94
+ raise ValueError("items must be a list of objects with name and description.")
95
+ if (cols, rows) not in _valid_grids_for(len(items)):
96
+ raise ValueError("Grid dimensions do not match the number of items.")
97
+ _validate_names([item.get("name") for item in items])
98
+ lines = [
99
+ "图 1 是一页幻灯片设计稿,仅作物件参考。将下列物件重画成透明背景上的独立素材。",
100
+ f"按从左到右、从上到下的顺序排成 {cols} 列 × {rows} 行的网格:",
101
+ ]
102
+ for index, item in enumerate(items):
103
+ description = item.get("description")
104
+ if not isinstance(description, str) or not description.strip():
105
+ raise ValueError(f"Item {item['name']!r} needs a non-empty description.")
106
+ row, col = divmod(index, cols)
107
+ lines.append(f"第{'一二三'[row]}行第 {col + 1} 格({item['name']}):{description.strip()}。")
108
+ if len(items) < cols * rows:
109
+ lines.append("未指定物件的格子保持完全透明。")
110
+ lines.extend([
111
+ "每个物件完整地居中放在自己的格子里,四周留足透明空白,不碰格子边缘,彼此不重叠。",
112
+ "画法、配色、线条粗细、材质与图 1 一致。原稿边缘切掉的部分,用同样的画法补全。",
113
+ "保持边缘干净,不要外发光、彩色光晕、投影或额外的底座和卡片。仅保留物件描述明确要求的文字,不添加素材名、标签或编号。",
114
+ ])
115
+ return "\n".join(lines)
116
+
117
+
118
+ def _component_runs(mask: Image.Image) -> list[list[tuple[int, int, int]]]:
119
+ """Group horizontal foreground runs by 8-connectedness."""
120
+ pixels = mask.tobytes()
121
+ width, height = mask.size
122
+ parents: list[int] = []
123
+ runs: list[tuple[int, int, int]] = []
124
+ previous: list[int] = []
125
+
126
+ def root(index: int) -> int:
127
+ while index != parents[index]:
128
+ parents[index] = parents[parents[index]]
129
+ index = parents[index]
130
+ return index
131
+
132
+ for y in range(height):
133
+ offset = y * width
134
+ current = []
135
+ start = 0
136
+ for match in _SOLID_RUN.finditer(pixels, offset, offset + width):
137
+ left, right = match.start() - offset, match.end() - offset
138
+ index = len(runs)
139
+ runs.append((left, y, right))
140
+ parents.append(index)
141
+ current.append(index)
142
+ while start < len(previous) and runs[previous[start]][2] < left:
143
+ start += 1
144
+ for neighbor_index in range(start, len(previous)):
145
+ neighbor = previous[neighbor_index]
146
+ if runs[neighbor][0] > right:
147
+ break
148
+ parents[root(neighbor)] = root(index)
149
+ previous = current
150
+
151
+ components: dict[int, list[tuple[int, int, int]]] = {}
152
+ for index, run in enumerate(runs):
153
+ components.setdefault(root(index), []).append(run)
154
+ return list(components.values())
155
+
156
+
157
+ def _auto_matte_opaque_sheet(sheet: Image.Image, cols: int, rows: int) -> Image.Image | None:
158
+ """Fallback border flood-fill matting when an image backend returns an opaque solid-color sheet.
159
+
160
+ Returns a new RGBA image with transparent background (and decontaminated anti-aliased fringe)
161
+ only when the outer perimeter is clearly a uniform solid backdrop (>=75% within RGB dist <=28).
162
+ Returns None if the sheet has a busy/textured background that cannot be cleanly keyed.
163
+ """
164
+ from collections import deque
165
+
166
+ width, height = sheet.size
167
+ if width < 16 or height < 16:
168
+ return None
169
+ rgb = sheet.convert("RGB")
170
+ raw = rgb.tobytes()
171
+ total_px = width * height
172
+
173
+ # Sample outer 2px perimeter to detect dominant background color
174
+ samples_r: list[int] = []
175
+ samples_g: list[int] = []
176
+ samples_b: list[int] = []
177
+ step_x = max(1, width // 160)
178
+ step_y = max(1, height // 160)
179
+ for x in range(0, width, step_x):
180
+ for y in (0, 1, height - 2, height - 1):
181
+ off = (y * width + x) * 3
182
+ samples_r.append(raw[off])
183
+ samples_g.append(raw[off + 1])
184
+ samples_b.append(raw[off + 2])
185
+ for y in range(0, height, step_y):
186
+ for x in (0, 1, width - 2, width - 1):
187
+ off = (y * width + x) * 3
188
+ samples_r.append(raw[off])
189
+ samples_g.append(raw[off + 1])
190
+ samples_b.append(raw[off + 2])
191
+
192
+ if not samples_r:
193
+ return None
194
+ samples_r.sort()
195
+ samples_g.sort()
196
+ samples_b.sort()
197
+ mid = len(samples_r) // 2
198
+ br, bg, bb = samples_r[mid], samples_g[mid], samples_b[mid]
199
+
200
+ # Verify perimeter is predominantly uniform (solid white/gray/chroma backdrop)
201
+ uniform_sq = 28 * 28
202
+ inliers = 0
203
+ for r, g, b in zip(samples_r, samples_g, samples_b):
204
+ dr, dg, db = r - br, g - bg, b - bb
205
+ if dr * dr + dg * dg + db * db <= uniform_sq:
206
+ inliers += 1
207
+ if inliers / len(samples_r) < 0.75:
208
+ return None
209
+
210
+ # 4-connected BFS flood-fill from canvas perimeter ONLY through strict core background pixels
211
+ # (dist <= soft_lo) so light-gray foreground elements and cross-cell objects are never punctured.
212
+ # A separate 1-pixel fringe pass afterwards softens and decontaminates immediate border neighbors.
213
+ soft_lo = 22.0
214
+ soft_hi = 44.0
215
+ soft_lo_sq = int(soft_lo * soft_lo)
216
+ soft_hi_sq = int(soft_hi * soft_hi)
217
+ visited = bytearray(total_px) # 1 = flooded core background
218
+ q: deque[int] = deque()
219
+
220
+ def _try_seed(idx: int) -> None:
221
+ if visited[idx]:
222
+ return
223
+ off = idx * 3
224
+ dr = raw[off] - br
225
+ dg = raw[off + 1] - bg
226
+ db = raw[off + 2] - bb
227
+ if dr * dr + dg * dg + db * db <= soft_lo_sq:
228
+ visited[idx] = 1
229
+ q.append(idx)
230
+
231
+ for x in range(width):
232
+ _try_seed(x)
233
+ _try_seed((height - 1) * width + x)
234
+ for y in range(height):
235
+ _try_seed(y * width)
236
+ _try_seed(y * width + (width - 1))
237
+
238
+ while q:
239
+ idx = q.popleft()
240
+ x = idx % width
241
+ y = idx // width
242
+ if x > 0:
243
+ n = idx - 1
244
+ if not visited[n]:
245
+ off = n * 3
246
+ dr, dg, db = raw[off] - br, raw[off + 1] - bg, raw[off + 2] - bb
247
+ if dr * dr + dg * dg + db * db <= soft_lo_sq:
248
+ visited[n] = 1
249
+ q.append(n)
250
+ if x + 1 < width:
251
+ n = idx + 1
252
+ if not visited[n]:
253
+ off = n * 3
254
+ dr, dg, db = raw[off] - br, raw[off + 1] - bg, raw[off + 2] - bb
255
+ if dr * dr + dg * dg + db * db <= soft_lo_sq:
256
+ visited[n] = 1
257
+ q.append(n)
258
+ if y > 0:
259
+ n = idx - width
260
+ if not visited[n]:
261
+ off = n * 3
262
+ dr, dg, db = raw[off] - br, raw[off + 1] - bg, raw[off + 2] - bb
263
+ if dr * dr + dg * dg + db * db <= soft_lo_sq:
264
+ visited[n] = 1
265
+ q.append(n)
266
+ if y + 1 < height:
267
+ n = idx + width
268
+ if not visited[n]:
269
+ off = n * 3
270
+ dr, dg, db = raw[off] - br, raw[off + 1] - bg, raw[off + 2] - bb
271
+ if dr * dr + dg * dg + db * db <= soft_lo_sq:
272
+ visited[n] = 1
273
+ q.append(n)
274
+
275
+ # Single 1-pixel fringe pass: soften only immediate 4-neighbors of flooded background pixels
276
+ # without propagating further into light foreground regions.
277
+ fringe = bytearray(total_px)
278
+ for idx in range(total_px):
279
+ if visited[idx]:
280
+ continue
281
+ x = idx % width
282
+ y = idx // width
283
+ if (
284
+ (x > 0 and visited[idx - 1])
285
+ or (x + 1 < width and visited[idx + 1])
286
+ or (y > 0 and visited[idx - width])
287
+ or (y + 1 < height and visited[idx + width])
288
+ ):
289
+ off = idx * 3
290
+ dr, dg, db = raw[off] - br, raw[off + 1] - bg, raw[off + 2] - bb
291
+ if dr * dr + dg * dg + db * db <= soft_hi_sq:
292
+ fringe[idx] = 1
293
+
294
+ bg_count = 0
295
+ out_rgba = bytearray(total_px * 4)
296
+ span = soft_hi - soft_lo
297
+ for idx in range(total_px):
298
+ off3 = idx * 3
299
+ off4 = idx * 4
300
+ if visited[idx]:
301
+ out_rgba[off4 + 3] = 0
302
+ bg_count += 1
303
+ continue
304
+ r, g, b = raw[off3], raw[off3 + 1], raw[off3 + 2]
305
+ if not fringe[idx]:
306
+ out_rgba[off4] = r
307
+ out_rgba[off4 + 1] = g
308
+ out_rgba[off4 + 2] = b
309
+ out_rgba[off4 + 3] = 255
310
+ continue
311
+ dr, dg, db = r - br, g - bg, b - bb
312
+ dist = (dr * dr + dg * dg + db * db) ** 0.5
313
+ a_f = min(1.0, max(0.0, (dist - soft_lo) / span))
314
+ alpha_byte = int(round(a_f * 255))
315
+ if alpha_byte <= 16:
316
+ out_rgba[off4 + 3] = 0
317
+ bg_count += 1
318
+ else:
319
+ denom = max(0.25, a_f)
320
+ out_rgba[off4] = min(255, max(0, int(round((r - (1.0 - a_f) * br) / denom))))
321
+ out_rgba[off4 + 1] = min(255, max(0, int(round((g - (1.0 - a_f) * bg) / denom))))
322
+ out_rgba[off4 + 2] = min(255, max(0, int(round((b - (1.0 - a_f) * bb) / denom))))
323
+ out_rgba[off4 + 3] = alpha_byte
324
+
325
+ bg_ratio = bg_count / float(total_px)
326
+ if bg_ratio < 0.15 or bg_ratio > 0.995:
327
+ return None
328
+ return Image.frombytes("RGBA", (width, height), bytes(out_rgba))
329
+
330
+
331
+ def slice_sheet(sheet_path, names, cols, rows, out_dir, pad=24, *, fmt: str = "png", quality: int = 88) -> list[dict]:
332
+ if (cols, rows) not in _valid_grids_for(len(names)):
333
+ raise ValueError("Grid dimensions do not match the number of items.")
334
+ _validate_names(names)
335
+ fmt_tok = (fmt or "png").strip().lower()
336
+ if fmt_tok not in ("png", "webp"):
337
+ raise ValueError(f"Unsupported output format: {fmt!r} (expected png|webp)")
338
+ if pad < 0:
339
+ raise ValueError("pad must be non-negative.")
340
+ with Image.open(sheet_path) as source:
341
+ sheet = source.convert("RGBA")
342
+ width, height = sheet.size
343
+ alpha = sheet.getchannel("A")
344
+ auto_matted = False
345
+ if alpha.getextrema()[0] == 255:
346
+ matted = _auto_matte_opaque_sheet(sheet, cols, rows)
347
+ if matted is None:
348
+ raise ValueError("Asset sheet is fully opaque. The image backend did not return transparency.")
349
+ sheet = matted
350
+ alpha = sheet.getchannel("A")
351
+ auto_matted = True
352
+
353
+ solid = alpha.point(lambda value: 255 if value > 16 else 0)
354
+ solid_pixels = solid.tobytes()
355
+ cell_runs: list[list[tuple[int, int, int]]] = [[] for _ in names]
356
+ for component in _component_runs(solid.filter(ImageFilter.MaxFilter(3))):
357
+ # Dilation joins narrow gaps and keeps a one-pixel antialiased fringe.
358
+ # Count original foreground pixels to discard specks.
359
+ area = sum(solid_pixels.count(b"\xff", y * width + left, y * width + right) for left, y, right in component)
360
+ if area < 6:
361
+ continue
362
+ run_area = sum(right - left for left, _, right in component)
363
+ cx = sum((left + right) * (right - left) for left, _, right in component) / (2 * run_area)
364
+ cy = sum((y + 0.5) * (right - left) for left, y, right in component) / run_area
365
+ index = int(cy * rows / height) * cols + int(cx * cols / width)
366
+ if index < len(names):
367
+ cell_runs[index].extend(component)
368
+
369
+ out_dir = Path(out_dir)
370
+ out_dir.mkdir(parents=True, exist_ok=True)
371
+ results = []
372
+ for index, (name, runs) in enumerate(zip(names, cell_runs)):
373
+ if not runs:
374
+ results.append({"name": name, "path": None, "size": None, "flags": ["empty"]})
375
+ continue
376
+ mask = Image.new("L", sheet.size)
377
+ draw = ImageDraw.Draw(mask)
378
+ for left, y, right in runs:
379
+ draw.line((left, y, right - 1, y), fill=255)
380
+ left, top, right, bottom = ImageChops.multiply(solid, mask).getbbox()
381
+ row, col = divmod(index, cols)
382
+ flags = []
383
+ if (
384
+ left - col * width / cols <= _EDGE_MARGIN
385
+ or (col + 1) * width / cols - right <= _EDGE_MARGIN
386
+ or top - row * height / rows <= _EDGE_MARGIN
387
+ or (row + 1) * height / rows - bottom <= _EDGE_MARGIN
388
+ ):
389
+ flags.append("touches_cell_edge")
390
+ if min(left, top, width - right, height - bottom) <= _EDGE_MARGIN:
391
+ flags.append("touches_canvas_edge")
392
+
393
+ box = (max(0, left - pad), max(0, top - pad), min(width, right + pad), min(height, bottom + pad))
394
+ asset = sheet.crop(box)
395
+ asset.putalpha(ImageChops.multiply(asset.getchannel("A"), mask.crop(box)))
396
+ path = out_dir / f"{name}.{fmt_tok}"
397
+ if fmt_tok == "webp":
398
+ q = max(40, min(100, int(quality)))
399
+ asset.save(path, format="WEBP", quality=q, method=4)
400
+ else:
401
+ asset.save(path)
402
+ item_res: dict[str, Any] = {"name": name, "path": str(path), "size": list(asset.size), "flags": flags}
403
+ bleed_edges = _detect_bleed_edges(asset)
404
+ if bleed_edges:
405
+ item_res["bleed_edges"] = bleed_edges
406
+ item_res["anchor_css"] = " ".join(f"{side}: 0;" for side in bleed_edges)
407
+ if auto_matted:
408
+ item_res["auto_matted"] = True
409
+ results.append(item_res)
410
+ return results
411
+
412
+
413
+ def _detect_bleed_edges(asset: Image.Image, alpha_threshold: int = 160) -> list[str]:
414
+ """Return sprite edges ('top','bottom','left','right') with a hard flush opaque cut."""
415
+ if asset.mode != "RGBA":
416
+ return []
417
+ w, h = asset.size
418
+ if w < 16 or h < 16:
419
+ return []
420
+ alpha = asset.getchannel("A")
421
+ lo, _ = alpha.getextrema()
422
+ if lo >= 248:
423
+ return []
424
+ px = alpha.load()
425
+ edges = (
426
+ ("top", [max(int(px[x, 0]), int(px[x, min(1, h - 1)])) for x in range(w)]),
427
+ ("bottom", [max(int(px[x, h - 1]), int(px[x, max(0, h - 2)])) for x in range(w)]),
428
+ ("left", [max(int(px[0, y]), int(px[min(1, w - 1), y])) for y in range(h)]),
429
+ ("right", [max(int(px[w - 1, y]), int(px[max(0, w - 2), y])) for y in range(h)]),
430
+ )
431
+ bleed: list[str] = []
432
+ for side_name, vals in edges:
433
+ max_run = 0
434
+ cur = 0
435
+ for a in vals:
436
+ if a >= alpha_threshold:
437
+ cur += 1
438
+ if cur > max_run:
439
+ max_run = cur
440
+ else:
441
+ cur = 0
442
+ if max_run >= 16 and (max_run / float(max(1, len(vals)))) >= 0.12:
443
+ bleed.append(side_name)
444
+ return bleed
445
+
446
+
447
+ def contact_sheet(paths, out_path) -> None:
448
+ """Show every asset on light and dark mats with a filename label."""
449
+ tile_w, tile_h, label_h = 240, 176, 34
450
+ columns = min(2, max(1, len(paths)))
451
+ rows = max(1, (len(paths) + columns - 1) // columns)
452
+ canvas = Image.new("RGB", (columns * 2 * tile_w, rows * (tile_h + label_h)), "white")
453
+ draw = ImageDraw.Draw(canvas)
454
+ for index, path in enumerate(paths):
455
+ row, col = divmod(index, columns)
456
+ x, y = col * 2 * tile_w, row * (tile_h + label_h)
457
+ draw.text((x + tile_w, y + label_h / 2), Path(path).stem, fill="#242830", anchor="mm")
458
+ with Image.open(path) as image:
459
+ asset = ImageOps.contain(image.convert("RGBA"), (tile_w - 24, tile_h - 24), Image.Resampling.LANCZOS)
460
+ for mat_index, color in enumerate(("#EEF2F8", "#3C4048")):
461
+ mat = Image.new("RGB", (tile_w, tile_h), color)
462
+ mat.paste(asset, ((tile_w - asset.width) // 2, (tile_h - asset.height) // 2), asset)
463
+ canvas.paste(mat, (x + mat_index * tile_w, y + label_h))
464
+ if not paths:
465
+ draw.text((tile_w, label_h / 2), "No assets extracted", fill="#242830", anchor="mm")
466
+ draw.rectangle((0, label_h, tile_w - 1, canvas.height - 1), fill="#EEF2F8")
467
+ draw.rectangle((tile_w, label_h, canvas.width - 1, canvas.height - 1), fill="#3C4048")
468
+ out_path = Path(out_path)
469
+ out_path.parent.mkdir(parents=True, exist_ok=True)
470
+ canvas.save(out_path)
471
+
472
+
473
+ def _configure_utf8_stdio() -> None:
474
+ import sys
475
+
476
+ for stream in (sys.stdout, sys.stderr):
477
+ if stream is not None:
478
+ try:
479
+ if not stream.isatty() and hasattr(stream, "reconfigure"):
480
+ stream.reconfigure(encoding="utf-8", errors="replace")
481
+ except Exception:
482
+ pass
483
+
484
+
485
+ def main() -> None:
486
+ _configure_utf8_stdio()
487
+ parser = argparse.ArgumentParser(description=__doc__)
488
+ commands = parser.add_subparsers(dest="command", required=True)
489
+ prompt = commands.add_parser("prompt")
490
+ prompt.add_argument("--items", required=True, type=Path)
491
+ prompt.add_argument("--ratio", "--aspect-ratio", dest="ratio", default=None, type=str)
492
+ slicer = commands.add_parser("slice")
493
+ slicer.add_argument("--items", required=True, type=Path)
494
+ slicer.add_argument("--sheet", required=True, type=Path)
495
+ slicer.add_argument("--out-dir", required=True, type=Path)
496
+ slicer.add_argument("--ratio", "--aspect-ratio", dest="ratio", default=None, type=str)
497
+ slicer.add_argument("--format", dest="fmt", default="png", choices=["png", "webp"])
498
+ slicer.add_argument("--quality", default=88, type=int)
499
+ args = parser.parse_args()
500
+ try:
501
+ items = json.loads(args.items.read_text(encoding="utf-8"))
502
+ if not isinstance(items, list) or not all(isinstance(item, dict) for item in items):
503
+ raise ValueError("items must be a JSON list of objects.")
504
+ eff_ratio = args.ratio
505
+ if args.command == "slice" and not eff_ratio and args.sheet.is_file():
506
+ with Image.open(args.sheet) as im:
507
+ if im.height > im.width:
508
+ eff_ratio = "3:4"
509
+ cols, rows, size = grid_for(len(items), ratio=eff_ratio)
510
+ if args.command == "prompt":
511
+ result = {"prompt": build_prompt(items, cols, rows), "size": size}
512
+ else:
513
+ result = slice_sheet(
514
+ args.sheet,
515
+ [item.get("name") for item in items],
516
+ cols,
517
+ rows,
518
+ args.out_dir,
519
+ fmt=args.fmt,
520
+ quality=args.quality,
521
+ )
522
+ except (OSError, ValueError) as exc:
523
+ parser.exit(2, f"asset_sheet: {exc}\n")
524
+ print(json.dumps(result, ensure_ascii=False, indent=2))
525
+
526
+
527
+ if __name__ == "__main__":
528
+ main()