#!/usr/bin/env node // Generate style examples — same reference photo, eight (or N) prompts, // dispatched to the right image model per style. // // Default routing: // - watercolor + charcoal → gemini-3-pro-image (Nano Banana) // - everything else → gpt-image-2 (OpenAI) // // Usage: // OPENAI_API_KEY=sk-... GEMINI_API_KEY=AIza... npm run gen:examples // // Optional env: // REFERENCE path to the reference photo (default: public/portraits/before-daisy.jpg) // SIZE image size, e.g. 1024x1024 (default; only honored by OpenAI) // OUT_DIR output dir under /public (default: portraits/examples) // ONLY comma-separated prompt ids to render // NAME pet name substituted into {{NAME}} prompt tokens (default: Teddy) // PET when set, output files are named after-{PET}-{id}.png. // Use this to render the per-pet catalog images that live // directly in public/portraits/ rather than the OUT_DIR // example tiles. Pair with OUT_DIR=portraits + REFERENCE=... // // Per-model env keys are only required for the models you actually use. // If you omit a key and a style needs that model, that style is skipped // with a clear log line. import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { spawn } from 'node:child_process'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(__dirname, '..'); // Resolve rembg — installed via pipx, lives at ~/.local/bin/rembg by // default. Override with REMBG_BIN if it's somewhere else. const REMBG = process.env.REMBG_BIN || path.join(process.env.HOME || '', '.local/bin/rembg'); // Background-removal model. isnet-general-use handles illustrated / // painted subjects on near-uniform backgrounds well. u2net is the // rembg default and a reasonable fallback. const REMBG_MODEL = process.env.REMBG_MODEL || 'isnet-general-use'; // ─── Config ───────────────────────────────────────────────────────── const OPENAI_KEY = process.env.OPENAI_API_KEY; const GEMINI_KEY = process.env.GEMINI_API_KEY; const SIZE = process.env.SIZE || '1024x1024'; // Gemini (Nano Banana Pro) output tier — default to the highest (4K). // Override with GEMINI_IMAGE_SIZE=1K/2K for quick, cheap test runs. const GEMINI_IMAGE_SIZE = process.env.GEMINI_IMAGE_SIZE || '4K'; const REFERENCE = path.resolve(ROOT, process.env.REFERENCE || 'public/portraits/before-daisy.jpg'); const OUT_DIR = path.resolve(ROOT, 'public', process.env.OUT_DIR || 'portraits/examples'); const ONLY = process.env.ONLY ? new Set(process.env.ONLY.split(',').map((s) => s.trim())) : null; const NAME = process.env.NAME || 'Teddy'; const PET = (process.env.PET || '').trim() || null; if (!fs.existsSync(REFERENCE)) { console.error(`Reference image not found: ${REFERENCE}`); process.exit(1); } // ─── Per-style model routing ──────────────────────────────────────── // Model routing. We use TWO models — gpt-image-2 (OpenAI) and // gemini-3-pro-image (Google Nano Banana). gpt-image-1 is // intentionally NOT in the rotation: it's the old model and we want // every render on the current generation. const MODEL_OVERRIDES = { // Pop art reads best out of Nano Banana — flatter colour, bolder // line work than what -2 produces. popart: 'gemini-3-pro-image', // Watercolor: Nano Banana handles wet pigment and soft pooled edges // significantly better than gpt-image-2, especially on baked-bg // variants where we need the watercolor edges to dissolve into the // ground colour rather than carry a transparent halo. watercolor: 'gemini-3-pro-image', // Risograph: Nano Banana handles flat ink fields, halftone dots, and // bleed-off-edge composition cleaner than gpt-image-2. risograph: 'gemini-3-pro-image', // Neo-expressionist: Nano Banana renders the gestural drips, large // graffiti icons, and raw canvas energy with more confidence. neoexpressionist: 'gemini-3-pro-image', // Landscape (classical oil): the painted scene + loaded brushwork read // far richer out of Nano Banana — gpt-image-2 smudges the face and // flattens the Old-Master palette. 'landscape-oil': 'gemini-3-pro-image', // Vector (flat illustration): Nano Banana commits to bold flat colour // blocks; gpt-image-2's image-edit anchors to the reference photo and // stays too detailed. (Vector is alpha-stripped via rembg either way.) vector: 'gemini-3-pro-image', // At Home (retro): gpt-image-2 wins for photoreal interiors with // period-specific props — Gemini softens into illustration. // (Default model is already gpt-image-2, but listed here for clarity.) athome: 'gpt-image-2', }; const DEFAULT_MODEL = 'gpt-image-2'; const modelFor = (id) => MODEL_OVERRIDES[id] || DEFAULT_MODEL; // Styles that render opaque on flat white and then get background-stripped // via rembg, producing a true-alpha PNG so the customer-chosen ground // colour composites cleanly behind it at preview/print time. // // Excluded: 'lineart' and 'charcoal' — those are composited via // mix-blend-mode: multiply over the chosen ground, which drops out white // pixels naturally. They render onto a flat #FFFFFF surround instead, // which gives cleaner edges than rembg masking for grayscale art. const TRANSPARENT_BG_STYLES = new Set(['watercolor', 'vector', 'named']); // ─── Load prompts from the TypeScript module ──────────────────────── // We read the .ts file as text and extract just the data we need rather // than depend on a TS runtime — keeps the script zero-dependency. const promptsTs = fs.readFileSync(path.join(ROOT, 'app/data/portraitPrompts.ts'), 'utf8'); function extractConst(name) { const re = new RegExp('const ' + name + ' = `([\\s\\S]*?)`;', 'm'); const m = promptsTs.match(re); if (!m) throw new Error('Could not find prompt const: ' + name); return m[1]; } // The hasSolidBackground prompts (watercolor, lineart, charcoal, vector, // named) carry {{BG_HEX}}/{{BG_LABEL}} placeholders that the live admin // route substitutes with the customer's chosen colour. The script bakes // the catalog example tiles on flat white so they can be rembg-stripped // into transparent PNGs (the Builder composites them over the chosen // ground at preview time). Substitute white defaults here so the model // never sees raw placeholder tokens. function bakeBg(s) { return s.replace(/\{\{BG_HEX\}\}/g, '#FFFFFF').replace(/\{\{BG_LABEL\}\}/g, 'white'); } const PROMPTS = [ { id: 'watercolor', name: 'Watercolor', prompt: bakeBg(extractConst('WATERCOLOR')) }, { id: 'lineart', name: 'Line Drawing', prompt: bakeBg(extractConst('LINEART')) }, { id: 'cubist', name: 'Cubist', prompt: extractConst('CUBIST') }, { id: 'ukiyoe', name: 'Ukiyo-e', prompt: extractConst('UKIYOE') }, { id: 'thangka', name: 'Thangka', prompt: extractConst('THANGKA') }, { id: 'mixedmedia', name: 'Mixed-Media', prompt: extractConst('MIXEDMEDIA') }, { id: 'charcoal', name: 'Charcoal', prompt: bakeBg(extractConst('CHARCOAL')) }, { id: 'vector', name: 'Vector Outline', prompt: bakeBg(extractConst('VECTOR')) }, { id: 'popart', name: 'Pop Art', prompt: extractConst('POPART') }, { id: 'risograph', name: 'Risograph', prompt: extractConst('RISOGRAPH') }, { id: 'athome', name: 'At Home', prompt: extractConst('ATHOME') }, { id: 'neoexpressionist', name: 'Neo-Expressionist', prompt: extractConst('NEOEXPRESSIONIST') }, { id: 'landscape-oil', name: 'Landscape Oil', prompt: extractConst('LANDSCAPE_OIL') }, { id: 'named', name: 'Named Portrait', prompt: bakeBg(extractConst('NAMED').replace(/\{\{NAME\}\}/g, NAME)) }, ]; // ─── Reference (loaded once) ──────────────────────────────────────── fs.mkdirSync(OUT_DIR, { recursive: true }); const refBytes = fs.readFileSync(REFERENCE); const refMime = REFERENCE.endsWith('.png') ? 'image/png' : 'image/jpeg'; const refBlob = new Blob([refBytes], { type: refMime }); const refName = path.basename(REFERENCE); const refB64 = refBytes.toString('base64'); // ─── OpenAI path ──────────────────────────────────────────────────── async function renderViaOpenAI({ id, name, prompt, model }, outPath) { if (!OPENAI_KEY) throw new Error('OPENAI_API_KEY not set'); const form = new FormData(); form.set('model', model); form.set('prompt', prompt); form.set('size', SIZE); form.set('n', '1'); // gpt-image-2 doesn't accept background: 'transparent'. Transparency // for TRANSPARENT_BG_STYLES is produced by post-processing through // rembg — see stripBackground() below. form.append('image', refBlob, refName); const r = await fetch('https://api.openai.com/v1/images/edits', { method: 'POST', headers: { Authorization: `Bearer ${OPENAI_KEY}` }, body: form, }); if (!r.ok) { const text = await r.text(); throw new Error(`${r.status} ${r.statusText}: ${text.slice(0, 400)}`); } const json = await r.json(); const b64 = json?.data?.[0]?.b64_json; if (!b64) throw new Error('No image data in OpenAI response'); fs.writeFileSync(outPath, Buffer.from(b64, 'base64')); } // ─── Gemini path (Nano Banana) ────────────────────────────────────── async function renderViaGemini({ name, prompt, model }, outPath) { if (!GEMINI_KEY) throw new Error('GEMINI_API_KEY not set'); const body = { contents: [ { parts: [ { text: prompt }, { inline_data: { mime_type: refMime, data: refB64 } }, ], }, ], generationConfig: { responseModalities: ['image', 'text'], imageConfig: { imageSize: GEMINI_IMAGE_SIZE }, }, }; const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`; const r = await fetch(url, { method: 'POST', headers: { 'x-goog-api-key': GEMINI_KEY, 'content-type': 'application/json', }, body: JSON.stringify(body), }); if (!r.ok) { const text = await r.text(); throw new Error(`${r.status} ${r.statusText}: ${text.slice(0, 400)}`); } const json = await r.json(); // Gemini returns parts; image data lives in part.inline_data.data // (or inlineData.data depending on API version). Walk both forms. const parts = json?.candidates?.[0]?.content?.parts ?? []; let b64 = null; for (const part of parts) { const data = part?.inline_data?.data ?? part?.inlineData?.data; if (data) { b64 = data; break; } } if (!b64) throw new Error('No image data in Gemini response'); fs.writeFileSync(outPath, Buffer.from(b64, 'base64')); } // ─── Output filename ──────────────────────────────────────────────── // PET=fox → after-fox-{id}.png (the canonical per-pet name used by the // style catalog). No PET → falls back to the legacy `${id}.png` form // used for the catalog tile examples in OUT_DIR. function outPathFor(id) { const base = PET ? `after-${PET}-${id}` : id; return path.join(OUT_DIR, `${base}.png`); } // ─── Post-process: alpha halo cleanup ─────────────────────────────── // rembg leaves a 1-2 pixel ring of low-alpha pixels around the subject // boundary whose RGB carries the original pigment colour. When composited // over a different ground colour at preview time, that ring shows as a // gray-brown halo around the silhouette. clean-alpha.mjs floors any // alpha < 80 to zero and erodes the mask by 1px — keeps the subject's // intended soft edge but kills the noise ring. function cleanAlpha(filePath) { return new Promise((resolve, reject) => { const proc = spawn('node', [path.join(ROOT, 'scripts/clean-alpha.mjs'), filePath], { stdio: ['ignore', 'pipe', 'pipe'], }); let err = ''; proc.stderr.on('data', (d) => (err += d.toString())); proc.on('close', (code) => { if (code === 0) resolve(); else reject(new Error(`clean-alpha exited ${code}: ${err.slice(0, 400)}`)); }); }); } // ─── Post-process: background removal via rembg ───────────────────── // rembg is a Python CLI installed via pipx — see MEMORY.md for setup // notes. Replaces the image in place with a true-alpha RGBA PNG so the // customer-chosen ground colour can show through at preview/print. function stripBackground(filePath) { return new Promise((resolve, reject) => { if (!fs.existsSync(REMBG)) { return reject(new Error(`rembg binary not found at ${REMBG}. Set REMBG_BIN or pipx install rembg.`)); } // rembg truncates the input file before reading when input==output, // so write to a sibling tmp and atomically rename when done. const tmpPath = filePath + '.rembg.tmp.png'; const proc = spawn(REMBG, ['i', '-m', REMBG_MODEL, filePath, tmpPath], { stdio: ['ignore', 'pipe', 'pipe'], }); let err = ''; proc.stderr.on('data', (d) => (err += d.toString())); proc.on('close', (code) => { if (code === 0 && fs.existsSync(tmpPath)) { fs.renameSync(tmpPath, filePath); resolve(); } else { try { fs.unlinkSync(tmpPath); } catch {} reject(new Error(`rembg exited ${code}: ${err.slice(0, 400)}`)); } }); }); } // ─── Dispatcher ───────────────────────────────────────────────────── async function renderStyle({ id, name, prompt }) { const model = modelFor(id); const outPath = outPathFor(id); const tag = model.startsWith('gemini') ? 'gemini' : 'openai'; const needsAlpha = TRANSPARENT_BG_STYLES.has(id); console.log(`\n→ ${name.padEnd(16)} (${id}, ${tag} · ${model}${needsAlpha ? ' + rembg' : ''})`); if (model.startsWith('gemini')) { await renderViaGemini({ name, prompt, model }, outPath); } else { await renderViaOpenAI({ id, name, prompt, model }, outPath); } console.log(` saved ${path.relative(ROOT, outPath)}`); if (needsAlpha && !process.env.SKIP_REMBG) { console.log(` stripping background (${REMBG_MODEL})…`); await stripBackground(outPath); console.log(` ✓ transparent PNG`); console.log(` cleaning alpha halo…`); await cleanAlpha(outPath); console.log(` ✓ halo cleaned`); } else if (needsAlpha) { console.log(` SKIP_REMBG set — leaving opaque-white background intact`); } } // ─── Run ──────────────────────────────────────────────────────────── const targets = ONLY ? PROMPTS.filter((p) => ONLY.has(p.id)) : PROMPTS; console.log(`Reference: ${path.relative(ROOT, REFERENCE)}`); console.log(`Size: ${SIZE} (OpenAI only)`); console.log(`Out: ${path.relative(ROOT, OUT_DIR)}`); console.log(`Pet: ${PET || '(none — using legacy ${id}.png filename)'}`); console.log(`Styles: ${targets.map((t) => `${t.id}→${modelFor(t.id).startsWith('gemini') ? 'gemini' : 'openai'}`).join(', ')}`); for (const t of targets) { try { await renderStyle(t); } catch (err) { console.error(` ✗ ${t.id}: ${err.message}`); } } console.log('\nDone.');