#!/usr/bin/env node // One-off: the "Vector (named)" catalog example — Mango, a scarlet macaw. // v3: earlier passes were too flat / lost detail in the cutout / had // ragged transparent edges. This pass: // - uses the detailed VECTOR prompt, now requiring a bold continuous // BLACK KEYLINE fully enclosing the silhouette → a clean, intentional // transparent edge instead of a ragged/haloed one // - renders the surround as a CONTRASTING mid-grey (not white) so rembg // keeps the bird's white/light areas intact // - reuses the existing before-mango.jpg reference (regen if missing) // - writes a NEW filename (after-mango-vector-v3.png) so Next's image // optimizer doesn't serve a stale cache of the old asset // - also drops a *.preview.png (final composited over dark slate) so the // transparent result can be eyeballed for any detail loss // // VECTOR + COMPOSITION_TIGHT are read live from portraitPrompts.ts (the // ${COMPOSITION_TIGHT} reference is resolved here, which the bulk regen // script does not do). // // Usage: GEMINI_API_KEY in .env.local (auto-loaded), then: // node scripts/generate-mango-vector.mjs import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { spawn } from 'node:child_process'; import sharp from 'sharp'; 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-mango.jpg'); const RAW_PATH = path.join(PORTRAITS, 'after-mango-vector-v3.raw.png'); // on-grey render, kept for diffing const AFTER_PATH = path.join(PORTRAITS, 'after-mango-vector-v3.png'); // final true-alpha asset const PREVIEW_PATH = path.join(PORTRAITS, 'after-mango-vector-v3.preview.png'); // final over dark slate // Contrasting surround so rembg separates the bird (incl. its white face) // from the ground without eating light areas. rembg strips it regardless. const SURROUND = '#8C9298'; const BEFORE_PROMPT = `A natural, candid pet photograph — the kind a customer would casually snap with their phone. ` + `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. ` + `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. ` + `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 (reuse if present) ───────────────────── let beforeBuf; if (fs.existsSync(BEFORE_PATH)) { beforeBuf = fs.readFileSync(BEFORE_PATH); console.log(`· reusing ${path.relative(ROOT, BEFORE_PATH)} (${beforeBuf.length.toLocaleString()} bytes)`); } else { beforeBuf = await gemini([{ text: BEFORE_PROMPT }], 'before-mango.jpg — candid scarlet-macaw reference'); fs.writeFileSync(BEFORE_PATH, beforeBuf); console.log(` ✓ ${path.relative(ROOT, BEFORE_PATH)}`); } // ─── Step 2: detailed flat-vector render on a contrasting ground ──── // VECTOR now carries {{BG_HEX}}/{{BG_LABEL}} placeholders that the live // admin route substitutes with the customer's chosen colour. Here we // substitute a mid-grey instead so rembg cleanly separates the bird // (including its WHITE facial skin and any pale feather edges) — using // pure white as the surround would let rembg eat those light areas. const VECTOR = extractConst('VECTOR') .replace('${COMPOSITION_TIGHT}', extractConst('COMPOSITION_TIGHT')) .replace(/\{\{BG_HEX\}\}/g, SURROUND) .replace(/\{\{BG_LABEL\}\}/g, 'medium neutral grey'); const afterBuf = await gemini( [{ text: VECTOR }, { inline_data: { mime_type: mimeOf(beforeBuf), data: beforeBuf.toString('base64') } }], 'after-mango-vector-v3 — detailed flat Vector on grey', ); fs.writeFileSync(RAW_PATH, afterBuf); fs.writeFileSync(AFTER_PATH, afterBuf); console.log(` ✓ ${path.relative(ROOT, RAW_PATH)} (raw on-grey render kept for diffing)`); // ─── Step 3: strip ground → 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)'); // ─── Step 4: preview composite (final over dark slate) for eyeballing ─ await sharp(AFTER_PATH).flatten({ background: '#2a3a44' }).png().toFile(PREVIEW_PATH); console.log(` ✓ ${path.relative(ROOT, AFTER_PATH)} + preview composite`); console.log('\nDone.');