Branchwell

Lumen & Gesso / website / scripts / generate-style-examples.mjs

1#!/usr/bin/env node
2// Generate style examples — same reference photo, eight (or N) prompts,
3// dispatched to the right image model per style.
4//
5// Default routing:
6// - watercolor + charcoal → gemini-3-pro-image (Nano Banana)
7// - everything else → gpt-image-2 (OpenAI)
8//
9// Usage:
10// OPENAI_API_KEY=sk-... GEMINI_API_KEY=AIza... npm run gen:examples
11//
12// Optional env:
13// REFERENCE path to the reference photo (default: public/portraits/before-daisy.jpg)
14// SIZE image size, e.g. 1024x1024 (default; only honored by OpenAI)
15// OUT_DIR output dir under /public (default: portraits/examples)
16// ONLY comma-separated prompt ids to render
17// NAME pet name substituted into {{NAME}} prompt tokens (default: Teddy)
18// PET when set, output files are named after-{PET}-{id}.png.
19// Use this to render the per-pet catalog images that live
20// directly in public/portraits/ rather than the OUT_DIR
21// example tiles. Pair with OUT_DIR=portraits + REFERENCE=...
22//
23// Per-model env keys are only required for the models you actually use.
24// If you omit a key and a style needs that model, that style is skipped
25// with a clear log line.
26
27import fs from 'node:fs';
28import path from 'node:path';
29import { fileURLToPath } from 'node:url';
30import { spawn } from 'node:child_process';
31
32const __dirname = path.dirname(fileURLToPath(import.meta.url));
33const ROOT = path.resolve(__dirname, '..');
34
35// Resolve rembg — installed via pipx, lives at ~/.local/bin/rembg by
36// default. Override with REMBG_BIN if it's somewhere else.
37const REMBG = process.env.REMBG_BIN || path.join(process.env.HOME || '', '.local/bin/rembg');
38// Background-removal model. isnet-general-use handles illustrated /
39// painted subjects on near-uniform backgrounds well. u2net is the
40// rembg default and a reasonable fallback.
41const REMBG_MODEL = process.env.REMBG_MODEL || 'isnet-general-use';
42
43// ─── Config ─────────────────────────────────────────────────────────
44const OPENAI_KEY = process.env.OPENAI_API_KEY;
45const GEMINI_KEY = process.env.GEMINI_API_KEY;
46const SIZE = process.env.SIZE || '1024x1024';
47// Gemini (Nano Banana Pro) output tier — default to the highest (4K).
48// Override with GEMINI_IMAGE_SIZE=1K/2K for quick, cheap test runs.
49const GEMINI_IMAGE_SIZE = process.env.GEMINI_IMAGE_SIZE || '4K';
50const REFERENCE = path.resolve(ROOT, process.env.REFERENCE || 'public/portraits/before-daisy.jpg');
51const OUT_DIR = path.resolve(ROOT, 'public', process.env.OUT_DIR || 'portraits/examples');
52const ONLY = process.env.ONLY ? new Set(process.env.ONLY.split(',').map((s) => s.trim())) : null;
53const NAME = process.env.NAME || 'Teddy';
54const PET = (process.env.PET || '').trim() || null;
55
56if (!fs.existsSync(REFERENCE)) {
57 console.error(`Reference image not found: ${REFERENCE}`);
58 process.exit(1);
59}
60
61// ─── Per-style model routing ────────────────────────────────────────
62// Model routing. We use TWO models — gpt-image-2 (OpenAI) and
63// gemini-3-pro-image (Google Nano Banana). gpt-image-1 is
64// intentionally NOT in the rotation: it's the old model and we want
65// every render on the current generation.
66const MODEL_OVERRIDES = {
67 // Pop art reads best out of Nano Banana — flatter colour, bolder
68 // line work than what -2 produces.
69 popart: 'gemini-3-pro-image',
70 // Watercolor: Nano Banana handles wet pigment and soft pooled edges
71 // significantly better than gpt-image-2, especially on baked-bg
72 // variants where we need the watercolor edges to dissolve into the
73 // ground colour rather than carry a transparent halo.
74 watercolor: 'gemini-3-pro-image',
75 // Risograph: Nano Banana handles flat ink fields, halftone dots, and
76 // bleed-off-edge composition cleaner than gpt-image-2.
77 risograph: 'gemini-3-pro-image',
78 // Neo-expressionist: Nano Banana renders the gestural drips, large
79 // graffiti icons, and raw canvas energy with more confidence.
80 neoexpressionist: 'gemini-3-pro-image',
81 // Landscape (classical oil): the painted scene + loaded brushwork read
82 // far richer out of Nano Banana — gpt-image-2 smudges the face and
83 // flattens the Old-Master palette.
84 'landscape-oil': 'gemini-3-pro-image',
85 // Vector (flat illustration): Nano Banana commits to bold flat colour
86 // blocks; gpt-image-2's image-edit anchors to the reference photo and
87 // stays too detailed. (Vector is alpha-stripped via rembg either way.)
88 vector: 'gemini-3-pro-image',
89 // At Home (retro): gpt-image-2 wins for photoreal interiors with
90 // period-specific props — Gemini softens into illustration.
91 // (Default model is already gpt-image-2, but listed here for clarity.)
92 athome: 'gpt-image-2',
93};
94const DEFAULT_MODEL = 'gpt-image-2';
95const modelFor = (id) => MODEL_OVERRIDES[id] || DEFAULT_MODEL;
96// Styles that render opaque on flat white and then get background-stripped
97// via rembg, producing a true-alpha PNG so the customer-chosen ground
98// colour composites cleanly behind it at preview/print time.
99//
100// Excluded: 'lineart' and 'charcoal' — those are composited via
101// mix-blend-mode: multiply over the chosen ground, which drops out white
102// pixels naturally. They render onto a flat #FFFFFF surround instead,
103// which gives cleaner edges than rembg masking for grayscale art.
104const TRANSPARENT_BG_STYLES = new Set(['watercolor', 'vector', 'named']);
105
106// ─── Load prompts from the TypeScript module ────────────────────────
107// We read the .ts file as text and extract just the data we need rather
108// than depend on a TS runtime — keeps the script zero-dependency.
109const promptsTs = fs.readFileSync(path.join(ROOT, 'app/data/portraitPrompts.ts'), 'utf8');
110
111function extractConst(name) {
112 const re = new RegExp('const ' + name + ' = `([\\s\\S]*?)`;', 'm');
113 const m = promptsTs.match(re);
114 if (!m) throw new Error('Could not find prompt const: ' + name);
115 return m[1];
116}
117
118// The hasSolidBackground prompts (watercolor, lineart, charcoal, vector,
119// named) carry {{BG_HEX}}/{{BG_LABEL}} placeholders that the live admin
120// route substitutes with the customer's chosen colour. The script bakes
121// the catalog example tiles on flat white so they can be rembg-stripped
122// into transparent PNGs (the Builder composites them over the chosen
123// ground at preview time). Substitute white defaults here so the model
124// never sees raw placeholder tokens.
125function bakeBg(s) {
126 return s.replace(/\{\{BG_HEX\}\}/g, '#FFFFFF').replace(/\{\{BG_LABEL\}\}/g, 'white');
127}
128
129
130const PROMPTS = [
131 { id: 'watercolor', name: 'Watercolor', prompt: bakeBg(extractConst('WATERCOLOR')) },
132 { id: 'lineart', name: 'Line Drawing', prompt: bakeBg(extractConst('LINEART')) },
133 { id: 'cubist', name: 'Cubist', prompt: extractConst('CUBIST') },
134 { id: 'ukiyoe', name: 'Ukiyo-e', prompt: extractConst('UKIYOE') },
135 { id: 'thangka', name: 'Thangka', prompt: extractConst('THANGKA') },
136 { id: 'mixedmedia', name: 'Mixed-Media', prompt: extractConst('MIXEDMEDIA') },
137 { id: 'charcoal', name: 'Charcoal', prompt: bakeBg(extractConst('CHARCOAL')) },
138 { id: 'vector', name: 'Vector Outline', prompt: bakeBg(extractConst('VECTOR')) },
139 { id: 'popart', name: 'Pop Art', prompt: extractConst('POPART') },
140 { id: 'risograph', name: 'Risograph', prompt: extractConst('RISOGRAPH') },
141 { id: 'athome', name: 'At Home', prompt: extractConst('ATHOME') },
142 { id: 'neoexpressionist', name: 'Neo-Expressionist', prompt: extractConst('NEOEXPRESSIONIST') },
143 { id: 'landscape-oil', name: 'Landscape Oil', prompt: extractConst('LANDSCAPE_OIL') },
144 { id: 'named', name: 'Named Portrait', prompt: bakeBg(extractConst('NAMED').replace(/\{\{NAME\}\}/g, NAME)) },
145];
146
147// ─── Reference (loaded once) ────────────────────────────────────────
148fs.mkdirSync(OUT_DIR, { recursive: true });
149const refBytes = fs.readFileSync(REFERENCE);
150const refMime = REFERENCE.endsWith('.png') ? 'image/png' : 'image/jpeg';
151const refBlob = new Blob([refBytes], { type: refMime });
152const refName = path.basename(REFERENCE);
153const refB64 = refBytes.toString('base64');
154
155// ─── OpenAI path ────────────────────────────────────────────────────
156async function renderViaOpenAI({ id, name, prompt, model }, outPath) {
157 if (!OPENAI_KEY) throw new Error('OPENAI_API_KEY not set');
158 const form = new FormData();
159 form.set('model', model);
160 form.set('prompt', prompt);
161 form.set('size', SIZE);
162 form.set('n', '1');
163 // gpt-image-2 doesn't accept background: 'transparent'. Transparency
164 // for TRANSPARENT_BG_STYLES is produced by post-processing through
165 // rembg — see stripBackground() below.
166 form.append('image', refBlob, refName);
167 const r = await fetch('https://api.openai.com/v1/images/edits', {
168 method: 'POST',
169 headers: { Authorization: `Bearer ${OPENAI_KEY}` },
170 body: form,
171 });
172 if (!r.ok) {
173 const text = await r.text();
174 throw new Error(`${r.status} ${r.statusText}: ${text.slice(0, 400)}`);
175 }
176 const json = await r.json();
177 const b64 = json?.data?.[0]?.b64_json;
178 if (!b64) throw new Error('No image data in OpenAI response');
179 fs.writeFileSync(outPath, Buffer.from(b64, 'base64'));
180}
181
182// ─── Gemini path (Nano Banana) ──────────────────────────────────────
183async function renderViaGemini({ name, prompt, model }, outPath) {
184 if (!GEMINI_KEY) throw new Error('GEMINI_API_KEY not set');
185 const body = {
186 contents: [
187 {
188 parts: [
189 { text: prompt },
190 { inline_data: { mime_type: refMime, data: refB64 } },
191 ],
192 },
193 ],
194 generationConfig: {
195 responseModalities: ['image', 'text'],
196 imageConfig: { imageSize: GEMINI_IMAGE_SIZE },
197 },
198 };
199 const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`;
200 const r = await fetch(url, {
201 method: 'POST',
202 headers: {
203 'x-goog-api-key': GEMINI_KEY,
204 'content-type': 'application/json',
205 },
206 body: JSON.stringify(body),
207 });
208 if (!r.ok) {
209 const text = await r.text();
210 throw new Error(`${r.status} ${r.statusText}: ${text.slice(0, 400)}`);
211 }
212 const json = await r.json();
213 // Gemini returns parts; image data lives in part.inline_data.data
214 // (or inlineData.data depending on API version). Walk both forms.
215 const parts = json?.candidates?.[0]?.content?.parts ?? [];
216 let b64 = null;
217 for (const part of parts) {
218 const data = part?.inline_data?.data ?? part?.inlineData?.data;
219 if (data) { b64 = data; break; }
220 }
221 if (!b64) throw new Error('No image data in Gemini response');
222 fs.writeFileSync(outPath, Buffer.from(b64, 'base64'));
223}
224
225// ─── Output filename ────────────────────────────────────────────────
226// PET=fox → after-fox-{id}.png (the canonical per-pet name used by the
227// style catalog). No PET → falls back to the legacy `${id}.png` form
228// used for the catalog tile examples in OUT_DIR.
229function outPathFor(id) {
230 const base = PET ? `after-${PET}-${id}` : id;
231 return path.join(OUT_DIR, `${base}.png`);
232}
233
234// ─── Post-process: alpha halo cleanup ───────────────────────────────
235// rembg leaves a 1-2 pixel ring of low-alpha pixels around the subject
236// boundary whose RGB carries the original pigment colour. When composited
237// over a different ground colour at preview time, that ring shows as a
238// gray-brown halo around the silhouette. clean-alpha.mjs floors any
239// alpha < 80 to zero and erodes the mask by 1px — keeps the subject's
240// intended soft edge but kills the noise ring.
241function cleanAlpha(filePath) {
242 return new Promise((resolve, reject) => {
243 const proc = spawn('node', [path.join(ROOT, 'scripts/clean-alpha.mjs'), filePath], {
244 stdio: ['ignore', 'pipe', 'pipe'],
245 });
246 let err = '';
247 proc.stderr.on('data', (d) => (err += d.toString()));
248 proc.on('close', (code) => {
249 if (code === 0) resolve();
250 else reject(new Error(`clean-alpha exited ${code}: ${err.slice(0, 400)}`));
251 });
252 });
253}
254
255// ─── Post-process: background removal via rembg ─────────────────────
256// rembg is a Python CLI installed via pipx — see MEMORY.md for setup
257// notes. Replaces the image in place with a true-alpha RGBA PNG so the
258// customer-chosen ground colour can show through at preview/print.
259function stripBackground(filePath) {
260 return new Promise((resolve, reject) => {
261 if (!fs.existsSync(REMBG)) {
262 return reject(new Error(`rembg binary not found at ${REMBG}. Set REMBG_BIN or pipx install rembg.`));
263 }
264 // rembg truncates the input file before reading when input==output,
265 // so write to a sibling tmp and atomically rename when done.
266 const tmpPath = filePath + '.rembg.tmp.png';
267 const proc = spawn(REMBG, ['i', '-m', REMBG_MODEL, filePath, tmpPath], {
268 stdio: ['ignore', 'pipe', 'pipe'],
269 });
270 let err = '';
271 proc.stderr.on('data', (d) => (err += d.toString()));
272 proc.on('close', (code) => {
273 if (code === 0 && fs.existsSync(tmpPath)) {
274 fs.renameSync(tmpPath, filePath);
275 resolve();
276 } else {
277 try { fs.unlinkSync(tmpPath); } catch {}
278 reject(new Error(`rembg exited ${code}: ${err.slice(0, 400)}`));
279 }
280 });
281 });
282}
283
284// ─── Dispatcher ─────────────────────────────────────────────────────
285async function renderStyle({ id, name, prompt }) {
286 const model = modelFor(id);
287 const outPath = outPathFor(id);
288 const tag = model.startsWith('gemini') ? 'gemini' : 'openai';
289 const needsAlpha = TRANSPARENT_BG_STYLES.has(id);
290 console.log(`\n→ ${name.padEnd(16)} (${id}, ${tag} · ${model}${needsAlpha ? ' + rembg' : ''})`);
291
292 if (model.startsWith('gemini')) {
293 await renderViaGemini({ name, prompt, model }, outPath);
294 } else {
295 await renderViaOpenAI({ id, name, prompt, model }, outPath);
296 }
297 console.log(` saved ${path.relative(ROOT, outPath)}`);
298
299 if (needsAlpha && !process.env.SKIP_REMBG) {
300 console.log(` stripping background (${REMBG_MODEL})…`);
301 await stripBackground(outPath);
302 console.log(` ✓ transparent PNG`);
303 console.log(` cleaning alpha halo…`);
304 await cleanAlpha(outPath);
305 console.log(` ✓ halo cleaned`);
306 } else if (needsAlpha) {
307 console.log(` SKIP_REMBG set — leaving opaque-white background intact`);
308 }
309}
310
311// ─── Run ────────────────────────────────────────────────────────────
312const targets = ONLY ? PROMPTS.filter((p) => ONLY.has(p.id)) : PROMPTS;
313console.log(`Reference: ${path.relative(ROOT, REFERENCE)}`);
314console.log(`Size: ${SIZE} (OpenAI only)`);
315console.log(`Out: ${path.relative(ROOT, OUT_DIR)}`);
316console.log(`Pet: ${PET || '(none — using legacy ${id}.png filename)'}`);
317console.log(`Styles: ${targets.map((t) => `${t.id}→${modelFor(t.id).startsWith('gemini') ? 'gemini' : 'openai'}`).join(', ')}`);
318
319for (const t of targets) {
320 try {
321 await renderStyle(t);
322 } catch (err) {
323 console.error(` ✗ ${t.id}: ${err.message}`);
324 }
325}
326console.log('\nDone.');