Lumen & Gesso / website · lumengesso.com / scripts / generate-charlie-named.mjs
| 1 | #!/usr/bin/env node |
| 2 | // One-off: a fresh "Modern Portrait (named)" catalog example — Charlie, |
| 3 | // a Golden Retriever. The named variant's existing tiles read a little |
| 4 | // flat, so this renders a richer painterly bust via Nano Banana Pro. |
| 5 | // |
| 6 | // Step 1 before-charlie.jpg — candid "phone snap" reference (t2i) |
| 7 | // Step 2 after-charlie-named.png — Charlie painted via the canonical |
| 8 | // NAMED prompt on flat white (i2i) |
| 9 | // Step 3 rembg + clean-alpha — strip the white to a true-alpha PNG |
| 10 | // with the soft painterly edge the |
| 11 | // named style composites over a colour |
| 12 | // |
| 13 | // The NAMED prompt is read live from app/data/portraitPrompts.ts so the |
| 14 | // example always tracks the real style definition. Mirrors the transparent |
| 15 | // pipeline in generate-style-examples.mjs (same rembg model + clean-alpha). |
| 16 | // |
| 17 | // Usage: GEMINI_API_KEY in .env.local (auto-loaded), then: |
| 18 | // node scripts/generate-charlie-named.mjs |
| 19 | |
| 20 | import fs from 'node:fs'; |
| 21 | import path from 'node:path'; |
| 22 | import { fileURLToPath } from 'node:url'; |
| 23 | import { spawn } from 'node:child_process'; |
| 24 | |
| 25 | const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 26 | const ROOT = path.resolve(__dirname, '..'); |
| 27 | |
| 28 | function loadEnvLocal() { |
| 29 | const p = path.join(ROOT, '.env.local'); |
| 30 | if (!fs.existsSync(p)) return; |
| 31 | for (const raw of fs.readFileSync(p, 'utf8').split('\n')) { |
| 32 | const line = raw.trim(); |
| 33 | if (!line || line.startsWith('#')) continue; |
| 34 | const eq = line.indexOf('='); |
| 35 | if (eq < 0) continue; |
| 36 | const key = line.slice(0, eq).trim(); |
| 37 | let val = line.slice(eq + 1).trim(); |
| 38 | if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { |
| 39 | val = val.slice(1, -1); |
| 40 | } |
| 41 | if (!(key in process.env)) process.env[key] = val; |
| 42 | } |
| 43 | } |
| 44 | loadEnvLocal(); |
| 45 | |
| 46 | const GEMINI_KEY = process.env.GEMINI_API_KEY; |
| 47 | if (!GEMINI_KEY) { |
| 48 | console.error('GEMINI_API_KEY not set (looked in env + .env.local)'); |
| 49 | process.exit(1); |
| 50 | } |
| 51 | |
| 52 | const MODEL = 'gemini-3-pro-image'; |
| 53 | const REMBG = process.env.REMBG_BIN || path.join(process.env.HOME || '', '.local/bin/rembg'); |
| 54 | const REMBG_MODEL = process.env.REMBG_MODEL || 'isnet-general-use'; |
| 55 | const PORTRAITS = path.resolve(ROOT, 'public/portraits'); |
| 56 | const BEFORE_PATH = path.join(PORTRAITS, 'before-charlie.jpg'); |
| 57 | const AFTER_PATH = path.join(PORTRAITS, 'after-charlie-named.png'); |
| 58 | |
| 59 | const BEFORE_PROMPT = |
| 60 | `A natural, candid pet photograph — the kind a customer would casually snap with their phone. ` + |
| 61 | `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. ` + |
| 62 | `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. ` + |
| 63 | `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. ` + |
| 64 | `Aspect ratio: square (1:1).`; |
| 65 | |
| 66 | function extractConst(name) { |
| 67 | const ts = fs.readFileSync(path.join(ROOT, 'app/data/portraitPrompts.ts'), 'utf8'); |
| 68 | const m = ts.match(new RegExp('const ' + name + ' = `([\\s\\S]*?)`;', 'm')); |
| 69 | if (!m) throw new Error('Could not find prompt const: ' + name); |
| 70 | return m[1]; |
| 71 | } |
| 72 | |
| 73 | function pickImageB64(json) { |
| 74 | const parts = json?.candidates?.[0]?.content?.parts ?? []; |
| 75 | for (const part of parts) { |
| 76 | const data = part?.inline_data?.data ?? part?.inlineData?.data; |
| 77 | if (data) return data; |
| 78 | } |
| 79 | return null; |
| 80 | } |
| 81 | |
| 82 | async function gemini(parts, label) { |
| 83 | const body = { contents: [{ parts }], generationConfig: { responseModalities: ['image', 'text'] } }; |
| 84 | const url = `https://generativelanguage.googleapis.com/v1beta/models/${MODEL}:generateContent`; |
| 85 | console.log(`→ ${label} (${MODEL})`); |
| 86 | const r = await fetch(url, { |
| 87 | method: 'POST', |
| 88 | headers: { 'x-goog-api-key': GEMINI_KEY, 'content-type': 'application/json' }, |
| 89 | body: JSON.stringify(body), |
| 90 | }); |
| 91 | if (!r.ok) throw new Error(`${r.status} ${r.statusText}: ${(await r.text()).slice(0, 600)}`); |
| 92 | const b64 = pickImageB64(await r.json()); |
| 93 | if (!b64) throw new Error('No image data in Gemini response'); |
| 94 | return Buffer.from(b64, 'base64'); |
| 95 | } |
| 96 | |
| 97 | const mimeOf = (buf) => (buf[0] === 0x89 && buf[1] === 0x50 ? 'image/png' : 'image/jpeg'); |
| 98 | |
| 99 | function run(cmd, args, label) { |
| 100 | return new Promise((resolve, reject) => { |
| 101 | console.log(` · ${label}`); |
| 102 | const proc = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] }); |
| 103 | let err = ''; |
| 104 | proc.stderr.on('data', (d) => (err += d.toString())); |
| 105 | proc.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`${label} exited ${code}: ${err.slice(0, 400)}`)))); |
| 106 | }); |
| 107 | } |
| 108 | |
| 109 | // ─── Step 1: reference photo ──────────────────────────────────────── |
| 110 | const beforeBuf = await gemini([{ text: BEFORE_PROMPT }], 'before-charlie.jpg — candid Golden Retriever reference'); |
| 111 | fs.writeFileSync(BEFORE_PATH, beforeBuf); |
| 112 | console.log(` ✓ ${path.relative(ROOT, BEFORE_PATH)} (${beforeBuf.length.toLocaleString()} bytes)`); |
| 113 | |
| 114 | // ─── Step 2: painted portrait on flat white ───────────────────────── |
| 115 | // NAMED now carries {{BG_HEX}}/{{BG_LABEL}} placeholders that the live |
| 116 | // admin route fills with the customer's chosen colour. Here we bake |
| 117 | // white so the next step (rembg) can strip cleanly to true-alpha. |
| 118 | const NAMED = extractConst('NAMED') |
| 119 | .replace(/\{\{NAME\}\}/g, 'Charlie') |
| 120 | .replace(/\{\{BG_HEX\}\}/g, '#FFFFFF') |
| 121 | .replace(/\{\{BG_LABEL\}\}/g, 'white'); |
| 122 | const afterBuf = await gemini( |
| 123 | [{ text: NAMED }, { inline_data: { mime_type: mimeOf(beforeBuf), data: beforeBuf.toString('base64') } }], |
| 124 | 'after-charlie-named.png — Modern Portrait (named) render on white', |
| 125 | ); |
| 126 | fs.writeFileSync(AFTER_PATH, afterBuf); |
| 127 | console.log(` ✓ ${path.relative(ROOT, AFTER_PATH)} (${afterBuf.length.toLocaleString()} bytes)`); |
| 128 | |
| 129 | // ─── Step 3: strip white → true-alpha + clean the halo ────────────── |
| 130 | if (!fs.existsSync(REMBG)) throw new Error(`rembg not found at ${REMBG} (set REMBG_BIN)`); |
| 131 | const tmp = AFTER_PATH + '.rembg.tmp.png'; |
| 132 | await run(REMBG, ['i', '-m', REMBG_MODEL, AFTER_PATH, tmp], `rembg (${REMBG_MODEL})`); |
| 133 | fs.renameSync(tmp, AFTER_PATH); |
| 134 | await run('node', [path.join(ROOT, 'scripts/clean-alpha.mjs'), AFTER_PATH], 'clean-alpha (halo cleanup)'); |
| 135 | console.log(` ✓ transparent PNG ready`); |
| 136 | |
| 137 | console.log('\nDone.'); |