Lumen & Gesso / website / scripts / generate-mango-vector.mjs
| 1 | #!/usr/bin/env node |
| 2 | // One-off: the "Vector (named)" catalog example — Mango, a scarlet macaw. |
| 3 | // v3: earlier passes were too flat / lost detail in the cutout / had |
| 4 | // ragged transparent edges. This pass: |
| 5 | // - uses the detailed VECTOR prompt, now requiring a bold continuous |
| 6 | // BLACK KEYLINE fully enclosing the silhouette → a clean, intentional |
| 7 | // transparent edge instead of a ragged/haloed one |
| 8 | // - renders the surround as a CONTRASTING mid-grey (not white) so rembg |
| 9 | // keeps the bird's white/light areas intact |
| 10 | // - reuses the existing before-mango.jpg reference (regen if missing) |
| 11 | // - writes a NEW filename (after-mango-vector-v3.png) so Next's image |
| 12 | // optimizer doesn't serve a stale cache of the old asset |
| 13 | // - also drops a *.preview.png (final composited over dark slate) so the |
| 14 | // transparent result can be eyeballed for any detail loss |
| 15 | // |
| 16 | // VECTOR + COMPOSITION_TIGHT are read live from portraitPrompts.ts (the |
| 17 | // ${COMPOSITION_TIGHT} reference is resolved here, which the bulk regen |
| 18 | // script does not do). |
| 19 | // |
| 20 | // Usage: GEMINI_API_KEY in .env.local (auto-loaded), then: |
| 21 | // node scripts/generate-mango-vector.mjs |
| 22 | |
| 23 | import fs from 'node:fs'; |
| 24 | import path from 'node:path'; |
| 25 | import { fileURLToPath } from 'node:url'; |
| 26 | import { spawn } from 'node:child_process'; |
| 27 | import sharp from 'sharp'; |
| 28 | |
| 29 | const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 30 | const ROOT = path.resolve(__dirname, '..'); |
| 31 | |
| 32 | function loadEnvLocal() { |
| 33 | const p = path.join(ROOT, '.env.local'); |
| 34 | if (!fs.existsSync(p)) return; |
| 35 | for (const raw of fs.readFileSync(p, 'utf8').split('\n')) { |
| 36 | const line = raw.trim(); |
| 37 | if (!line || line.startsWith('#')) continue; |
| 38 | const eq = line.indexOf('='); |
| 39 | if (eq < 0) continue; |
| 40 | const key = line.slice(0, eq).trim(); |
| 41 | let val = line.slice(eq + 1).trim(); |
| 42 | if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { |
| 43 | val = val.slice(1, -1); |
| 44 | } |
| 45 | if (!(key in process.env)) process.env[key] = val; |
| 46 | } |
| 47 | } |
| 48 | loadEnvLocal(); |
| 49 | |
| 50 | const GEMINI_KEY = process.env.GEMINI_API_KEY; |
| 51 | if (!GEMINI_KEY) { |
| 52 | console.error('GEMINI_API_KEY not set (looked in env + .env.local)'); |
| 53 | process.exit(1); |
| 54 | } |
| 55 | |
| 56 | const MODEL = 'gemini-3-pro-image'; |
| 57 | const REMBG = process.env.REMBG_BIN || path.join(process.env.HOME || '', '.local/bin/rembg'); |
| 58 | const REMBG_MODEL = process.env.REMBG_MODEL || 'isnet-general-use'; |
| 59 | const PORTRAITS = path.resolve(ROOT, 'public/portraits'); |
| 60 | const BEFORE_PATH = path.join(PORTRAITS, 'before-mango.jpg'); |
| 61 | const RAW_PATH = path.join(PORTRAITS, 'after-mango-vector-v3.raw.png'); // on-grey render, kept for diffing |
| 62 | const AFTER_PATH = path.join(PORTRAITS, 'after-mango-vector-v3.png'); // final true-alpha asset |
| 63 | const PREVIEW_PATH = path.join(PORTRAITS, 'after-mango-vector-v3.preview.png'); // final over dark slate |
| 64 | |
| 65 | // Contrasting surround so rembg separates the bird (incl. its white face) |
| 66 | // from the ground without eating light areas. rembg strips it regardless. |
| 67 | const SURROUND = '#8C9298'; |
| 68 | |
| 69 | const BEFORE_PROMPT = |
| 70 | `A natural, candid pet photograph — the kind a customer would casually snap with their phone. ` + |
| 71 | `Composition: head-and-shoulders / bust crop, the subject occupying roughly the centre 60-75% of a square frame with comfortable margin on all four sides. ` + |
| 72 | `Subject: a scarlet macaw parrot perched calmly, vivid red head and chest, bright blue and golden-yellow wing feathers, pale white facial skin with fine dark lines, a large curved black-and-bone beak, one bright eye looking toward the camera, soft natural daylight, blurred green foliage out of focus behind. ` + |
| 73 | `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. ` + |
| 74 | `Aspect ratio: square (1:1).`; |
| 75 | |
| 76 | function extractConst(name) { |
| 77 | const ts = fs.readFileSync(path.join(ROOT, 'app/data/portraitPrompts.ts'), 'utf8'); |
| 78 | const m = ts.match(new RegExp('const ' + name + ' = `([\\s\\S]*?)`;', 'm')); |
| 79 | if (!m) throw new Error('Could not find prompt const: ' + name); |
| 80 | return m[1]; |
| 81 | } |
| 82 | |
| 83 | function pickImageB64(json) { |
| 84 | const parts = json?.candidates?.[0]?.content?.parts ?? []; |
| 85 | for (const part of parts) { |
| 86 | const data = part?.inline_data?.data ?? part?.inlineData?.data; |
| 87 | if (data) return data; |
| 88 | } |
| 89 | return null; |
| 90 | } |
| 91 | |
| 92 | async function gemini(parts, label) { |
| 93 | const body = { contents: [{ parts }], generationConfig: { responseModalities: ['image', 'text'] } }; |
| 94 | const url = `https://generativelanguage.googleapis.com/v1beta/models/${MODEL}:generateContent`; |
| 95 | console.log(`→ ${label} (${MODEL})`); |
| 96 | const r = await fetch(url, { |
| 97 | method: 'POST', |
| 98 | headers: { 'x-goog-api-key': GEMINI_KEY, 'content-type': 'application/json' }, |
| 99 | body: JSON.stringify(body), |
| 100 | }); |
| 101 | if (!r.ok) throw new Error(`${r.status} ${r.statusText}: ${(await r.text()).slice(0, 600)}`); |
| 102 | const b64 = pickImageB64(await r.json()); |
| 103 | if (!b64) throw new Error('No image data in Gemini response'); |
| 104 | return Buffer.from(b64, 'base64'); |
| 105 | } |
| 106 | |
| 107 | const mimeOf = (buf) => (buf[0] === 0x89 && buf[1] === 0x50 ? 'image/png' : 'image/jpeg'); |
| 108 | |
| 109 | function run(cmd, args, label) { |
| 110 | return new Promise((resolve, reject) => { |
| 111 | console.log(` · ${label}`); |
| 112 | const proc = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] }); |
| 113 | let err = ''; |
| 114 | proc.stderr.on('data', (d) => (err += d.toString())); |
| 115 | proc.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`${label} exited ${code}: ${err.slice(0, 400)}`)))); |
| 116 | }); |
| 117 | } |
| 118 | |
| 119 | // ─── Step 1: reference photo (reuse if present) ───────────────────── |
| 120 | let beforeBuf; |
| 121 | if (fs.existsSync(BEFORE_PATH)) { |
| 122 | beforeBuf = fs.readFileSync(BEFORE_PATH); |
| 123 | console.log(`· reusing ${path.relative(ROOT, BEFORE_PATH)} (${beforeBuf.length.toLocaleString()} bytes)`); |
| 124 | } else { |
| 125 | beforeBuf = await gemini([{ text: BEFORE_PROMPT }], 'before-mango.jpg — candid scarlet-macaw reference'); |
| 126 | fs.writeFileSync(BEFORE_PATH, beforeBuf); |
| 127 | console.log(` ✓ ${path.relative(ROOT, BEFORE_PATH)}`); |
| 128 | } |
| 129 | |
| 130 | // ─── Step 2: detailed flat-vector render on a contrasting ground ──── |
| 131 | // VECTOR now carries {{BG_HEX}}/{{BG_LABEL}} placeholders that the live |
| 132 | // admin route substitutes with the customer's chosen colour. Here we |
| 133 | // substitute a mid-grey instead so rembg cleanly separates the bird |
| 134 | // (including its WHITE facial skin and any pale feather edges) — using |
| 135 | // pure white as the surround would let rembg eat those light areas. |
| 136 | const VECTOR = extractConst('VECTOR') |
| 137 | .replace('${COMPOSITION_TIGHT}', extractConst('COMPOSITION_TIGHT')) |
| 138 | .replace(/\{\{BG_HEX\}\}/g, SURROUND) |
| 139 | .replace(/\{\{BG_LABEL\}\}/g, 'medium neutral grey'); |
| 140 | const afterBuf = await gemini( |
| 141 | [{ text: VECTOR }, { inline_data: { mime_type: mimeOf(beforeBuf), data: beforeBuf.toString('base64') } }], |
| 142 | 'after-mango-vector-v3 — detailed flat Vector on grey', |
| 143 | ); |
| 144 | fs.writeFileSync(RAW_PATH, afterBuf); |
| 145 | fs.writeFileSync(AFTER_PATH, afterBuf); |
| 146 | console.log(` ✓ ${path.relative(ROOT, RAW_PATH)} (raw on-grey render kept for diffing)`); |
| 147 | |
| 148 | // ─── Step 3: strip ground → true-alpha + clean the halo ───────────── |
| 149 | if (!fs.existsSync(REMBG)) throw new Error(`rembg not found at ${REMBG} (set REMBG_BIN)`); |
| 150 | const tmp = AFTER_PATH + '.rembg.tmp.png'; |
| 151 | await run(REMBG, ['i', '-m', REMBG_MODEL, AFTER_PATH, tmp], `rembg (${REMBG_MODEL})`); |
| 152 | fs.renameSync(tmp, AFTER_PATH); |
| 153 | await run('node', [path.join(ROOT, 'scripts/clean-alpha.mjs'), AFTER_PATH], 'clean-alpha (halo cleanup)'); |
| 154 | |
| 155 | // ─── Step 4: preview composite (final over dark slate) for eyeballing ─ |
| 156 | await sharp(AFTER_PATH).flatten({ background: '#2a3a44' }).png().toFile(PREVIEW_PATH); |
| 157 | console.log(` ✓ ${path.relative(ROOT, AFTER_PATH)} + preview composite`); |
| 158 | |
| 159 | console.log('\nDone.'); |