Branchwell

Lumen & Gesso / website · lumengesso.com / scripts / generate-new-styles-test.mjs

1#!/usr/bin/env node
2// Scratch generator for three new candidate styles — risograph, at-home,
3// neo-expressionist. Outputs to public/portraits/examples-test/ so we can
4// iterate the prompt text without touching the production catalog. Once
5// a prompt is locked, lift the constant into app/data/portraitPrompts.ts
6// and wire it through styleCatalog.ts + generate-style-examples.mjs.
7//
8// Usage:
9// OPENAI_API_KEY=… GEMINI_API_KEY=… node scripts/generate-new-styles-test.mjs
10//
11// Env:
12// REFERENCE path to reference photo (default: public/portraits/before-daisy.jpg)
13// OUT_DIR output dir under /public (default: portraits/examples-test)
14// ONLY comma-separated style ids to render (default: all three)
15// PET pet name slug for file naming (default: derived from REFERENCE)
16
17import fs from 'node:fs';
18import path from 'node:path';
19import { fileURLToPath } from 'node:url';
20
21const __dirname = path.dirname(fileURLToPath(import.meta.url));
22const ROOT = path.resolve(__dirname, '..');
23
24// Zero-dep .env.local loader — matches the production script's style.
25function loadEnvLocal() {
26 const p = path.join(ROOT, '.env.local');
27 if (!fs.existsSync(p)) return;
28 for (const raw of fs.readFileSync(p, 'utf8').split('\n')) {
29 const line = raw.trim();
30 if (!line || line.startsWith('#')) continue;
31 const eq = line.indexOf('=');
32 if (eq < 0) continue;
33 const key = line.slice(0, eq).trim();
34 let val = line.slice(eq + 1).trim();
35 if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
36 val = val.slice(1, -1);
37 }
38 if (!(key in process.env)) process.env[key] = val;
39 }
40}
41loadEnvLocal();
42
43const OPENAI_KEY = process.env.OPENAI_API_KEY;
44const GEMINI_KEY = process.env.GEMINI_API_KEY;
45const SIZE = process.env.SIZE || '1024x1024';
46const OUT_DIR = path.resolve(ROOT, 'public', process.env.OUT_DIR || 'portraits/examples-test');
47const ONLY = process.env.ONLY ? new Set(process.env.ONLY.split(',').map((s) => s.trim())) : null;
48
49// ─── Shared composition blocks ──────────────────────────────────────
50// Bust-style fill (the production default) — head upper-middle, body
51// fades off the bottom. Right for watercolor / cubist / thangka etc.
52const COMPOSITION_TIGHT = `Composition and framing — strict, this matters more than any other section:
53- FILL THE FULL CANVAS edge-to-edge. The artwork will be placed inside the customer's chosen frame (which may be square, portrait, or landscape), and any built-in padding inside the square becomes awkward empty mat space when the image is cropped into a non-square frame.
54- Position the pet's HEAD AND EYES in the upper-middle of the canvas — roughly 20–35% down from the top edge — with only a thin breathing room (about 3–6% of the canvas height) above the top of the head, ears, or hairline. NEVER leave large empty space above the face.
55- The pet's body should EXTEND NEARLY EDGE-TO-EDGE horizontally, with only thin margins (about 2–5%) on the left and right sides. Tight enough that the pet dominates the composition, but not so tight that ears, whiskers, or any feature gets cropped.
56- The pet's LOWER BODY, CHEST, and any flowing fur should naturally DISSOLVE or FADE toward the BOTTOM edge of the canvas — bust-style — and MAY run off the bottom edge if the pet has a long chest. This natural bottom-fade is the ONLY edge the artwork may touch.
57- NEVER crop or cut off any part of the pet's HEAD, EARS, EYES, MUZZLE, NOSE, or FACE — these features must always be fully visible inside the canvas. Only the lower body / chest may fade off the bottom.
58- DO NOT add a mat, vignette, soft halo, painted border, or built-in empty padding band around the pet beyond the thin breathing room specified above.`;
59
60// Standing hero — full-body standing pose, with crop-safe margin on ALL
61// FOUR EDGES so the dog stays whole when the square render is cropped
62// into portrait or landscape frame sizes. The painted BACKGROUND fills
63// the canvas; the dog sits inside a safe central zone.
64const COMPOSITION_STANDING = `Composition and framing — strict, this matters more than any other section:
65- The painted BACKGROUND fills the full canvas edge-to-edge. The artwork will be placed inside the customer's chosen frame (square, portrait, or landscape), and the painted ground / drips / iconography must wrap fully to all four canvas edges with no empty padding.
66- The PET, however, sits INSIDE a crop-safe central zone — the entire dog must be visible with comfortable margin on ALL FOUR SIDES so it stays whole when the square canvas is cropped to portrait or landscape aspect ratios.
67- The pet is in a STANDING HERO POSE — full body planted, all four legs visible (or three legs and a tucked one if the breed naturally stands that way), chest forward, head held high.
68- Position the pet's HEAD AND EARS at roughly 20–30% down from the top edge, with comfortable breathing room above the head / ears (about 10–15% of the canvas height) filled with the painted background and iconography (crown, M, etc.) — NEVER let the top of the head, ears, or crown touch the top edge.
69- Position the pet's PAWS at roughly 80–90% down from the top edge, with a clear floor margin BELOW the paws (about 10–15% of the canvas height) filled with painted background, drips, and a soft contact shadow — NEVER let any paw touch or run off the bottom edge.
70- The pet's body sits in the CENTRAL 50–70% of the width with at least 10–15% painted-background margin on the left AND right — NEVER let any part of the pet (tail, hip, ear, paw, snout) touch the left or right edge.
71- DO NOT crop or cut off ANY part of the pet's HEAD, EARS, EYES, MUZZLE, NOSE, FACE, BODY, LEGS, TAIL, or PAWS — the entire dog must be a complete, intact silhouette sitting inside the painted background field, surrounded on all four sides by the graffiti ground and icons.
72- DO NOT add a mat, frame, painted border, or built-in empty padding band — the painted background continues uniformly all the way to every edge; the safe margin around the dog is filled with painted background, not blank space.`;
73
74// ─── Prompt drafts ──────────────────────────────────────────────────
75
76const RISOGRAPH = `Create a risograph screen-print portrait of the pet (or pets) shown in the reference image(s) — the look of a hand-pulled small-press risograph print in 2-3 ink colours, FULL-BLEED across the entire canvas with NO internal frame, border, edge rule, mat, or paper margin of any kind.
77
78Canvas requirements:
79- 1:1 square aspect ratio (equal width and height)
80- The riso ink ground FILLS THE ENTIRE CANVAS edge-to-edge — top, bottom, left, and right edges are all covered by saturated risograph ink. There is NO cream / white / paper margin band around the artwork, NO thin inked edge rule, NO drawn rectangle, NO mat, NO frame, NO border of any kind inside the canvas. The print runs FULL BLEED.
81- Pick a single saturated ink-field hue for the main ground — bold and recognisably riso: deep teal, fluorescent magenta-pink, mustard yellow, persimmon orange, deep cobalt, soft mint, or sumi black. The ground is a flat saturated field of that ink with visible paper-grain texture and faint registration misalignment showing through
82- The full riso palette is a limited set of 2 or 3 inks — the main ground hue plus 1–2 supporting inks used in the pet, the geometric motif, and any halftone shading. The inks overlap in a few places to produce a third blended tone characteristic of the medium
83- Carry a single restrained GEOMETRIC PATTERN MOTIF behind the pet, anchored in one corner or quarter and RUNNING TO THE NEAREST TWO CANVAS EDGES (never confined inside a smaller drawn box) — pick ONE of: argyle / harlequin diamonds, spirograph rosette in fine linework, halftone dot field, simple checker, sparse stars, or a half-disc rising sun. The motif sits behind the pet, anchored to a corner, and bleeds off the two adjacent canvas edges — never floated as a contained shape with empty ground around it
84- The background must remain quiet enough that the pet still dominates: no scenery, no objects, no text, no signage, no extra figures, no decorative shapes other than the single corner motif
85
86Subject requirements:
87- If a single reference image is provided, render that one pet alone
88- If multiple reference images are provided, render all of the pets together in a single unified portrait, as if posed side by side for a small-press print
89- Match the scale of each pet realistically relative to the others
90- Preserve each pet's individual identity through the risograph idiom: breed silhouette, coat pattern, markings, eye colour, and distinctive features must match their respective reference photos exactly — translated into flat ink fields and halftone shading
91
92Pose requirements:
93- Portrait hero pose: each subject facing slightly off-center (roughly 3/4 view) with head held high and alert
94- Confident, characterful bearing — chest forward, ears perked, gaze directed forward or slightly upward
95- Composed, slightly playful expression, as if posed for an editioned art print
96- Head-and-shoulders or bust crop that emphasizes faces and upper bodies
97
98Style requirements (applied only to the pet, never to the background as scenery):
99- Risograph / soy-ink screen-print aesthetic — the look of a 2-3 colour limited-edition print pulled from a hand-cranked Riso duplicator
100- Reinterpret the pet's coat as flat overlapping fields of risograph ink, separated by clearly visible halftone-dot tonal layers — coarse, evenly-spaced dot patterns standing in for shading and fur depth, never airbrushed gradients
101- Slight registration offset on the colour separations — a 1–2px shift between the ink layers so the colours overhang the contour by a hair on one side and pull back on the other, the signature mis-registration of the medium
102- Bold dark contour outlines (sumi-black or the deepest ink in the chosen palette) defining the silhouette, the muzzle, the eyes, and the major fur masses; supplementary line work for whiskers, brow tufts, and ear hair
103- A pulled-paper feel across the whole print: faint paper fibre texture (showing through the saturated ink ground), the slightly chalky matte of riso ink sitting on uncoated stock, occasional ink streaks
104- Restrained palette pulled from the chosen 2–3 inks — never more — used in deliberate flat zones inside the contour. The pet's white or pale coat areas may carry one of the inks as a tinted wash rather than reading as pure white
105- The eyes and nose remain the most readable features — kept clear and characterful despite the limited palette
106
107${COMPOSITION_TIGHT}
108
109Background + surround — strict:
110- The saturated riso ink ground FILLS THE FULL CANVAS edge-to-edge; the geometric motif anchors a corner and bleeds off the two adjacent edges; the pet sits in front of the ground filling the central composition.
111- ABSOLUTELY NO inset rectangular edge rule, NO inked frame, NO drawn border, NO mat, NO paper-coloured margin band, NO contained boxed artwork inside the canvas. The print is full-bleed.
112- No scenery, objects, text, captions, signatures, or graphic accents drawn on top of the canvas beyond the single corner motif.
113
114The mood should feel bold, warm, contemporary-print-shop, and gallery-ready — a full-bleed small-press riso keepsake portrait that looks like it was pulled from a numbered edition, with the saturated ink running clean to every edge.`;
115
116const ATHOME = `Create a BRIGHT, BUBBLY, JOYFUL disco-era retro photograph of the pet (or pets) shown in the reference image(s), standing or sitting inside a quintessential late-1970s American KITCHEN — the look of a glossy 1978 magazine ad page or a sunny family Polaroid: SATURATED, OPTIMISTIC, and full of disco-era pop, NOT dingy, NOT damaged, NOT moody.
117
118Canvas requirements:
119- 1:1 square aspect ratio (equal width and height)
120- The frame is a fully rendered, photorealistic disco-era 1970s kitchen — never a living room, never an abstract field, never a flat colour, never modern, never dim
121- Bright disco-era colour palette — saturated, candy-finished, glossy: bright avocado green, lemon yellow, hot pink, candy tangerine, mint, sky blue, bubblegum, gleaming chrome
122- Build the scene from a tight selection of these icons (compose well, never cluttered):
123 • A GLOSSY AVOCADO GREEN refrigerator (Frigidaire era) with chrome handle and rounded shoulders — bright, polished, almost candy-finished — with a couple of YELLOW SMILEY-FACE magnets on the door
124 • A matching avocado-green or poppy-red range/oven with chrome trim and analog dials
125 • Bright YELLOW or harvest-gold Formica countertops with a glossy finish, chrome edge banding
126 • White or warm wood-veneer cabinets with chrome ring pulls
127 • A bold CHECKERBOARD linoleum floor (black + white, OR orange + cream, OR hot-pink + cream)
128 • A glowing ORANGE or PINK LAVA LAMP, actively bubbling, sitting prominently on the counter
129 • A round white pendant GLOBE LAMP or a colourful beaded swag lamp hanging from above; OR a small mirrored DISCO BALL hanging in one upper corner of the frame, catching the light and scattering soft sparkle dots on the wall
130 • DAISY-PRINT, SMILEY-FACE, or RAINBOW-STRIPE wallpaper / wallpaper border in saturated cheerful colours
131 • A few bright happy props: a stack of vinyl LP records leaning against a wall, a yellow happy-face wall clock or sunburst clock, a red enamel kettle, a Merry-Mushroom ceramic canister set, a rainbow-striped tea towel, a Pyrex bowl in bright yellow or pink
132 • Glossy CHROME accents wherever the period allows — kettle, fridge handle, lamp base, a chrome bar stool leg
133- LIGHTING — BRIGHT, BUBBLY, AND WELL-EXPOSED, NEVER DIM:
134 • Bright cheerful daylight pouring in through a sunny kitchen window AND a warm overhead fixture firing — the room is fully illuminated, never a tungsten-only mood lit scene
135 • The lava lamp adds a warm orange / pink accent glow on the counter; if a disco ball is present, scattered soft sparkle dots dance gently on one wall
136 • Crisp catchlights in the pet's eyes from the daylight source
137 • Never dim, never moody, never amber gloom, never underexposed — the kitchen reads as sunny, cheerful, and well-lit
138
139Subject requirements:
140- If a single reference image is provided, photograph that one pet alone
141- If multiple reference images are provided, photograph all of the pets together in the same scene, naturally grouped on the linoleum, the rug, or beside the appliances
142- Preserve each pet's individual identity exactly: breed, coat colour and pattern, markings, eye colour, fur length / texture, expression, age, body proportions. The pet must look REAL — a real photographed adult dog with its full coat texture, individual hairs, real wet specular on the nose, glossy iris with a clean catchlight — NEVER cartoonish, NEVER AI-cute, NEVER smoothed plush-toy puppy-render, NEVER a children's-book illustration
143- The pet is the unmistakable hero of the frame — sharply in focus, in the foreground, anchoring the central third — while the kitchen sits around it in a comfortable but readable depth-of-field falloff
144
145Pose requirements:
146- Hero pose: pet sitting or standing naturally on the kitchen floor or rug — body squared toward the viewer or in a soft 3/4 turn, head held high and alert
147- Warm, confident bearing — ears perked, gaze directed at the camera (or just past it)
148- Calm, characterful expression, as if briefly pausing mid-walk for the photographer
149
150Style requirements — GLOSSY BRIGHT RETRO PHOTO, NOT DAMAGED, NOT DINGY, NOT DISTRESSED:
151- The image reads as a glossy, joyful, well-exposed 1978 Kodachrome family photo or magazine-ad page — sharp, colourful, optimistic — NEVER as a damaged or beat-up artifact, NEVER as found-in-attic decay
152- SATURATED COLOUR POP — every disco-era hue glows: vibrant avocado, electric tangerine, lemon yellow, hot pink, mint, bubblegum, chrome highlights
153- BRIGHT NEUTRAL EXPOSURE — clean white-point, gentle Kodachrome warmth in the midtones only (not an amber tint over the whole frame), gentle highlight bloom on chrome and glass, soft milky blacks (never crushed). Slight retro warmth — never a heavy amber filter
154- Very SUBTLE film texture only — a hint of fine 35mm film grain, that's it
155- NO HEAVY DISTRESS — explicitly DO NOT add: light leaks, edge streaks, visible scratches, dust specks, hairs, emulsion cracks, water stains, thumbprint smudges, corner damage, faded or chemically-shifted corners, heavy vignetting, chromatic aberration, or any other "aged artifact" effects. The photo must look CLEAN, well-cared-for, and JOYFUL — as if it was just printed yesterday from a 1978 negative
156- Good contrast and clean micro-detail — a sharp, well-printed magazine-quality photograph; not soft, not underexposed
157- Composed like a glossy magazine spread — pet centred and confident, rule-of-thirds anchoring, layered foreground / midground / background
158
159${COMPOSITION_TIGHT}
160
161Scene + surround — strict:
162- The bright disco-era kitchen fills the surround beyond the pet; the checker linoleum grounds the bottom, the avocado fridge / glossy cabinets / cheerful wallpaper anchor the back, the lava lamp / disco ball / pendant lamp / canisters anchor the midground — but never compete with the pet for focus.
163- No on-image text, captions, signatures, watermarks, dates, or graphic overlays — this is a clean, well-exposed photographic print.
164- No people, no hands, no human figures partially visible — the pet is alone in the frame.
165- No other animals beyond those in the reference photo(s).
166- No modern electronics, no flat-screen TVs, no smartphones, no LED lighting, no stainless-steel appliances, no contemporary minimalist furniture — period correctness is non-negotiable. The fridge MUST be avocado green / harvest gold / poppy red, never white, never stainless.
167
168The mood should feel bright, bubbly, joyful, optimistic, and unmistakably late-1970s disco-era — a sunny, glossy retro keepsake photograph of the pet at home in a cheerful disco-era kitchen, NOT a damaged found-in-attic artifact.`;
169
170const NEOEXPRESSIONIST = `Create a bold, raw, Basquiat-inspired neo-expressionist standing portrait of the pet (or pets) shown in the reference image(s) — the look of a hand-painted street-art / graffiti canvas, full-body hero pose, large iconography.
171
172Canvas requirements:
173- 1:1 square aspect ratio (equal width and height)
174- Background must read as a heavily worked graffiti-on-canvas surface — bold blocks of saturated colour layered, scraped, dripped, and overpainted in the spirit of Jean-Michel Basquiat's portrait grounds — hot pink / magenta, cadmium yellow, deep cobalt, sumi black, cream, vermillion, acid green, plus raw exposed unprimed canvas patches
175- The painted ground should feel raw and confidently improvised: paint drips running visibly down the surface, scratched and scribbled mark-making layered over colour washes, distressed exposed underlayers, occasional palette-knife scrapes, the feel of acrylic + spray paint + oil-stick applied to unprimed stretched canvas
176- Carry classic Basquiat-style graffiti iconography around and behind the pet, drawn LARGE and confident — sized so each icon is roughly 15–30% of the canvas dimension, never small or subtle:
177 • A bold three-pointed gold or yellow CROWN floating directly above the pet's head, drawn with a thick dripping brush, the crown roughly as wide as the pet's head — this is the signature element, make it dominant
178 • 2–3 large secondary marks from this set, scattered around the pet (never on the face): a large capital "M" or "W" letterform, a bold scribbled X or asterisk, a confident hand-drawn arrow, a chunky three-bar halo over the crown, a stylised dollar-sign or copyright mark, a quick smiley face, a single bold heart. Each at meaningful scale, drawn with a thick dripping brush
179- Do NOT spell out any words, the pet's name, sentences, or readable text — only the abstract icon set above
180- The backdrop must remain energetic but readable: no scenery, no objects, no readable words or sentences, no logos, no signatures, no dates
181
182Subject requirements:
183- If a single reference image is provided, paint that one pet alone
184- If multiple reference images are provided, paint all of the pets together in a single unified portrait, naturally grouped, all standing
185- Preserve each pet's individual identity through the expressionist treatment: breed silhouette, coat pattern, markings, eye colour, and distinctive features must remain clearly recognizable
186
187Pose requirements — STANDING HERO, NOT BUST:
188- The pet is in a STANDING HERO POSE — full body planted, all four legs visible, chest forward, head held high, body squared toward the viewer or in a soft 3/4 turn
189- Confident, regal, slightly defiant bearing — chest forward, ears perked, gaze directed forward and slightly up
190- The pet stands as if posing for the viewer on a graffitied alley wall — proud, characterful, monumental
191- The crown floats prominently above the pet's head, treated like a halo / king's-crown signature
192
193Style requirements (applied only to the pet, never to the background as scenery):
194- Jean-Michel Basquiat-inspired neo-expressionist portrait aesthetic — raw, urgent, energetic, painted with broad gestural strokes and confident dark linework
195- Build the pet from layered slabs of paint and bold black outlines: a thick, slightly wobbly black contour tracing the silhouette, the muzzle, the eyes, the ears, the legs, and the major coat masses; secondary lines for whiskers, brow tufts, key fur direction, and muscle articulation
196- Inside the contour: confident gestural strokes of saturated colour (pink, cobalt, yellow, vermillion, cream, black) standing in for fur and markings — never photographic shading, never airbrushed gradient
197- Visible paint drips running from the lower edges of the contour and from saturated colour patches, a few quick scribbled cross-hatch marks for shadow under the belly and behind the legs, occasional scratch-back lines revealing the under-painting
198- Preserve the pet's actual eye colour and nose colour as the most readable features — painted with care so the personality reads through the expressionist treatment
199- The crown, M's, arrows, and other iconography are part of the painted subject layer, drawn with the same thick dripping brush as the contour — never thin or refined, always confident and graffiti-loose
200
201${COMPOSITION_STANDING}
202
203Background + surround — strict:
204- The painted graffiti ground fills the surround beyond the pet — drips and overpaint may run to the edges; no borders, frames, mats, captions, readable words, signatures, dates, or logos drawn on top of the canvas.
205- The bold large-scale set of Basquiat-style icons (a dominant crown above the head, plus 2–3 large secondary marks: M/W, arrow, X, halo, smiley, heart) is the only graphic accent; no additional decorative elements, no spelled-out words.
206
207The mood should feel bold, raw, urgent, street-art, downtown-gallery, and unmistakably contemporary — a vivid neo-expressionist standing-king keepsake portrait that looks like it was painted on a Lower East Side gallery canvas.`;
208
209// ─── Style table (per-style reference photo + model) ────────────────
210const STYLES = [
211 { id: 'risograph', name: 'Risograph', prompt: RISOGRAPH, model: 'gemini-3-pro-image', pet: 'murph', reference: 'public/portraits/before-murph.jpg' },
212 { id: 'athome', name: 'At Home (retro)', prompt: ATHOME, model: 'gpt-image-2', pet: 'frank', reference: 'public/portraits/before-frank.jpg' },
213 { id: 'neoexpressionist', name: 'Neo-Expressionist', prompt: NEOEXPRESSIONIST, model: 'gemini-3-pro-image', pet: 'rex', reference: 'public/portraits/before-rex.jpg' },
214];
215
216fs.mkdirSync(OUT_DIR, { recursive: true });
217
218function loadReference(refRelPath) {
219 const refPath = path.resolve(ROOT, refRelPath);
220 if (!fs.existsSync(refPath)) throw new Error(`Reference not found: ${refPath}`);
221 const bytes = fs.readFileSync(refPath);
222 const mime = refPath.endsWith('.png') ? 'image/png' : 'image/jpeg';
223 return { bytes, mime, blob: new Blob([bytes], { type: mime }), name: path.basename(refPath), b64: bytes.toString('base64') };
224}
225
226// ─── OpenAI ─────────────────────────────────────────────────────────
227async function renderViaOpenAI({ prompt, model, ref }, outPath) {
228 if (!OPENAI_KEY) throw new Error('OPENAI_API_KEY not set');
229 const form = new FormData();
230 form.set('model', model);
231 form.set('prompt', prompt);
232 form.set('size', SIZE);
233 form.set('n', '1');
234 form.append('image', ref.blob, ref.name);
235 const r = await fetch('https://api.openai.com/v1/images/edits', {
236 method: 'POST',
237 headers: { Authorization: `Bearer ${OPENAI_KEY}` },
238 body: form,
239 });
240 if (!r.ok) {
241 const text = await r.text();
242 throw new Error(`${r.status} ${r.statusText}: ${text.slice(0, 400)}`);
243 }
244 const json = await r.json();
245 const b64 = json?.data?.[0]?.b64_json;
246 if (!b64) throw new Error('No image data in OpenAI response');
247 fs.writeFileSync(outPath, Buffer.from(b64, 'base64'));
248}
249
250// ─── Gemini (Nano Banana) ───────────────────────────────────────────
251async function renderViaGemini({ prompt, model, ref }, outPath) {
252 if (!GEMINI_KEY) throw new Error('GEMINI_API_KEY not set');
253 const body = {
254 contents: [
255 {
256 parts: [
257 { text: prompt },
258 { inline_data: { mime_type: ref.mime, data: ref.b64 } },
259 ],
260 },
261 ],
262 generationConfig: { responseModalities: ['image', 'text'] },
263 };
264 const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`;
265 const r = await fetch(url, {
266 method: 'POST',
267 headers: { 'x-goog-api-key': GEMINI_KEY, 'content-type': 'application/json' },
268 body: JSON.stringify(body),
269 });
270 if (!r.ok) {
271 const text = await r.text();
272 throw new Error(`${r.status} ${r.statusText}: ${text.slice(0, 400)}`);
273 }
274 const json = await r.json();
275 const parts = json?.candidates?.[0]?.content?.parts ?? [];
276 let b64 = null;
277 for (const part of parts) {
278 const data = part?.inline_data?.data ?? part?.inlineData?.data;
279 if (data) { b64 = data; break; }
280 }
281 if (!b64) throw new Error('No image data in Gemini response');
282 fs.writeFileSync(outPath, Buffer.from(b64, 'base64'));
283}
284
285// ─── Dispatch ───────────────────────────────────────────────────────
286async function renderStyle(style) {
287 const ref = loadReference(style.reference);
288 const outPath = path.join(OUT_DIR, `after-${style.pet}-${style.id}.png`);
289 const tag = style.model.startsWith('gemini') ? 'gemini' : 'openai';
290 console.log(`→ ${style.name.padEnd(22)} (${style.id}, ${tag} · ${style.model}, ref=${style.pet})`);
291 const args = { prompt: style.prompt, model: style.model, ref };
292 if (style.model.startsWith('gemini')) {
293 await renderViaGemini(args, outPath);
294 } else {
295 await renderViaOpenAI(args, outPath);
296 }
297 console.log(` ✓ ${path.relative(ROOT, outPath)}`);
298}
299
300const targets = ONLY ? STYLES.filter((s) => ONLY.has(s.id)) : STYLES;
301console.log(`Out: ${path.relative(ROOT, OUT_DIR)}`);
302console.log(`Styles: ${targets.map((t) => `${t.id} (${t.pet})`).join(', ')}\n`);
303
304// Run all in parallel — each is an independent API call.
305const results = await Promise.allSettled(targets.map(renderStyle));
306let fails = 0;
307results.forEach((r, i) => {
308 if (r.status === 'rejected') {
309 fails++;
310 console.error(` ✗ ${targets[i].id}: ${r.reason?.message || r.reason}`);
311 }
312});
313console.log(`\nDone. ${results.length - fails}/${results.length} succeeded.`);