@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,776 @@
1
+ #!/usr/bin/env python3
2
+ """Rasterize brand SVG/PNG to tightly cropped RGBA PNG and generate a 1280x720 brand reference card."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import base64
7
+ import html
8
+ import json
9
+ import os
10
+ import re
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ from pathlib import Path
16
+
17
+ from PIL import Image, ImageDraw, ImageFont
18
+
19
+ CARD_W = 1280
20
+ CARD_H = 720
21
+
22
+
23
+ def _load_runtime_utils():
24
+ cand_res = (Path(__file__).resolve().parent / "_runtime_utils.py").resolve()
25
+ for mod_name in ("_oil_slide_runtime_utils", "_runtime_utils"):
26
+ mod = sys.modules.get(mod_name)
27
+ mod_file = getattr(mod, "__file__", None) if mod is not None else None
28
+ if mod_file:
29
+ try:
30
+ if Path(mod_file).resolve() == cand_res:
31
+ return mod
32
+ except OSError:
33
+ pass
34
+ if not os.path.isfile(cand_res):
35
+ return None
36
+ try:
37
+ import importlib.util
38
+
39
+ spec = importlib.util.spec_from_file_location("_oil_slide_runtime_utils", cand_res)
40
+ if spec is None or spec.loader is None:
41
+ return None
42
+ mod = importlib.util.module_from_spec(spec)
43
+ sys.modules["_oil_slide_runtime_utils"] = mod
44
+ spec.loader.exec_module(mod)
45
+ return mod
46
+ except Exception:
47
+ return None
48
+
49
+
50
+ def _configure_utf8_stdio() -> None:
51
+ ru = _load_runtime_utils()
52
+ if ru is not None:
53
+ ru.configure_utf8_stdio()
54
+ return
55
+ for stream in (sys.stdout, sys.stderr):
56
+ if stream is not None:
57
+ try:
58
+ if not stream.isatty() and hasattr(stream, "reconfigure"):
59
+ stream.reconfigure(encoding="utf-8", errors="replace")
60
+ except Exception:
61
+ pass
62
+
63
+
64
+ def _launch_chromium(
65
+ playwright_obj,
66
+ *,
67
+ headless: bool = True,
68
+ args: list[str] | None = None,
69
+ executable_path: str | None = None,
70
+ discover_system: bool = False,
71
+ ):
72
+ ru = _load_runtime_utils()
73
+ if ru is not None:
74
+ return ru.launch_chromium(
75
+ playwright_obj,
76
+ headless=headless,
77
+ args=args,
78
+ executable_path=executable_path,
79
+ discover_system=discover_system,
80
+ )
81
+ launch_kw: dict = {"headless": headless}
82
+ if args is not None:
83
+ launch_kw["args"] = list(args)
84
+ if executable_path:
85
+ launch_kw["executable_path"] = executable_path
86
+ return playwright_obj.chromium.launch(**launch_kw)
87
+
88
+
89
+ def _is_exec_file(cand_p: Path) -> bool:
90
+ try:
91
+ return cand_p.is_file() and (os.name == "nt" or sys.platform == "win32" or os.access(cand_p, os.X_OK))
92
+ except OSError:
93
+ return False
94
+
95
+
96
+ def find_browser(explicit: str | None = None) -> str | None:
97
+ """Locate Chrome/Chromium/Edge across macOS, Linux, and Windows without hardcoded user paths."""
98
+ if explicit and explicit.strip():
99
+ cand_p = Path(explicit.strip())
100
+ if _is_exec_file(cand_p):
101
+ return str(cand_p)
102
+ for env_key in ("BROWSER_BIN", "CHROME_BIN", "CHROMIUM_BIN"):
103
+ env_val = (os.environ.get(env_key) or "").strip()
104
+ if env_val:
105
+ cand_p = Path(env_val)
106
+ if _is_exec_file(cand_p):
107
+ return str(cand_p)
108
+ ru = _load_runtime_utils()
109
+ if ru is not None:
110
+ return ru.find_browser(explicit)
111
+ for name in ("google-chrome", "chromium", "chromium-browser", "chrome", "msedge"):
112
+ found = shutil.which(name)
113
+ if found and _is_exec_file(Path(found)):
114
+ return found
115
+ return None
116
+
117
+
118
+ def _recolor_svg(svg_text: str, color_hex: str | None) -> str:
119
+ if not color_hex:
120
+ return svg_text
121
+ if "currentColor" in svg_text:
122
+ return svg_text.replace("currentColor", color_hex)
123
+ # Only inject root fill if root <svg> has no explicit fill attribute
124
+ return re.sub(
125
+ r"<svg\b(?![^>]*\bfill=)",
126
+ f'<svg fill="{color_hex}"',
127
+ svg_text,
128
+ count=1,
129
+ )
130
+
131
+
132
+ def _set_svg_square_size(svg_text: str, size_px: int) -> str:
133
+ if re.search(r'<svg\b[^>]*\bwidth="[^"]+"', svg_text):
134
+ svg_text = re.sub(r'(<svg\b[^>]*\bwidth=")[^"]+(")', rf"\g<1>{size_px}\2", svg_text, count=1)
135
+ else:
136
+ svg_text = re.sub(r"<svg\b", f'<svg width="{size_px}"', svg_text, count=1)
137
+ if re.search(r'<svg\b[^>]*\bheight="[^"]+"', svg_text):
138
+ svg_text = re.sub(r'(<svg\b[^>]*\bheight=")[^"]+(")', rf"\g<1>{size_px}\2", svg_text, count=1)
139
+ else:
140
+ svg_text = re.sub(r"<svg\b", f'<svg height="{size_px}"', svg_text, count=1)
141
+ return svg_text
142
+
143
+
144
+ def rasterize_logo(
145
+ logo_path: Path,
146
+ out_path: Path,
147
+ *,
148
+ color_hex: str | None = None,
149
+ size_px: int = 384,
150
+ browser_path: str | None = None,
151
+ ) -> dict:
152
+ """Convert SVG or PNG logo to a tightly cropped transparent RGBA PNG."""
153
+ suffix = logo_path.suffix.lower()
154
+ out_path.parent.mkdir(parents=True, exist_ok=True)
155
+
156
+ if suffix == ".svg":
157
+ browser = find_browser(browser_path)
158
+ svg_text = _recolor_svg(logo_path.read_text(encoding="utf-8"), color_hex)
159
+ svg_text = _set_svg_square_size(svg_text, size_px)
160
+ svg_b64 = base64.b64encode(svg_text.encode("utf-8")).decode("ascii")
161
+
162
+ doc = f"""<!doctype html>
163
+ <html><head><meta charset="utf-8"></head>
164
+ <body style="margin:0;background:transparent">
165
+ <canvas id="c" width="{size_px}" height="{size_px}"></canvas>
166
+ <pre id="out"></pre>
167
+ <script>
168
+ const img = new Image();
169
+ img.onload = () => {{
170
+ const c = document.getElementById("c");
171
+ const ctx = c.getContext("2d");
172
+ ctx.clearRect(0, 0, {size_px}, {size_px});
173
+ const scale = Math.min({size_px} / (img.naturalWidth || {size_px}), {size_px} / (img.naturalHeight || {size_px}));
174
+ const dw = (img.naturalWidth || {size_px}) * scale;
175
+ const dh = (img.naturalHeight || {size_px}) * scale;
176
+ ctx.drawImage(img, ({size_px} - dw) / 2, ({size_px} - dh) / 2, dw, dh);
177
+ document.getElementById("out").textContent = c.toDataURL("image/png");
178
+ }};
179
+ img.src = "data:image/svg+xml;base64,{svg_b64}";
180
+ </script>
181
+ </body></html>"""
182
+
183
+ with tempfile.TemporaryDirectory(prefix="brand-svg-") as tmpdir:
184
+ tmp_root = Path(tmpdir)
185
+ html_file = tmp_root / "rasterize.html"
186
+ profile_dir = tmp_root / "chrome-profile"
187
+ profile_dir.mkdir(parents=True, exist_ok=True)
188
+ html_file.write_text(doc, encoding="utf-8")
189
+
190
+ png_bytes: bytes | None = None
191
+ errors: list[str] = []
192
+
193
+ # Primary: headless Chrome with isolated user-data-dir (prevents macOS exit code 2 when Chrome is open)
194
+ if browser:
195
+ try:
196
+ proc = subprocess.run(
197
+ [
198
+ browser,
199
+ "--headless=new",
200
+ "--no-sandbox",
201
+ "--disable-gpu",
202
+ "--disable-crash-reporter",
203
+ f"--user-data-dir={profile_dir}",
204
+ "--virtual-time-budget=2500",
205
+ "--dump-dom",
206
+ html_file.as_uri(),
207
+ ],
208
+ capture_output=True,
209
+ text=True,
210
+ check=False,
211
+ timeout=25,
212
+ )
213
+ match = re.search(r"data:image/png;base64,([A-Za-z0-9+/=]+)", proc.stdout or "")
214
+ if proc.returncode == 0 and match:
215
+ png_bytes = base64.b64decode(match.group(1))
216
+ else:
217
+ errors.append(f"chrome rc={proc.returncode}: {(proc.stderr or '').strip()[:200]}")
218
+ except (OSError, subprocess.SubprocessError) as exc:
219
+ errors.append(f"chrome launch failed: {exc}")
220
+ else:
221
+ errors.append("no Chrome/Chromium binary found")
222
+
223
+ # Fallback 1: Playwright Chromium (reliable in sandboxed / active-Chrome macOS & Linux environments)
224
+ if png_bytes is None:
225
+ try:
226
+ from playwright.sync_api import sync_playwright
227
+
228
+ with sync_playwright() as p:
229
+ br = _launch_chromium(
230
+ p,
231
+ headless=True,
232
+ args=["--no-sandbox", "--disable-gpu"],
233
+ executable_path=browser,
234
+ discover_system=False,
235
+ )
236
+ pg = br.new_page(viewport={"width": size_px, "height": size_px})
237
+ pg.goto(html_file.as_uri(), wait_until="load", timeout=15000)
238
+ pg.wait_for_function("() => document.getElementById('out').textContent.startsWith('data:image/png')", timeout=8000)
239
+ data_uri = pg.evaluate("() => document.getElementById('out').textContent")
240
+ br.close()
241
+ m2 = re.search(r"data:image/png;base64,([A-Za-z0-9+/=]+)", data_uri or "")
242
+ if m2:
243
+ png_bytes = base64.b64decode(m2.group(1))
244
+ except Exception as exc:
245
+ errors.append(f"playwright fallback failed: {exc}")
246
+
247
+ # Fallback 2: rsvg-convert (if available on macOS/Linux)
248
+ if png_bytes is None:
249
+ if shutil.which("rsvg-convert"):
250
+ svg_file = tmp_root / "logo.svg"
251
+ svg_file.write_text(svg_text, encoding="utf-8")
252
+ rsvg_out = tmp_root / "logo.png"
253
+ try:
254
+ r2 = subprocess.run(
255
+ ["rsvg-convert", "-w", str(size_px), "-h", str(size_px), "-o", str(rsvg_out), str(svg_file)],
256
+ capture_output=True,
257
+ text=True,
258
+ check=False,
259
+ timeout=20,
260
+ )
261
+ if r2.returncode == 0 and rsvg_out.is_file():
262
+ png_bytes = rsvg_out.read_bytes()
263
+ else:
264
+ errors.append(f"rsvg-convert rc={r2.returncode}: {(r2.stderr or '').strip()[:120]}")
265
+ except (OSError, subprocess.SubprocessError) as exc:
266
+ errors.append(f"rsvg-convert failed: {exc}")
267
+ else:
268
+ errors.append("rsvg-convert not installed")
269
+
270
+ if png_bytes is None:
271
+ raise RuntimeError(f"Failed to rasterize SVG {logo_path}: {'; '.join(errors) or 'no rasterizer succeeded'}")
272
+
273
+ out_path.write_bytes(png_bytes)
274
+ with Image.open(out_path) as im:
275
+ rgba = im.convert("RGBA")
276
+ bg_stripped = False
277
+ else:
278
+ with Image.open(logo_path) as im:
279
+ rgba = im.convert("RGBA")
280
+ rgba, bg_stripped = _strip_solid_box_bg(rgba)
281
+
282
+ bbox = rgba.getbbox()
283
+ cropped = rgba.crop(bbox) if bbox else rgba
284
+ w, h = cropped.size
285
+ if max(w, h) != size_px:
286
+ scale = size_px / max(w, h)
287
+ cropped = cropped.resize((max(1, round(w * scale)), max(1, round(h * scale))), Image.Resampling.LANCZOS)
288
+ cropped.save(out_path, format="PNG", optimize=True)
289
+ final_size = list(cropped.size)
290
+ alpha_extrema = list(cropped.getchannel("A").getextrema())
291
+
292
+ tone = _analyze_logo_tone(cropped)
293
+ light_bg_path = str(out_path)
294
+ dark_bg_path = str(out_path)
295
+ if tone in ("light_mono", "dark_mono") or bg_stripped:
296
+ dark_variant = out_path.parent / "logo-dark.png"
297
+ light_variant = out_path.parent / "logo-light.png"
298
+ if tone == "light_mono":
299
+ _recolor_mono_logo(cropped, (20, 22, 26)).save(dark_variant, format="PNG", optimize=True)
300
+ cropped.save(light_variant, format="PNG", optimize=True)
301
+ light_bg_path = str(dark_variant)
302
+ dark_bg_path = str(light_variant)
303
+ elif tone == "dark_mono":
304
+ cropped.save(dark_variant, format="PNG", optimize=True)
305
+ _recolor_mono_logo(cropped, (255, 255, 255)).save(light_variant, format="PNG", optimize=True)
306
+ light_bg_path = str(dark_variant)
307
+ dark_bg_path = str(light_variant)
308
+
309
+ return {
310
+ "path": str(out_path),
311
+ "size": final_size,
312
+ "mode": "RGBA",
313
+ "alpha_extrema": alpha_extrema,
314
+ "bg_stripped": bg_stripped,
315
+ "logo_tone": tone,
316
+ "recommended_for_light_bg": light_bg_path,
317
+ "recommended_for_dark_bg": dark_bg_path,
318
+ }
319
+
320
+
321
+ def _strip_solid_box_bg(rgba: Image.Image) -> tuple[Image.Image, bool]:
322
+ """Detect and flood-fill remove a solid opaque neutral dark or white outer rectangular box
323
+ (e.g. scraped white-on-black or black-on-white raster logos) so logos never render as black stickers."""
324
+ from collections import deque
325
+
326
+ w, h = rgba.size
327
+ if w < 16 or h < 16:
328
+ return rgba, False
329
+ px = rgba.load()
330
+
331
+ border_pixels: list[tuple[int, int, int, int]] = []
332
+ step_x = max(1, w // 40)
333
+ step_y = max(1, h // 40)
334
+ for x in range(0, w, step_x):
335
+ border_pixels.append(px[x, 0])
336
+ border_pixels.append(px[x, h - 1])
337
+ for y in range(0, h, step_y):
338
+ border_pixels.append(px[0, y])
339
+ border_pixels.append(px[w - 1, y])
340
+
341
+ opaque_border = [p for p in border_pixels if p[3] >= 235]
342
+ if len(opaque_border) < len(border_pixels) * 0.85:
343
+ return rgba, False
344
+
345
+ rs = sorted(p[0] for p in opaque_border)
346
+ gs = sorted(p[1] for p in opaque_border)
347
+ bs = sorted(p[2] for p in opaque_border)
348
+ mid = len(opaque_border) // 2
349
+ bg_r, bg_g, bg_b = rs[mid], gs[mid], bs[mid]
350
+
351
+ bg_lum = 0.2126 * bg_r + 0.7152 * bg_g + 0.0722 * bg_b
352
+ bg_chroma = max(bg_r, bg_g, bg_b) - min(bg_r, bg_g, bg_b)
353
+ if bg_chroma > 22 or not (bg_lum <= 38 or bg_lum >= 225):
354
+ return rgba, False
355
+
356
+ uniform_count = sum(
357
+ 1 for r, g, b, _ in opaque_border
358
+ if abs(r - bg_r) <= 22 and abs(g - bg_g) <= 22 and abs(b - bg_b) <= 22
359
+ )
360
+ if uniform_count < len(opaque_border) * 0.85:
361
+ return rgba, False
362
+
363
+ fg_hits = 0
364
+ for y in range(h // 6, (5 * h) // 6, max(1, h // 24)):
365
+ for x in range(w // 6, (5 * w) // 6, max(1, w // 24)):
366
+ r, g, b, a = px[x, y]
367
+ if a >= 40 and (abs(r - bg_r) > 36 or abs(g - bg_g) > 36 or abs(b - bg_b) > 36):
368
+ fg_hits += 1
369
+ if fg_hits < 4:
370
+ return rgba, False
371
+
372
+ out = rgba.copy()
373
+ opx = out.load()
374
+ visited = [[False] * w for _ in range(h)]
375
+ bg_mask = [[False] * w for _ in range(h)]
376
+ q: deque[tuple[int, int]] = deque()
377
+ for x in range(w):
378
+ q.append((x, 0))
379
+ q.append((x, h - 1))
380
+ for y in range(h):
381
+ q.append((0, y))
382
+ q.append((w - 1, y))
383
+
384
+ while q:
385
+ x, y = q.popleft()
386
+ if visited[y][x]:
387
+ continue
388
+ visited[y][x] = True
389
+ r, g, b, a = opx[x, y]
390
+ if a < 20 or (abs(r - bg_r) <= 28 and abs(g - bg_g) <= 28 and abs(b - bg_b) <= 28):
391
+ bg_mask[y][x] = True
392
+ opx[x, y] = (0, 0, 0, 0)
393
+ for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
394
+ if 0 <= nx < w and 0 <= ny < h and not visited[ny][nx]:
395
+ q.append((nx, ny))
396
+
397
+ # If this is a high-contrast monochrome logo on a solid neutral box (e.g. white text on black,
398
+ # or black text on white), derive clean luminance alpha across the entire image so BOTH
399
+ # enclosed letter counters (A, O, P, R, B) AND anti-alias dark/light fringes vanish cleanly.
400
+ rem_lums = []
401
+ for y in range(0, h, max(1, h // 32)):
402
+ for x in range(0, w, max(1, w // 32)):
403
+ if not bg_mask[y][x]:
404
+ r, g, b, a = opx[x, y]
405
+ if a >= 80 and max(abs(r - bg_r), abs(g - bg_g), abs(b - bg_b)) > 56:
406
+ rem_lums.append(0.2126 * r + 0.7152 * g + 0.0722 * b)
407
+ if rem_lums:
408
+ fg_avg_lum = sum(rem_lums) / len(rem_lums)
409
+ high_contrast_mono = (bg_lum <= 38 and fg_avg_lum >= 175) or (bg_lum >= 225 and fg_avg_lum <= 95)
410
+ if high_contrast_mono:
411
+ is_white_on_black = bg_lum <= 38
412
+ fg_rgb = (255, 255, 255) if is_white_on_black else (20, 22, 26)
413
+ span = max(80.0, abs(fg_avg_lum - bg_lum))
414
+ src_px = rgba.load()
415
+ for y in range(h):
416
+ for x in range(w):
417
+ r, g, b, a = src_px[x, y]
418
+ if a < 10:
419
+ opx[x, y] = (0, 0, 0, 0)
420
+ continue
421
+ lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
422
+ t = ((lum - bg_lum) / span) if is_white_on_black else ((bg_lum - lum) / span)
423
+ if t <= 0.08:
424
+ opx[x, y] = (0, 0, 0, 0)
425
+ else:
426
+ alpha_out = int(round(min(1.0, max(0.0, (t - 0.08) / 0.84)) * a))
427
+ opx[x, y] = (fg_rgb[0], fg_rgb[1], fg_rgb[2], alpha_out)
428
+ return out, True
429
+
430
+ for y in range(1, h - 1):
431
+ for x in range(1, w - 1):
432
+ if not bg_mask[y][x]:
433
+ r, g, b, a = opx[x, y]
434
+ if a > 0 and (bg_mask[y - 1][x] or bg_mask[y + 1][x] or bg_mask[y][x - 1] or bg_mask[y][x + 1]):
435
+ dist = max(abs(r - bg_r), abs(g - bg_g), abs(b - bg_b))
436
+ if dist < 56:
437
+ opx[x, y] = (r, g, b, int(max(0, min(a, a * (dist / 56.0)))))
438
+
439
+ return out, True
440
+
441
+
442
+ def _analyze_logo_tone(rgba: Image.Image) -> str:
443
+ w, h = rgba.size
444
+ px = rgba.load()
445
+ lums: list[float] = []
446
+ chromas: list[int] = []
447
+ step_x = max(1, w // 48)
448
+ step_y = max(1, h // 48)
449
+ for y in range(0, h, step_y):
450
+ for x in range(0, w, step_x):
451
+ r, g, b, a = px[x, y]
452
+ if a >= 80:
453
+ lums.append(0.2126 * r + 0.7152 * g + 0.0722 * b)
454
+ chromas.append(max(r, g, b) - min(r, g, b))
455
+ if not lums:
456
+ return "color"
457
+ n = len(lums)
458
+ avg_chroma = sum(chromas) / n
459
+ avg_lum = sum(lums) / n
460
+ # Protect multi-tone icons and app badges (e.g., white rounded tile with dark line-art + small red dot)
461
+ # from being falsely flattened into a solid monochrome silhouette.
462
+ accent_ratio = sum(1 for c in chromas if c >= 55) / n
463
+ dark_ratio = sum(1 for l in lums if l <= 105) / n
464
+ light_ratio = sum(1 for l in lums if l >= 185) / n
465
+ if avg_chroma > 35 or accent_ratio >= 0.015 or (dark_ratio >= 0.05 and light_ratio >= 0.05):
466
+ return "color"
467
+ if avg_lum >= 185:
468
+ return "light_mono"
469
+ if avg_lum <= 85:
470
+ return "dark_mono"
471
+ return "color"
472
+
473
+
474
+ def _recolor_mono_logo(rgba: Image.Image, rgb: tuple[int, int, int]) -> Image.Image:
475
+ out = Image.new("RGBA", rgba.size, (rgb[0], rgb[1], rgb[2], 0))
476
+ out.putalpha(rgba.getchannel("A"))
477
+ return out
478
+
479
+
480
+ def _split_top_level_commas(raw: str) -> list[str]:
481
+ """Split on ASCII/CJK commas outside parentheses so labels like '蓝(目测,待核)' stay intact."""
482
+ chunks: list[str] = []
483
+ buf: list[str] = []
484
+ depth = 0
485
+ for ch in raw or "":
486
+ if ch in "((":
487
+ depth += 1
488
+ buf.append(ch)
489
+ elif ch in "))":
490
+ depth = max(0, depth - 1)
491
+ buf.append(ch)
492
+ elif ch in ",," and depth == 0:
493
+ chunks.append("".join(buf))
494
+ buf = []
495
+ else:
496
+ buf.append(ch)
497
+ if buf:
498
+ chunks.append("".join(buf))
499
+ return chunks
500
+
501
+
502
+ def parse_colors_arg(raw: str) -> list[tuple[str, str]]:
503
+ items: list[tuple[str, str]] = []
504
+ for chunk in _split_top_level_commas(raw or ""):
505
+ part = chunk.strip()
506
+ if not part:
507
+ continue
508
+ m = re.search(r"#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})\b", part)
509
+ if not m and ":" in part:
510
+ hp = part.split(":", 1)[0].strip()
511
+ m = re.match(r"^([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$", hp)
512
+ if not m:
513
+ raise ValueError(f"Invalid hex color in --colors: {part!r}")
514
+ raw_hex = m.group(1)
515
+ if len(raw_hex) == 3:
516
+ raw_hex = "".join(ch * 2 for ch in raw_hex)
517
+ hex_val = f"#{raw_hex.upper()}"
518
+ remainder = (part[: m.start()] + part[m.end() :]).strip(" :|-\t")
519
+ if (remainder.startswith("(") and remainder.endswith(")")) or (
520
+ remainder.startswith("(") and remainder.endswith(")")
521
+ ):
522
+ inner = remainder[1:-1].strip()
523
+ if inner and "(" not in inner and ")" not in inner and "(" not in inner and ")" not in inner:
524
+ remainder = inner
525
+ label = remainder if remainder else hex_val
526
+ items.append((hex_val, label))
527
+ if not items:
528
+ raise ValueError("--colors must provide at least one '#HEX:Label' entry.")
529
+ return items
530
+
531
+
532
+ def _hex_rgb(hex_str: str) -> tuple[int, int, int]:
533
+ v = hex_str.lstrip("#")
534
+ return int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16)
535
+
536
+
537
+ def _is_light(hex_str: str) -> bool:
538
+ r, g, b = _hex_rgb(hex_str)
539
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) > 165
540
+
541
+
542
+ def render_brand_card(
543
+ *,
544
+ logo_png: Path,
545
+ name: str,
546
+ colors: list[tuple[str, str]],
547
+ out_card: Path,
548
+ bg_hex: str = "#FFFFFF",
549
+ ink_hex: str = "#060D1C",
550
+ accent_hex: str | None = None,
551
+ wordmark_font: str = "Inter, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif",
552
+ browser_path: str | None = None,
553
+ ) -> dict:
554
+ """Render a 1280x720 official brand reference card suitable for --ref Slide 1 generation."""
555
+ out_card.parent.mkdir(parents=True, exist_ok=True)
556
+ wordmark_color = accent_hex or colors[0][0]
557
+ browser = find_browser(browser_path)
558
+
559
+ if browser:
560
+ logo_b64 = base64.b64encode(logo_png.read_bytes()).decode("ascii")
561
+ light_bg = _is_light(bg_hex)
562
+ muted_ink = "#5E6B80" if light_bg else "#9FB0CE"
563
+ divider_css = "rgba(6,13,28,0.12)" if light_bg else "rgba(255,255,255,0.16)"
564
+ swatch_border = "rgba(6,13,28,0.12)" if light_bg else "rgba(255,255,255,0.22)"
565
+
566
+ swatches_html = []
567
+ for hex_val, label in colors[:6]:
568
+ swatches_html.append(
569
+ f"""<div class="swatch-item">
570
+ <div class="swatch-box" style="background:{html.escape(hex_val)};border:1px solid {swatch_border};"></div>
571
+ <div class="swatch-meta">
572
+ <div class="swatch-label">{html.escape(label)}</div>
573
+ <div class="swatch-hex">{html.escape(hex_val)}</div>
574
+ </div>
575
+ </div>"""
576
+ )
577
+
578
+ card_html = f"""<!doctype html>
579
+ <html><head><meta charset="utf-8">
580
+ <style>
581
+ * {{ box-sizing: border-box; margin: 0; padding: 0; }}
582
+ html, body {{
583
+ width: {CARD_W}px; height: {CARD_H}px; overflow: hidden;
584
+ background: {html.escape(bg_hex)}; color: {html.escape(ink_hex)};
585
+ font-family: {wordmark_font};
586
+ -webkit-font-smoothing: antialiased;
587
+ }}
588
+ .canvas {{
589
+ width: {CARD_W}px; height: {CARD_H}px; padding: 64px 88px 64px 88px;
590
+ display: flex; flex-direction: column; justify-content: space-between;
591
+ }}
592
+ .eyebrow {{
593
+ font-size: 20px; font-weight: 600; letter-spacing: 0.14em;
594
+ color: {muted_ink}; text-transform: uppercase;
595
+ }}
596
+ .lockup {{
597
+ display: flex; align-items: center; gap: 36px; margin-top: 12px;
598
+ }}
599
+ .lockup img {{
600
+ height: 152px; width: auto; display: block;
601
+ }}
602
+ .wordmark {{
603
+ font-size: 112px; font-weight: 700; letter-spacing: -0.025em;
604
+ line-height: 1; color: {html.escape(wordmark_color)};
605
+ }}
606
+ .palette {{
607
+ border-top: 1px solid {divider_css}; padding-top: 34px;
608
+ display: flex; flex-wrap: wrap; gap: 36px 44px; align-items: center;
609
+ }}
610
+ .swatch-item {{ display: flex; align-items: center; gap: 14px; }}
611
+ .swatch-box {{ width: 46px; height: 46px; border-radius: 10px; flex: none; }}
612
+ .swatch-label {{ font-size: 19px; font-weight: 600; color: {html.escape(ink_hex)}; }}
613
+ .swatch-hex {{ font-size: 16px; font-weight: 500; color: {muted_ink}; margin-top: 3px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }}
614
+ </style></head>
615
+ <body>
616
+ <div class="canvas">
617
+ <div class="eyebrow">BRAND IDENTITY &amp; OFFICIAL LOGO REFERENCE — {html.escape(name.upper())}</div>
618
+ <div class="lockup">
619
+ <img src="data:image/png;base64,{logo_b64}" alt="logo" />
620
+ <div class="wordmark">{html.escape(name)}</div>
621
+ </div>
622
+ <div class="palette">
623
+ {"".join(swatches_html)}
624
+ </div>
625
+ </div>
626
+ </body></html>"""
627
+
628
+ with tempfile.TemporaryDirectory(prefix="brand-card-") as tmpdir:
629
+ html_file = Path(tmpdir) / "card.html"
630
+ profile_dir = Path(tmpdir) / "chrome-profile"
631
+ html_file.write_text(card_html, encoding="utf-8")
632
+ rendered = False
633
+ try:
634
+ proc = subprocess.run(
635
+ [
636
+ browser,
637
+ "--headless=new",
638
+ "--no-sandbox",
639
+ "--disable-gpu",
640
+ "--disable-crash-reporter",
641
+ f"--user-data-dir={profile_dir}",
642
+ "--hide-scrollbars",
643
+ "--force-device-scale-factor=1",
644
+ f"--window-size={CARD_W},{CARD_H}",
645
+ f"--screenshot={out_card}",
646
+ html_file.as_uri(),
647
+ ],
648
+ capture_output=True,
649
+ text=True,
650
+ check=False,
651
+ timeout=25,
652
+ )
653
+ if proc.returncode == 0 and out_card.is_file() and out_card.stat().st_size > 0:
654
+ rendered = True
655
+ except (OSError, subprocess.SubprocessError):
656
+ rendered = False
657
+ if not rendered:
658
+ from playwright.sync_api import sync_playwright
659
+
660
+ with sync_playwright() as p:
661
+ br = _launch_chromium(
662
+ p,
663
+ headless=True,
664
+ args=["--no-sandbox", "--disable-gpu"],
665
+ executable_path=browser,
666
+ discover_system=False,
667
+ )
668
+ pg = br.new_page(viewport={"width": CARD_W, "height": CARD_H}, device_scale_factor=1)
669
+ pg.goto(html_file.as_uri(), wait_until="load", timeout=15000)
670
+ pg.screenshot(path=str(out_card), full_page=False)
671
+ br.close()
672
+ else:
673
+ # Pure-Pillow fallback when Chrome/Chromium is not available
674
+ img = Image.new("RGB", (CARD_W, CARD_H), _hex_rgb(bg_hex))
675
+ draw = ImageDraw.Draw(img)
676
+ font_lg = ImageFont.load_default()
677
+ draw.text((88, 64), f"BRAND IDENTITY REFERENCE - {name.upper()}", fill=_hex_rgb(ink_hex), font=font_lg)
678
+ with Image.open(logo_png) as lg:
679
+ lg_rgba = lg.convert("RGBA")
680
+ scale = 152 / max(1, lg_rgba.height)
681
+ lg_resized = lg_rgba.resize((max(1, round(lg_rgba.width * scale)), 152), Image.Resampling.LANCZOS)
682
+ img.paste(lg_resized, (88, 260), lg_resized)
683
+ draw.text((88 + lg_resized.width + 36, 320), name, fill=_hex_rgb(wordmark_color), font=font_lg)
684
+ draw.line([(88, 560), (CARD_W - 88, 560)], fill=(210, 218, 228), width=1)
685
+ x_cur = 88
686
+ for hex_val, label in colors[:6]:
687
+ draw.rounded_rectangle([x_cur, 596, x_cur + 46, 642], radius=8, fill=_hex_rgb(hex_val))
688
+ draw.text((x_cur + 58, 602), f"{label} ({hex_val})", fill=_hex_rgb(ink_hex), font=font_lg)
689
+ x_cur += 210
690
+ img.save(out_card, format="PNG")
691
+
692
+ with Image.open(out_card) as card_im:
693
+ return {"path": str(out_card), "size": list(card_im.size)}
694
+
695
+
696
+ def main() -> None:
697
+ _configure_utf8_stdio()
698
+ parser = argparse.ArgumentParser(
699
+ description="Rasterize SVG/PNG logo to tight RGBA PNG and generate a 1280x720 brand reference card."
700
+ )
701
+ parser.add_argument("--logo", required=True, type=Path, help="Input official brand logo (.svg or .png).")
702
+ parser.add_argument("--name", required=True, type=str, help="Brand wordmark text for the reference card.")
703
+ parser.add_argument(
704
+ "--colors",
705
+ required=True,
706
+ type=str,
707
+ help="Comma-separated '#HEX:Label' palette entries, e.g. '#4D6BFE:Cobalt,#060D1C:Midnight'.",
708
+ )
709
+ parser.add_argument("--out-card", required=True, type=Path, help="Output 1280x720 brand reference PNG.")
710
+ parser.add_argument("--out-logo-png", type=Path, default=None, help="Optional output path for tight RGBA logo PNG.")
711
+ parser.add_argument("--logo-color", type=str, default=None, help="Optional hex color for SVG currentColor.")
712
+ parser.add_argument(
713
+ "--wordmark-color",
714
+ type=str,
715
+ default=None,
716
+ help="Optional hex color for card wordmark (defaults to --ink for PNG logos, or --logo-color/first color for SVG).",
717
+ )
718
+ parser.add_argument("--logo-size", type=int, default=384, help="Rasterization square budget in px (default: 384).")
719
+ parser.add_argument("--bg", type=str, default="#FFFFFF", help="Card background hex color (default: #FFFFFF).")
720
+ parser.add_argument("--ink", type=str, default="#060D1C", help="Card primary text hex color (default: #060D1C).")
721
+ parser.add_argument(
722
+ "--wordmark-font",
723
+ type=str,
724
+ default="Inter, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif",
725
+ help="CSS font-family stack for card wordmark.",
726
+ )
727
+ parser.add_argument("--browser", type=str, default=None, help="Optional Chrome/Chromium binary path.")
728
+ parser.add_argument("--json", action="store_true", help="Emit concise JSON output.")
729
+ args = parser.parse_args()
730
+
731
+ logo_path = args.logo.resolve()
732
+ if not logo_path.is_file():
733
+ raise SystemExit(f"Logo file not found: {logo_path}")
734
+
735
+ colors = parse_colors_arg(args.colors)
736
+ is_svg = logo_path.suffix.lower() == ".svg"
737
+ effective_logo_color = args.logo_color or colors[0][0]
738
+ effective_wordmark_color = args.wordmark_color or (effective_logo_color if is_svg else args.ink)
739
+
740
+ with tempfile.TemporaryDirectory(prefix="brand-ref-work-") as tmpdir:
741
+ logo_png_target = args.out_logo_png.resolve() if args.out_logo_png else (Path(tmpdir) / "logo-tight.png")
742
+ logo_meta = rasterize_logo(
743
+ logo_path=logo_path,
744
+ out_path=logo_png_target,
745
+ color_hex=effective_logo_color if (args.logo_color or is_svg) else None,
746
+ size_px=args.logo_size,
747
+ browser_path=args.browser,
748
+ )
749
+ card_logo_png = Path(
750
+ logo_meta["recommended_for_light_bg"] if _is_light(args.bg) else logo_meta["recommended_for_dark_bg"]
751
+ )
752
+ card_meta = render_brand_card(
753
+ logo_png=card_logo_png if card_logo_png.is_file() else logo_png_target,
754
+ name=args.name,
755
+ colors=colors,
756
+ out_card=args.out_card.resolve(),
757
+ bg_hex=args.bg,
758
+ ink_hex=args.ink,
759
+ accent_hex=effective_wordmark_color,
760
+ wordmark_font=args.wordmark_font,
761
+ browser_path=args.browser,
762
+ )
763
+
764
+ payload = {
765
+ "ok": True,
766
+ "logo": logo_meta if args.out_logo_png else {"size": logo_meta["size"], "mode": logo_meta["mode"]},
767
+ "card": card_meta,
768
+ }
769
+ if args.json:
770
+ print(json.dumps(payload, ensure_ascii=False))
771
+ else:
772
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
773
+
774
+
775
+ if __name__ == "__main__":
776
+ main()