Branchwell

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
20import fs from 'node:fs';
21import path from 'node:path';
22import { fileURLToPath } from 'node:url';
23import { spawn } from 'node:child_process';
24
25const __dirname = path.dirname(fileURLToPath(import.meta.url));
26const ROOT = path.resolve(__dirname, '..');
27
28function 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}
44loadEnvLocal();
45
46const GEMINI_KEY = process.env.GEMINI_API_KEY;
47if (!GEMINI_KEY) {
48 console.error('GEMINI_API_KEY not set (looked in env + .env.local)');
49 process.exit(1);
50}
51
52const MODEL = 'gemini-3-pro-image';
53const REMBG = process.env.REMBG_BIN || path.join(process.env.HOME || '', '.local/bin/rembg');
54const REMBG_MODEL = process.env.REMBG_MODEL || 'isnet-general-use';
55const PORTRAITS = path.resolve(ROOT, 'public/portraits');
56const BEFORE_PATH = path.join(PORTRAITS, 'before-charlie.jpg');
57const AFTER_PATH = path.join(PORTRAITS, 'after-charlie-named.png');
58
59const 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
66function 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
73function 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
82async 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
97const mimeOf = (buf) => (buf[0] === 0x89 && buf[1] === 0x50 ? 'image/png' : 'image/jpeg');
98
99function 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 ────────────────────────────────────────
110const beforeBuf = await gemini([{ text: BEFORE_PROMPT }], 'before-charlie.jpg — candid Golden Retriever reference');
111fs.writeFileSync(BEFORE_PATH, beforeBuf);
112console.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.
118const NAMED = extractConst('NAMED')
119 .replace(/\{\{NAME\}\}/g, 'Charlie')
120 .replace(/\{\{BG_HEX\}\}/g, '#FFFFFF')
121 .replace(/\{\{BG_LABEL\}\}/g, 'white');
122const 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);
126fs.writeFileSync(AFTER_PATH, afterBuf);
127console.log(` ✓ ${path.relative(ROOT, AFTER_PATH)} (${afterBuf.length.toLocaleString()} bytes)`);
128
129// ─── Step 3: strip white → true-alpha + clean the halo ──────────────
130if (!fs.existsSync(REMBG)) throw new Error(`rembg not found at ${REMBG} (set REMBG_BIN)`);
131const tmp = AFTER_PATH + '.rembg.tmp.png';
132await run(REMBG, ['i', '-m', REMBG_MODEL, AFTER_PATH, tmp], `rembg (${REMBG_MODEL})`);
133fs.renameSync(tmp, AFTER_PATH);
134await run('node', [path.join(ROOT, 'scripts/clean-alpha.mjs'), AFTER_PATH], 'clean-alpha (halo cleanup)');
135console.log(` ✓ transparent PNG ready`);
136
137console.log('\nDone.');