@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.8
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.
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
- package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
- package/bundled-assets/skill/LICENSE +21 -0
- package/bundled-assets/skill/README.md +61 -0
- package/bundled-assets/skill/SKILL.md +185 -0
- package/bundled-assets/skill/references/art-directions.md +99 -0
- package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
- package/bundled-assets/skill/references/design-baseline.txt +1 -0
- package/bundled-assets/skill/references/prompt-compiler.md +99 -0
- package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
- package/bundled-assets/skill/references/staged-pptx.md +71 -0
- package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
- package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
- package/bundled-assets/skill/scripts/brand_ref.py +776 -0
- package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
- package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
- package/bundled-assets/skill/scripts/export_images.py +280 -0
- package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
- package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
- package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
- package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
- package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
- package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
- package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
- package/bundled-assets/skill/scripts/render_gradient.py +258 -0
- package/bundled-assets/skill/scripts/slide_brand.py +111 -0
- package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
- package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
- package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
- package/bundled-assets/skill/vendor/README.md +4 -0
- package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
- package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
- package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +11423 -0
- package/lib/index.js +2638 -0
- package/package.json +140 -4
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Prepare reference images (<2 MiB JPEG) and stitch N-up contact sheets."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import re
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _parse_hex(hex_color: str) -> tuple[int, int, int]:
|
|
15
|
+
val = hex_color.strip().lstrip("#")
|
|
16
|
+
if len(val) == 3:
|
|
17
|
+
val = "".join(c * 2 for c in val)
|
|
18
|
+
if not re.match(r"^[0-9A-Fa-f]{6}$", val):
|
|
19
|
+
raise ValueError(f"Invalid hex color: {hex_color!r}")
|
|
20
|
+
return int(val[0:2], 16), int(val[2:4], 16), int(val[4:6], 16)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _to_rgb_white_bg(im: Image.Image) -> Image.Image:
|
|
24
|
+
if im.mode in ("RGBA", "LA") or (im.mode == "P" and "transparency" in im.info):
|
|
25
|
+
rgba = im.convert("RGBA")
|
|
26
|
+
bg = Image.new("RGB", rgba.size, (255, 255, 255))
|
|
27
|
+
bg.paste(rgba, mask=rgba.getchannel("A"))
|
|
28
|
+
return bg
|
|
29
|
+
return im.convert("RGB")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def prepare_ref(
|
|
33
|
+
src: Path,
|
|
34
|
+
out: Path,
|
|
35
|
+
*,
|
|
36
|
+
max_bytes: int = 1_950_000,
|
|
37
|
+
max_dim: int = 2048,
|
|
38
|
+
) -> dict:
|
|
39
|
+
"""Convert/compress an image to JPEG strictly below max_bytes for --ref inputs."""
|
|
40
|
+
if not src.is_file():
|
|
41
|
+
raise FileNotFoundError(f"Input image not found: {src}")
|
|
42
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
|
|
44
|
+
with Image.open(src) as raw:
|
|
45
|
+
im = _to_rgb_white_bg(raw)
|
|
46
|
+
w, h = im.size
|
|
47
|
+
if max(w, h) > max_dim:
|
|
48
|
+
scale = max_dim / max(w, h)
|
|
49
|
+
im = im.resize((max(1, round(w * scale)), max(1, round(h * scale))), Image.Resampling.LANCZOS)
|
|
50
|
+
|
|
51
|
+
cur = im
|
|
52
|
+
chosen_q = None
|
|
53
|
+
for _attempt in range(6):
|
|
54
|
+
for q in (94, 92, 90, 88, 84, 80, 75, 70):
|
|
55
|
+
cur.save(out, format="JPEG", quality=q, optimize=True, progressive=True)
|
|
56
|
+
if out.stat().st_size <= max_bytes:
|
|
57
|
+
chosen_q = q
|
|
58
|
+
break
|
|
59
|
+
if chosen_q is not None:
|
|
60
|
+
break
|
|
61
|
+
nw = max(320, round(cur.width * 0.85))
|
|
62
|
+
nh = max(180, round(cur.height * 0.85))
|
|
63
|
+
cur = cur.resize((nw, nh), Image.Resampling.LANCZOS)
|
|
64
|
+
|
|
65
|
+
size_bytes = out.stat().st_size
|
|
66
|
+
if size_bytes > max_bytes:
|
|
67
|
+
raise RuntimeError(f"Unable to compress {src} under {max_bytes} bytes (got {size_bytes}).")
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
"ok": True,
|
|
71
|
+
"input": str(src),
|
|
72
|
+
"out": str(out),
|
|
73
|
+
"size": [cur.width, cur.height],
|
|
74
|
+
"quality": chosen_q or 70,
|
|
75
|
+
"bytes": size_bytes,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def stitch_grid(
|
|
80
|
+
inputs: list[Path],
|
|
81
|
+
out: Path,
|
|
82
|
+
*,
|
|
83
|
+
cols: int = 2,
|
|
84
|
+
pad: int = 36,
|
|
85
|
+
bg_hex: str = "#E8EDF6",
|
|
86
|
+
tile_width: int = 960,
|
|
87
|
+
labels: list[str] | None = None,
|
|
88
|
+
) -> dict:
|
|
89
|
+
"""Stitch multiple images into an N-up contact sheet PNG."""
|
|
90
|
+
if not inputs:
|
|
91
|
+
raise ValueError("stitch requires at least one input image.")
|
|
92
|
+
for p in inputs:
|
|
93
|
+
if not p.is_file():
|
|
94
|
+
raise FileNotFoundError(f"Input image not found: {p}")
|
|
95
|
+
|
|
96
|
+
cols = max(1, cols)
|
|
97
|
+
rows = math.ceil(len(inputs) / cols)
|
|
98
|
+
bg_rgb = _parse_hex(bg_hex)
|
|
99
|
+
|
|
100
|
+
resized_tiles: list[Image.Image] = []
|
|
101
|
+
max_tile_h = 1
|
|
102
|
+
for p in inputs:
|
|
103
|
+
with Image.open(p) as raw:
|
|
104
|
+
rgb = _to_rgb_white_bg(raw)
|
|
105
|
+
scale = tile_width / max(1, rgb.width)
|
|
106
|
+
th = max(1, round(rgb.height * scale))
|
|
107
|
+
tile = rgb.resize((tile_width, th), Image.Resampling.LANCZOS)
|
|
108
|
+
resized_tiles.append(tile)
|
|
109
|
+
max_tile_h = max(max_tile_h, th)
|
|
110
|
+
|
|
111
|
+
label_h = 34 if labels else 0
|
|
112
|
+
cell_h = max_tile_h + label_h
|
|
113
|
+
canvas_w = pad + cols * (tile_width + pad)
|
|
114
|
+
canvas_h = pad + rows * (cell_h + pad)
|
|
115
|
+
canvas = Image.new("RGB", (canvas_w, canvas_h), bg_rgb)
|
|
116
|
+
draw = ImageDraw.Draw(canvas) if labels else None
|
|
117
|
+
font = ImageFont.load_default() if labels else None
|
|
118
|
+
ink_rgb = (18, 28, 48) if (0.2126 * bg_rgb[0] + 0.7152 * bg_rgb[1] + 0.0722 * bg_rgb[2]) > 140 else (238, 242, 255)
|
|
119
|
+
|
|
120
|
+
for idx, tile in enumerate(resized_tiles):
|
|
121
|
+
r = idx // cols
|
|
122
|
+
c = idx % cols
|
|
123
|
+
x = pad + c * (tile_width + pad)
|
|
124
|
+
y = pad + r * (cell_h + pad)
|
|
125
|
+
if labels and idx < len(labels) and draw is not None:
|
|
126
|
+
draw.text((x + 4, y + 6), labels[idx], fill=ink_rgb, font=font)
|
|
127
|
+
y_img = y + label_h + (max_tile_h - tile.height) // 2
|
|
128
|
+
canvas.paste(tile, (x, y_img))
|
|
129
|
+
|
|
130
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
canvas.save(out, format="PNG", optimize=True)
|
|
132
|
+
return {
|
|
133
|
+
"ok": True,
|
|
134
|
+
"count": len(resized_tiles),
|
|
135
|
+
"grid": [cols, rows],
|
|
136
|
+
"out": str(out),
|
|
137
|
+
"size": [canvas_w, canvas_h],
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _sample_clean_surface_tile(rgb: Image.Image) -> Image.Image:
|
|
142
|
+
"""Extract a clean, text-free background surface texture tile from outer margins of an anchor slide."""
|
|
143
|
+
w, h = rgb.size
|
|
144
|
+
candidates: list[tuple[float, Image.Image]] = []
|
|
145
|
+
boxes = [
|
|
146
|
+
(int(w * 0.30), int(h * 0.015), int(w * 0.70), int(h * 0.065)), # top center margin
|
|
147
|
+
(int(w * 0.30), int(h * 0.935), int(w * 0.70), int(h * 0.985)), # bottom center margin
|
|
148
|
+
(int(w * 0.015), int(h * 0.30), int(w * 0.065), int(h * 0.70)), # left center margin
|
|
149
|
+
(int(w * 0.935), int(h * 0.30), int(w * 0.985), int(h * 0.70)), # right center margin
|
|
150
|
+
]
|
|
151
|
+
for box in boxes:
|
|
152
|
+
x0, y0, x1, y1 = box
|
|
153
|
+
if x1 - x0 < 16 or y1 - y0 < 16:
|
|
154
|
+
continue
|
|
155
|
+
patch = rgb.crop(box)
|
|
156
|
+
small = patch.resize((32, 32), Image.Resampling.BILINEAR)
|
|
157
|
+
px = list(small.get_flattened_data()) if hasattr(small, "get_flattened_data") else list(small.getdata())
|
|
158
|
+
n = max(1, len(px))
|
|
159
|
+
mr = sum(p[0] for p in px) / n
|
|
160
|
+
mg = sum(p[1] for p in px) / n
|
|
161
|
+
mb = sum(p[2] for p in px) / n
|
|
162
|
+
var = sum((p[0] - mr) ** 2 + (p[1] - mg) ** 2 + (p[2] - mb) ** 2 for p in px) / n
|
|
163
|
+
candidates.append((var, patch))
|
|
164
|
+
if not candidates:
|
|
165
|
+
return rgb.crop((0, 0, min(w, 64), min(h, 64)))
|
|
166
|
+
candidates.sort(key=lambda item: item[0])
|
|
167
|
+
return candidates[0][1]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _reconstruct_surface_canvas(rgb: Image.Image, size: tuple[int, int]) -> Image.Image:
|
|
171
|
+
"""Rebuild a composition-free surface canvas preserving subtle 4-corner light falloff and fine grain.
|
|
172
|
+
|
|
173
|
+
Pure flat slides stay flat; slides with gentle directional lighting or vignette keep their tonal depth
|
|
174
|
+
instead of being flattened to a single uniform margin strip.
|
|
175
|
+
"""
|
|
176
|
+
sw, sh = rgb.size
|
|
177
|
+
out_w, out_h = size
|
|
178
|
+
clean_tile = _sample_clean_surface_tile(rgb)
|
|
179
|
+
# Compute reference median color from the cleanest outer strip
|
|
180
|
+
tile_small = clean_tile.resize((32, 32), Image.Resampling.BILINEAR)
|
|
181
|
+
tpx = list(tile_small.get_flattened_data()) if hasattr(tile_small, "get_flattened_data") else list(tile_small.getdata())
|
|
182
|
+
ref_r = sorted(p[0] for p in tpx)[len(tpx) // 2]
|
|
183
|
+
ref_g = sorted(p[1] for p in tpx)[len(tpx) // 2]
|
|
184
|
+
ref_b = sorted(p[2] for p in tpx)[len(tpx) // 2]
|
|
185
|
+
|
|
186
|
+
# Sample the 4 extreme outer corners (free of body content); fallback to ref if a corner holds dense ink/UI
|
|
187
|
+
corner_boxes = [
|
|
188
|
+
(int(sw * 0.01), int(sh * 0.01), int(sw * 0.07), int(sh * 0.07)), # TL
|
|
189
|
+
(int(sw * 0.93), int(sh * 0.01), int(sw * 0.99), int(sh * 0.07)), # TR
|
|
190
|
+
(int(sw * 0.01), int(sh * 0.93), int(sw * 0.07), int(sh * 0.99)), # BL
|
|
191
|
+
(int(sw * 0.93), int(sh * 0.93), int(sw * 0.99), int(sh * 0.99)), # BR
|
|
192
|
+
]
|
|
193
|
+
corners: list[tuple[int, int, int]] = []
|
|
194
|
+
for box in corner_boxes:
|
|
195
|
+
x0, y0, x1, y1 = box
|
|
196
|
+
if x1 - x0 < 8 or y1 - y0 < 8:
|
|
197
|
+
corners.append((ref_r, ref_g, ref_b))
|
|
198
|
+
continue
|
|
199
|
+
p = rgb.crop(box).resize((16, 16), Image.Resampling.BILINEAR)
|
|
200
|
+
px = list(p.get_flattened_data()) if hasattr(p, "get_flattened_data") else list(p.getdata())
|
|
201
|
+
mr = sorted(c[0] for c in px)[len(px) // 2]
|
|
202
|
+
mg = sorted(c[1] for c in px)[len(px) // 2]
|
|
203
|
+
mb = sorted(c[2] for c in px)[len(px) // 2]
|
|
204
|
+
var = sum((c[0] - mr) ** 2 + (c[1] - mg) ** 2 + (c[2] - mb) ** 2 for c in px) / max(1, len(px))
|
|
205
|
+
# Accept smooth directional tonal shifts (var <= 220), reject hard graphic/photo corners
|
|
206
|
+
if var <= 220:
|
|
207
|
+
corners.append((mr, mg, mb))
|
|
208
|
+
else:
|
|
209
|
+
corners.append((ref_r, ref_g, ref_b))
|
|
210
|
+
|
|
211
|
+
grid2 = Image.new("RGB", (2, 2))
|
|
212
|
+
grid2.putdata(corners)
|
|
213
|
+
grad_canvas = grid2.resize((out_w, out_h), Image.Resampling.BILINEAR)
|
|
214
|
+
|
|
215
|
+
# Blend 35% of the clean tile's subtle micro-texture back onto the smooth tonal wash
|
|
216
|
+
tile_stretched = clean_tile.resize((out_w, out_h), Image.Resampling.BICUBIC)
|
|
217
|
+
return Image.blend(grad_canvas, tile_stretched, 0.30)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _extract_dominant_hex_colors(rgb: Image.Image, count: int = 4) -> list[str]:
|
|
221
|
+
"""Quantize an image into distinct dominant hex swatches."""
|
|
222
|
+
small = rgb.resize((160, 90), Image.Resampling.BILINEAR)
|
|
223
|
+
pal_im = small.quantize(colors=max(count * 3, 12), method=Image.Quantize.MEDIANCUT)
|
|
224
|
+
palette = pal_im.getpalette() or []
|
|
225
|
+
hist = sorted(pal_im.getcolors() or [], reverse=True)
|
|
226
|
+
picked: list[tuple[int, int, int]] = []
|
|
227
|
+
for _cnt, idx in hist:
|
|
228
|
+
base = idx * 3
|
|
229
|
+
if base + 2 >= len(palette):
|
|
230
|
+
continue
|
|
231
|
+
c = (palette[base], palette[base + 1], palette[base + 2])
|
|
232
|
+
if all(sum((c[i] - p[i]) ** 2 for i in range(3)) > 1600 for p in picked):
|
|
233
|
+
picked.append(c)
|
|
234
|
+
if len(picked) >= count:
|
|
235
|
+
break
|
|
236
|
+
return [f"#{r:02X}{g:02X}{b:02X}" for r, g, b in picked]
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _normalize_color_tokens(raw: list[str] | str | None) -> list[str]:
|
|
240
|
+
"""Accept a list of hex colors, a JSON array string, or comma/whitespace-separated hex strings."""
|
|
241
|
+
if not raw:
|
|
242
|
+
return []
|
|
243
|
+
candidates: list[str] = []
|
|
244
|
+
if isinstance(raw, list):
|
|
245
|
+
candidates = [str(item).strip() for item in raw if str(item).strip()]
|
|
246
|
+
elif isinstance(raw, str):
|
|
247
|
+
text = raw.strip()
|
|
248
|
+
if not text:
|
|
249
|
+
return []
|
|
250
|
+
if text.startswith("[") and text.endswith("]"):
|
|
251
|
+
try:
|
|
252
|
+
parsed = json.loads(text)
|
|
253
|
+
if isinstance(parsed, list):
|
|
254
|
+
candidates = [str(item).strip() for item in parsed if str(item).strip()]
|
|
255
|
+
except Exception:
|
|
256
|
+
pass
|
|
257
|
+
if not candidates:
|
|
258
|
+
# Strip surrounding brackets/quotes and split by comma/semicolon/whitespace
|
|
259
|
+
cleaned = text.strip("[](){}")
|
|
260
|
+
for part in cleaned.replace(";", ",").split(","):
|
|
261
|
+
tok = part.strip().strip("\"'` ")
|
|
262
|
+
if tok:
|
|
263
|
+
candidates.append(tok)
|
|
264
|
+
|
|
265
|
+
out: list[str] = []
|
|
266
|
+
for c in candidates:
|
|
267
|
+
c_clean = c.strip().strip("\"'` ")
|
|
268
|
+
if not c_clean:
|
|
269
|
+
continue
|
|
270
|
+
_parse_hex(c_clean)
|
|
271
|
+
out.append(c_clean.upper() if c_clean.startswith("#") else f"#{c_clean.upper()}")
|
|
272
|
+
return out
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def build_style_swatch(
|
|
276
|
+
src: Path,
|
|
277
|
+
out: Path,
|
|
278
|
+
*,
|
|
279
|
+
colors: list[str] | str | None = None,
|
|
280
|
+
logo: Path | None = None,
|
|
281
|
+
size: tuple[int, int] = (1280, 720),
|
|
282
|
+
) -> dict:
|
|
283
|
+
"""Create a composition-free Style Swatch (surface texture + palette chips + optional logo) from an anchor slide.
|
|
284
|
+
|
|
285
|
+
Unlike passing a full composed slide as --ref (which causes layout lock), this swatch transfers ONLY
|
|
286
|
+
canvas material, color temperature, and palette harmony with ZERO slide grid or layout boxes.
|
|
287
|
+
"""
|
|
288
|
+
if not src.is_file():
|
|
289
|
+
raise FileNotFoundError(f"Anchor image not found: {src}")
|
|
290
|
+
w, h = size
|
|
291
|
+
with Image.open(src) as raw:
|
|
292
|
+
rgb = _to_rgb_white_bg(raw)
|
|
293
|
+
canvas = _reconstruct_surface_canvas(rgb, (w, h))
|
|
294
|
+
palette_hex = _normalize_color_tokens(colors)
|
|
295
|
+
if not palette_hex:
|
|
296
|
+
palette_hex = _extract_dominant_hex_colors(rgb, count=4)
|
|
297
|
+
|
|
298
|
+
draw = ImageDraw.Draw(canvas)
|
|
299
|
+
|
|
300
|
+
# Place clean circular palette chips along the lower center (abstract material tokens, not a slide UI grid)
|
|
301
|
+
n_chips = min(6, len(palette_hex))
|
|
302
|
+
if n_chips > 0:
|
|
303
|
+
chip_r = 46
|
|
304
|
+
gap = 38
|
|
305
|
+
total_w = n_chips * (chip_r * 2) + (n_chips - 1) * gap
|
|
306
|
+
start_x = (w - total_w) // 2 + chip_r
|
|
307
|
+
cy = int(h * 0.65)
|
|
308
|
+
for idx, hex_c in enumerate(palette_hex[:n_chips]):
|
|
309
|
+
cx = start_x + idx * (chip_r * 2 + gap)
|
|
310
|
+
c_rgb = _parse_hex(hex_c)
|
|
311
|
+
lum = 0.2126 * c_rgb[0] + 0.7152 * c_rgb[1] + 0.722 * c_rgb[2] if False else (0.2126 * c_rgb[0] + 0.7152 * c_rgb[1] + 0.0722 * c_rgb[2])
|
|
312
|
+
ring_rgb = (180, 176, 168) if lum > 200 else (235, 232, 226)
|
|
313
|
+
draw.ellipse((cx - chip_r, cy - chip_r, cx + chip_r, cy + chip_r), fill=c_rgb, outline=ring_rgb, width=2)
|
|
314
|
+
|
|
315
|
+
# Optional crisp transparent logo mark centered above chips — large enough to stay legible inside multi-ref boards
|
|
316
|
+
logo_used = False
|
|
317
|
+
if logo and logo.is_file():
|
|
318
|
+
try:
|
|
319
|
+
with Image.open(logo) as raw_logo:
|
|
320
|
+
lg = raw_logo.convert("RGBA")
|
|
321
|
+
aspect = lg.width / max(1, lg.height)
|
|
322
|
+
max_lw, max_lh = (320, 130) if aspect > 1.6 else (180, 180)
|
|
323
|
+
scale = min(max_lw / max(1, lg.width), max_lh / max(1, lg.height), 1.0)
|
|
324
|
+
lg = lg.resize((max(1, round(lg.width * scale)), max(1, round(lg.height * scale))), Image.Resampling.LANCZOS)
|
|
325
|
+
lx = (w - lg.width) // 2
|
|
326
|
+
ly = int(h * 0.30) - lg.height // 2
|
|
327
|
+
canvas.paste(lg, (lx, ly), mask=lg.getchannel("A"))
|
|
328
|
+
logo_used = True
|
|
329
|
+
except Exception:
|
|
330
|
+
logo_used = False
|
|
331
|
+
|
|
332
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
333
|
+
canvas.save(out, format="PNG", optimize=True)
|
|
334
|
+
return {
|
|
335
|
+
"ok": True,
|
|
336
|
+
"input": str(src),
|
|
337
|
+
"out": str(out),
|
|
338
|
+
"size": [w, h],
|
|
339
|
+
"palette": palette_hex[:6],
|
|
340
|
+
"logo_embedded": logo_used,
|
|
341
|
+
"composition_free": True,
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _configure_utf8_stdio() -> None:
|
|
346
|
+
import sys
|
|
347
|
+
|
|
348
|
+
for stream in (sys.stdout, sys.stderr):
|
|
349
|
+
if stream is not None:
|
|
350
|
+
try:
|
|
351
|
+
if not stream.isatty() and hasattr(stream, "reconfigure"):
|
|
352
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
353
|
+
except Exception:
|
|
354
|
+
pass
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def main() -> None:
|
|
358
|
+
_configure_utf8_stdio()
|
|
359
|
+
parser = argparse.ArgumentParser(description="Prepare reference JPEGs (<2 MiB), composition-free style swatches, and contact sheets.")
|
|
360
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
361
|
+
|
|
362
|
+
p_ref = sub.add_parser("prepare-ref", help="Downscale/compress an image under max-bytes JPEG for --ref.")
|
|
363
|
+
p_ref.add_argument("input", type=Path, help="Source image (.png/.jpg/.webp).")
|
|
364
|
+
p_ref.add_argument("--out", required=True, type=Path, help="Output JPEG path.")
|
|
365
|
+
p_ref.add_argument("--max-bytes", type=int, default=1_950_000, help="Max output bytes (default: 1950000).")
|
|
366
|
+
p_ref.add_argument("--max-dim", type=int, default=2048, help="Max long edge px before JPEG pass (default: 2048).")
|
|
367
|
+
p_ref.add_argument("--json", action="store_true", help="Emit compact single-line JSON.")
|
|
368
|
+
|
|
369
|
+
p_st = sub.add_parser("stitch", help="Stitch images into an N-up overview contact sheet PNG.")
|
|
370
|
+
p_st.add_argument("inputs", nargs="+", type=Path, help="Input image paths in display order.")
|
|
371
|
+
p_st.add_argument("--out", required=True, type=Path, help="Output stitched PNG path.")
|
|
372
|
+
p_st.add_argument("--cols", type=int, default=2, help="Number of columns (default: 2).")
|
|
373
|
+
p_st.add_argument("--pad", type=int, default=36, help="Padding between tiles in px (default: 36).")
|
|
374
|
+
p_st.add_argument("--bg", type=str, default="#E8EDF6", help="Canvas background hex (default: #E8EDF6).")
|
|
375
|
+
p_st.add_argument("--tile-width", type=int, default=960, help="Scaled tile width in px (default: 960).")
|
|
376
|
+
p_st.add_argument("--labels", type=str, default=None, help="Optional comma-separated tile labels.")
|
|
377
|
+
p_st.add_argument("--json", action="store_true", help="Emit compact single-line JSON.")
|
|
378
|
+
|
|
379
|
+
p_sw = sub.add_parser("style-swatch", help="Build a composition-free Style Swatch (surface + palette) from an approved anchor slide.")
|
|
380
|
+
p_sw.add_argument("input", type=Path, help="Approved anchor slide image (e.g. s1.png).")
|
|
381
|
+
p_sw.add_argument("--out", required=True, type=Path, help="Output style-swatch PNG path.")
|
|
382
|
+
p_sw.add_argument("--colors", type=str, default=None, help="Optional comma-separated #HEX palette tokens.")
|
|
383
|
+
p_sw.add_argument("--logo", type=Path, default=None, help="Optional transparent brand logo PNG.")
|
|
384
|
+
p_sw.add_argument("--json", action="store_true", help="Emit compact single-line JSON.")
|
|
385
|
+
|
|
386
|
+
args = parser.parse_args()
|
|
387
|
+
if args.command == "prepare-ref":
|
|
388
|
+
res = prepare_ref(args.input.resolve(), args.out.resolve(), max_bytes=args.max_bytes, max_dim=args.max_dim)
|
|
389
|
+
elif args.command == "style-swatch":
|
|
390
|
+
col_list = _normalize_color_tokens(args.colors) if args.colors else None
|
|
391
|
+
logo_p = args.logo.resolve() if args.logo else None
|
|
392
|
+
res = build_style_swatch(args.input.resolve(), args.out.resolve(), colors=col_list, logo=logo_p)
|
|
393
|
+
else:
|
|
394
|
+
lbls = [s.strip() for s in args.labels.split(",")] if args.labels else None
|
|
395
|
+
res = stitch_grid(
|
|
396
|
+
[p.resolve() for p in args.inputs],
|
|
397
|
+
args.out.resolve(),
|
|
398
|
+
cols=args.cols,
|
|
399
|
+
pad=args.pad,
|
|
400
|
+
bg_hex=args.bg,
|
|
401
|
+
tile_width=args.tile_width,
|
|
402
|
+
labels=lbls,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
if args.json:
|
|
406
|
+
print(json.dumps(res, ensure_ascii=False))
|
|
407
|
+
else:
|
|
408
|
+
print(json.dumps(res, indent=2, ensure_ascii=False))
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
if __name__ == "__main__":
|
|
412
|
+
main()
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Generate banding-free same-hue radial atmospheric gradient plates (dark or light) via linear-light + TPDF dithering."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import random
|
|
9
|
+
import re
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
import numpy as np # type: ignore
|
|
14
|
+
except ImportError:
|
|
15
|
+
np = None # type: ignore
|
|
16
|
+
from PIL import Image
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _parse_hex_tuple(hex_color: str) -> tuple[float, float, float]:
|
|
20
|
+
value = hex_color.strip().lstrip("#")
|
|
21
|
+
if len(value) == 3:
|
|
22
|
+
value = "".join(c * 2 for c in value)
|
|
23
|
+
if not re.match(r"^[0-9A-Fa-f]{6}$", value):
|
|
24
|
+
raise ValueError(f"Expected 6-digit hex color, got {hex_color!r}")
|
|
25
|
+
return (
|
|
26
|
+
float(int(value[0:2], 16)),
|
|
27
|
+
float(int(value[2:4], 16)),
|
|
28
|
+
float(int(value[4:6], 16)),
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _srgb_val_to_linear(v: float) -> float:
|
|
33
|
+
x = v / 255.0
|
|
34
|
+
return x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _linear_val_to_srgb(x: float) -> float:
|
|
38
|
+
x = 0.0 if x < 0.0 else (1.0 if x > 1.0 else x)
|
|
39
|
+
s = 12.92 * x if x <= 0.0031308 else 1.055 * (x ** (1.0 / 2.4)) - 0.055
|
|
40
|
+
return s * 255.0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _hex_to_rgb(hex_color: str):
|
|
44
|
+
rgb = _parse_hex_tuple(hex_color)
|
|
45
|
+
return np.array(rgb, dtype=np.float64) if np is not None else rgb
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _srgb_to_linear(c):
|
|
49
|
+
x = c / 255.0
|
|
50
|
+
return np.where(x <= 0.04045, x / 12.92, ((x + 0.055) / 1.055) ** 2.4)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _linear_to_srgb(x):
|
|
54
|
+
x = np.clip(x, 0.0, 1.0)
|
|
55
|
+
s = np.where(x <= 0.0031308, 12.92 * x, 1.055 * (x ** (1.0 / 2.4)) - 0.055)
|
|
56
|
+
return s * 255.0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_RATIO_SIZES: dict[str, tuple[int, int]] = {
|
|
60
|
+
"16:9": (1920, 1080),
|
|
61
|
+
"3:4": (1080, 1440),
|
|
62
|
+
"9:16": (1080, 1920),
|
|
63
|
+
"1:1": (1440, 1440),
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def parse_pair(raw: str, label: str) -> tuple[float, float]:
|
|
68
|
+
tok = raw.strip().lower().replace("×", "x").replace("/", ":")
|
|
69
|
+
if label == "size" and tok in _RATIO_SIZES:
|
|
70
|
+
w, h = _RATIO_SIZES[tok]
|
|
71
|
+
return float(w), float(h)
|
|
72
|
+
parts = [p.strip() for p in raw.replace("×", "x").replace("x", ",").split(",")]
|
|
73
|
+
if len(parts) != 2:
|
|
74
|
+
raise ValueError(f"Invalid {label} pair: {raw!r}")
|
|
75
|
+
return float(parts[0]), float(parts[1])
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _render_radial_gradient_pure_pillow(
|
|
79
|
+
out_path: Path,
|
|
80
|
+
*,
|
|
81
|
+
base_hex: str,
|
|
82
|
+
glow_hex: str,
|
|
83
|
+
mid_hex: str | None,
|
|
84
|
+
cx: float,
|
|
85
|
+
cy: float,
|
|
86
|
+
rx: float,
|
|
87
|
+
ry: float,
|
|
88
|
+
width: int,
|
|
89
|
+
height: int,
|
|
90
|
+
dither: float,
|
|
91
|
+
seed: int,
|
|
92
|
+
) -> None:
|
|
93
|
+
"""Zero-numpy fallback: compute smooth radial gradient on proportional <=480px linear grid and upscale cleanly."""
|
|
94
|
+
scale_down = min(1.0, 480.0 / max(1, width, height))
|
|
95
|
+
sw = max(1, int(round(width * scale_down)))
|
|
96
|
+
sh = max(1, int(round(height * scale_down)))
|
|
97
|
+
c_out = tuple(_srgb_val_to_linear(v) for v in _parse_hex_tuple(base_hex))
|
|
98
|
+
c_in = tuple(_srgb_val_to_linear(v) for v in _parse_hex_tuple(glow_hex))
|
|
99
|
+
c_mid = (
|
|
100
|
+
tuple(_srgb_val_to_linear(v) for v in _parse_hex_tuple(mid_hex))
|
|
101
|
+
if mid_hex
|
|
102
|
+
else tuple(0.65 * o + 0.35 * i for o, i in zip(c_out, c_in))
|
|
103
|
+
)
|
|
104
|
+
rng = random.Random(seed)
|
|
105
|
+
buf = bytearray(sw * sh * 3)
|
|
106
|
+
pos = 0
|
|
107
|
+
for py in range(sh):
|
|
108
|
+
dy = (((py + 0.5) / sh) - cy) / ry
|
|
109
|
+
dy2 = dy * dy
|
|
110
|
+
for px in range(sw):
|
|
111
|
+
dx = (((px + 0.5) / sw) - cx) / rx
|
|
112
|
+
dist = math.sqrt(dx * dx + dy2)
|
|
113
|
+
t = 1.0 if dist >= 1.0 else dist
|
|
114
|
+
falloff = 0.5 * (1.0 + math.cos(math.pi * t))
|
|
115
|
+
w_in = 0.0 if falloff <= 0.35 else min(1.0, (falloff - 0.35) / 0.65)
|
|
116
|
+
w_mid = min(1.0, falloff / 0.35)
|
|
117
|
+
for ch in range(3):
|
|
118
|
+
s1 = c_out[ch] * (1.0 - w_mid) + c_mid[ch] * w_mid
|
|
119
|
+
lin = s1 * (1.0 - w_in) + c_in[ch] * w_in
|
|
120
|
+
val = _linear_val_to_srgb(lin)
|
|
121
|
+
if dither > 0:
|
|
122
|
+
val += (rng.random() + rng.random() - 1.0) * float(dither)
|
|
123
|
+
buf[pos] = 0 if val < 0 else (255 if val > 255 else int(round(val)))
|
|
124
|
+
pos += 1
|
|
125
|
+
img = Image.frombytes("RGB", (sw, sh), bytes(buf))
|
|
126
|
+
if (sw, sh) != (width, height):
|
|
127
|
+
img = img.resize((width, height), Image.Resampling.BICUBIC)
|
|
128
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
129
|
+
img.save(out_path, format="PNG", optimize=True)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def render_radial_gradient(
|
|
133
|
+
out_path: Path,
|
|
134
|
+
*,
|
|
135
|
+
base_hex: str,
|
|
136
|
+
glow_hex: str,
|
|
137
|
+
mid_hex: str | None = None,
|
|
138
|
+
focus: tuple[float, float] = (0.72, 0.40),
|
|
139
|
+
radii: tuple[float, float] = (0.68, 0.72),
|
|
140
|
+
size: tuple[int, int] = (1920, 1080),
|
|
141
|
+
dither: float = 0.85,
|
|
142
|
+
seed: int = 20261121,
|
|
143
|
+
) -> dict:
|
|
144
|
+
"""Render a smooth radial gradient PNG in linear-light space with TPDF dithering."""
|
|
145
|
+
width, height = int(size[0]), int(size[1])
|
|
146
|
+
cx, cy = float(focus[0]), float(focus[1])
|
|
147
|
+
rx, ry = max(0.05, float(radii[0])), max(0.05, float(radii[1]))
|
|
148
|
+
|
|
149
|
+
if np is None:
|
|
150
|
+
_render_radial_gradient_pure_pillow(
|
|
151
|
+
out_path,
|
|
152
|
+
base_hex=base_hex,
|
|
153
|
+
glow_hex=glow_hex,
|
|
154
|
+
mid_hex=mid_hex,
|
|
155
|
+
cx=cx,
|
|
156
|
+
cy=cy,
|
|
157
|
+
rx=rx,
|
|
158
|
+
ry=ry,
|
|
159
|
+
width=width,
|
|
160
|
+
height=height,
|
|
161
|
+
dither=dither,
|
|
162
|
+
seed=seed,
|
|
163
|
+
)
|
|
164
|
+
else:
|
|
165
|
+
xs = (np.arange(width, dtype=np.float64) + 0.5) / width
|
|
166
|
+
ys = (np.arange(height, dtype=np.float64) + 0.5) / height
|
|
167
|
+
grid_x, grid_y = np.meshgrid(xs, ys)
|
|
168
|
+
|
|
169
|
+
dist = np.sqrt(((grid_x - cx) / rx) ** 2 + ((grid_y - cy) / ry) ** 2)
|
|
170
|
+
t = np.clip(dist, 0.0, 1.0)
|
|
171
|
+
falloff = 0.5 * (1.0 + np.cos(np.pi * t))
|
|
172
|
+
|
|
173
|
+
c_outer = _srgb_to_linear(_hex_to_rgb(base_hex))
|
|
174
|
+
c_inner = _srgb_to_linear(_hex_to_rgb(glow_hex))
|
|
175
|
+
c_mid = _srgb_to_linear(_hex_to_rgb(mid_hex)) if mid_hex else (0.65 * c_outer + 0.35 * c_inner)
|
|
176
|
+
|
|
177
|
+
w_inner = np.clip((falloff - 0.35) / 0.65, 0.0, 1.0)[..., None]
|
|
178
|
+
w_mid = np.clip(falloff / 0.35, 0.0, 1.0)[..., None]
|
|
179
|
+
|
|
180
|
+
stage1 = c_outer[None, None, :] * (1.0 - w_mid) + c_mid[None, None, :] * w_mid
|
|
181
|
+
linear_img = stage1 * (1.0 - w_inner) + c_inner[None, None, :] * w_inner
|
|
182
|
+
srgb_float = _linear_to_srgb(linear_img)
|
|
183
|
+
|
|
184
|
+
if dither > 0:
|
|
185
|
+
rng = np.random.default_rng(seed=seed)
|
|
186
|
+
noise = (rng.random((height, width, 3)) + rng.random((height, width, 3)) - 1.0) * float(dither)
|
|
187
|
+
srgb_float = srgb_float + noise
|
|
188
|
+
|
|
189
|
+
quantized = np.clip(np.rint(srgb_float), 0, 255).astype(np.uint8)
|
|
190
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
Image.fromarray(quantized, mode="RGB").save(out_path, format="PNG", optimize=True)
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
"ok": True,
|
|
195
|
+
"out": str(out_path),
|
|
196
|
+
"size": [width, height],
|
|
197
|
+
"base": base_hex.upper(),
|
|
198
|
+
"mid": (mid_hex.upper() if mid_hex else "auto"),
|
|
199
|
+
"glow": glow_hex.upper(),
|
|
200
|
+
"focus": [cx, cy],
|
|
201
|
+
"radii": [rx, ry],
|
|
202
|
+
"dither": dither,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _configure_utf8_stdio() -> None:
|
|
207
|
+
import sys
|
|
208
|
+
|
|
209
|
+
for stream in (sys.stdout, sys.stderr):
|
|
210
|
+
if stream is not None:
|
|
211
|
+
try:
|
|
212
|
+
if not stream.isatty() and hasattr(stream, "reconfigure"):
|
|
213
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
214
|
+
except Exception:
|
|
215
|
+
pass
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def main() -> None:
|
|
219
|
+
_configure_utf8_stdio()
|
|
220
|
+
parser = argparse.ArgumentParser(
|
|
221
|
+
description="Render banding-free radial atmospheric gradient PNG for T2 slides (dark or light)."
|
|
222
|
+
)
|
|
223
|
+
parser.add_argument("--base", required=True, type=str, help="Outer edge hex color, e.g. '#050B18' or '#ECEFE5'.")
|
|
224
|
+
parser.add_argument("--glow", required=True, type=str, help="Focal glow hex color, e.g. '#102A66' or '#FAF8F1'.")
|
|
225
|
+
parser.add_argument("--mid", type=str, default=None, help="Optional midpoint hex color.")
|
|
226
|
+
parser.add_argument("--focus", type=str, default="0.72,0.40", help="Normalized focal center 'cx,cy' (default: 0.72,0.40).")
|
|
227
|
+
parser.add_argument("--radii", type=str, default="0.68,0.72", help="Normalized ellipse radii 'rx,ry' (default: 0.68,0.72).")
|
|
228
|
+
parser.add_argument("--size", type=str, default="1920x1080", help="Output resolution 'WxH' or ratio '16:9'|'3:4'|'9:16'|'1:1' (default: 1920x1080).")
|
|
229
|
+
parser.add_argument("--ratio", "--aspect-ratio", dest="ratio", type=str, default=None, help="Optional canvas aspect ratio ('16:9', '3:4', '9:16', '1:1').")
|
|
230
|
+
parser.add_argument("--dither", type=float, default=0.85, help="TPDF dither amplitude in LSB (default: 0.85).")
|
|
231
|
+
parser.add_argument("--seed", type=int, default=20261121, help="Deterministic RNG seed for dithering.")
|
|
232
|
+
parser.add_argument("--out", required=True, type=Path, help="Output PNG path.")
|
|
233
|
+
parser.add_argument("--json", action="store_true", help="Emit compact single-line JSON.")
|
|
234
|
+
args = parser.parse_args()
|
|
235
|
+
|
|
236
|
+
w, h = parse_pair(args.ratio if args.ratio else args.size, "size")
|
|
237
|
+
cx, cy = parse_pair(args.focus, "focus")
|
|
238
|
+
rx, ry = parse_pair(args.radii, "radii")
|
|
239
|
+
|
|
240
|
+
res = render_radial_gradient(
|
|
241
|
+
args.out.resolve(),
|
|
242
|
+
base_hex=args.base,
|
|
243
|
+
glow_hex=args.glow,
|
|
244
|
+
mid_hex=args.mid,
|
|
245
|
+
focus=(cx, cy),
|
|
246
|
+
radii=(rx, ry),
|
|
247
|
+
size=(int(w), int(h)),
|
|
248
|
+
dither=args.dither,
|
|
249
|
+
seed=args.seed,
|
|
250
|
+
)
|
|
251
|
+
if args.json:
|
|
252
|
+
print(json.dumps(res, ensure_ascii=False))
|
|
253
|
+
else:
|
|
254
|
+
print(json.dumps(res, indent=2, ensure_ascii=False))
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
if __name__ == "__main__":
|
|
258
|
+
main()
|