#!/usr/bin/env node // One-off: a fresh "Modern Portrait (named)" catalog example — Charlie, // a Golden Retriever. The named variant's existing tiles read a little // flat, so this renders a richer painterly bust via Nano Banana Pro. // // Step 1 before-charlie.jpg — candid "phone snap" reference (t2i) // Step 2 after-charlie-named.png — Charlie painted via the canonical // NAMED prompt on flat white (i2i) // Step 3 rembg + clean-alpha — strip the white to a true-alpha PNG // with the soft painterly edge the // named style composites over a colour // // The NAMED prompt is read live from app/data/portraitPrompts.ts so the // example always tracks the real style definition. Mirrors the transparent // pipeline in generate-style-examples.mjs (same rembg model + clean-alpha). // // Usage: GEMINI_API_KEY in .env.local (auto-loaded), then: // node scripts/generate-charlie-named.mjs 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, '..'); function loadEnvLocal() { const p = path.join(ROOT, '.env.local'); if (!fs.existsSync(p)) return; for (const raw of fs.readFileSync(p, 'utf8').split('\n')) { const line = raw.trim(); if (!line || line.startsWith('#')) continue; const eq = line.indexOf('='); if (eq < 0) continue; const key = line.slice(0, eq).trim(); let val = line.slice(eq + 1).trim(); if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { val = val.slice(1, -1); } if (!(key in process.env)) process.env[key] = val; } } loadEnvLocal(); const GEMINI_KEY = process.env.GEMINI_API_KEY; if (!GEMINI_KEY) { console.error('GEMINI_API_KEY not set (looked in env + .env.local)'); process.exit(1); } const MODEL = 'gemini-3-pro-image'; const REMBG = process.env.REMBG_BIN || path.join(process.env.HOME || '', '.local/bin/rembg'); const REMBG_MODEL = process.env.REMBG_MODEL || 'isnet-general-use'; const PORTRAITS = path.resolve(ROOT, 'public/portraits'); const BEFORE_PATH = path.join(PORTRAITS, 'before-charlie.jpg'); const AFTER_PATH = path.join(PORTRAITS, 'after-charlie-named.png'); const BEFORE_PROMPT = `A natural, candid pet photograph — the kind a customer would casually snap with their phone. ` + `Composition: head-and-shoulders to bust crop, the subject occupying roughly the centre 60-75% of a square frame with comfortable margin on all four sides. ` + `Subject: a Golden Retriever dog sitting indoors near a bright window, warm golden coat with soft feathering, gentle dark-brown eyes looking directly at the camera, friendly relaxed open expression, a little black nose, soft natural daylight, a cozy living room softly out of focus behind. ` + `Style: realistic photographic quality, soft natural light, narrow depth of field, slight grain, no text, no watermark, no studio lighting, no people, no other animals. ` + `Aspect ratio: square (1:1).`; function extractConst(name) { const ts = fs.readFileSync(path.join(ROOT, 'app/data/portraitPrompts.ts'), 'utf8'); const m = ts.match(new RegExp('const ' + name + ' = `([\\s\\S]*?)`;', 'm')); if (!m) throw new Error('Could not find prompt const: ' + name); return m[1]; } function pickImageB64(json) { const parts = json?.candidates?.[0]?.content?.parts ?? []; for (const part of parts) { const data = part?.inline_data?.data ?? part?.inlineData?.data; if (data) return data; } return null; } async function gemini(parts, label) { const body = { contents: [{ parts }], generationConfig: { responseModalities: ['image', 'text'] } }; const url = `https://generativelanguage.googleapis.com/v1beta/models/${MODEL}:generateContent`; console.log(`→ ${label} (${MODEL})`); 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) throw new Error(`${r.status} ${r.statusText}: ${(await r.text()).slice(0, 600)}`); const b64 = pickImageB64(await r.json()); if (!b64) throw new Error('No image data in Gemini response'); return Buffer.from(b64, 'base64'); } const mimeOf = (buf) => (buf[0] === 0x89 && buf[1] === 0x50 ? 'image/png' : 'image/jpeg'); function run(cmd, args, label) { return new Promise((resolve, reject) => { console.log(` · ${label}`); const proc = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] }); let err = ''; proc.stderr.on('data', (d) => (err += d.toString())); proc.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`${label} exited ${code}: ${err.slice(0, 400)}`)))); }); } // ─── Step 1: reference photo ──────────────────────────────────────── const beforeBuf = await gemini([{ text: BEFORE_PROMPT }], 'before-charlie.jpg — candid Golden Retriever reference'); fs.writeFileSync(BEFORE_PATH, beforeBuf); console.log(` ✓ ${path.relative(ROOT, BEFORE_PATH)} (${beforeBuf.length.toLocaleString()} bytes)`); // ─── Step 2: painted portrait on flat white ───────────────────────── // NAMED now carries {{BG_HEX}}/{{BG_LABEL}} placeholders that the live // admin route fills with the customer's chosen colour. Here we bake // white so the next step (rembg) can strip cleanly to true-alpha. const NAMED = extractConst('NAMED') .replace(/\{\{NAME\}\}/g, 'Charlie') .replace(/\{\{BG_HEX\}\}/g, '#FFFFFF') .replace(/\{\{BG_LABEL\}\}/g, 'white'); const afterBuf = await gemini( [{ text: NAMED }, { inline_data: { mime_type: mimeOf(beforeBuf), data: beforeBuf.toString('base64') } }], 'after-charlie-named.png — Modern Portrait (named) render on white', ); fs.writeFileSync(AFTER_PATH, afterBuf); console.log(` ✓ ${path.relative(ROOT, AFTER_PATH)} (${afterBuf.length.toLocaleString()} bytes)`); // ─── Step 3: strip white → true-alpha + clean the halo ────────────── if (!fs.existsSync(REMBG)) throw new Error(`rembg not found at ${REMBG} (set REMBG_BIN)`); const tmp = AFTER_PATH + '.rembg.tmp.png'; await run(REMBG, ['i', '-m', REMBG_MODEL, AFTER_PATH, tmp], `rembg (${REMBG_MODEL})`); fs.renameSync(tmp, AFTER_PATH); await run('node', [path.join(ROOT, 'scripts/clean-alpha.mjs'), AFTER_PATH], 'clean-alpha (halo cleanup)'); console.log(` ✓ transparent PNG ready`); console.log('\nDone.');