Branchwell

Lumen & Gesso / website · lumengesso.com / scripts / generate-otto-teddy-ziggy.mjs

1#!/usr/bin/env node
2// One-off content refresh: regenerate Otto + Teddy and mint a new pop-art
3// cat (Ziggy) for the home-feature trio. Three stages per pet, all via
4// Gemini Nano Banana Pro, written to public/portraits as optimized JPEG:
5//
6// 1) before-{id}.jpg text->image (3:4 phone-snapshot look)
7// 2) after-{id}-{style}.jpg before->styled square artwork (the print)
8// 3) lifestyle-{id}-{style}.jpg artwork->framed-on-a-wall room shot
9//
10// Style ingredients mirror app/lib/image-gen.ts; the landscape-oil prompt
11// and the lifestyle framing prompt mirror the proven one-off scripts.
12//
13// Usage:
14// node scripts/generate-otto-teddy-ziggy.mjs
15// ONLY=ziggy node scripts/generate-otto-teddy-ziggy.mjs # one pet
16// STAGES=lifestyle node scripts/generate-otto-teddy-ziggy.mjs # one stage
17//
18// Pets run in parallel; stages within a pet run in order (each feeds the
19// next). Reads GEMINI_API_KEY from the environment or .env.local.
20
21import fs from 'node:fs';
22import path from 'node:path';
23import { fileURLToPath } from 'node:url';
24import sharp from 'sharp';
25
26const __dirname = path.dirname(fileURLToPath(import.meta.url));
27const ROOT = path.resolve(__dirname, '..');
28const PORTRAITS = path.join(ROOT, 'public/portraits');
29const MODEL = 'gemini-3-pro-image';
30const IMAGE_SIZE = process.env.GEMINI_IMAGE_SIZE || '2K';
31
32function 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}
48loadEnvLocal();
49
50const GEMINI_KEY = process.env.GEMINI_API_KEY;
51if (!GEMINI_KEY) {
52 console.error('GEMINI_API_KEY not set (env or .env.local)');
53 process.exit(1);
54}
55
56// ── Shared prompt fragments ──────────────────────────────────────────
57const STYLE_INGREDIENTS = {
58 mixedmedia:
59 'abstract contemporary mixed-media — heavy oil/acrylic impasto, broad aggressive brush strokes, palette-knife smears and scraped ridges, dry charcoal-like marks, paint drips, visible canvas grain. The pet simplified into bold painterly shapes but still recognizable. Muted ivory/cream/taupe/umber palette on a layered warm off-white ground; lower body dissolves into gestural marks.',
60 popart:
61 'bold contemporary pop-art painting — the coat reimagined in confident blocks and streaks of saturated colour (cobalt, violet, magenta, vermilion, cream, black) running along the fur, thick gestural visible brushwork, with playful polka-dot motifs scattered on a few passages. The pet stays recognizable — only the colour is reimagined, never the anatomy. Quiet hand-painted neutral ground with a few faint muted colour blocks.',
62};
63
64const BUST_COMPOSITION =
65 'COMPOSITION: square 1:1, filled edge to edge. Put the head and eyes in the upper-middle — about 20-35% down from the top — with only a sliver of room above the ears; let the lower chest and body fade off the bottom edge (bust style). Never crop the head, ears, eyes, muzzle, or nose.';
66
67// geminiBase() equivalent from app/lib/image-gen.ts — subject fidelity +
68// the per-style ingredient + a bust composition + clean output.
69function styledArtworkPrompt(styleName, ingredient) {
70 return [
71 `Recreate the pet from the reference photo as a ${styleName} portrait.`,
72 '',
73 "SUBJECT — most important: keep the exact pet from the photo. Same breed, coat colour and markings, eye colour, ear shape, nose, and distinctive features — it must stay instantly recognizable to its owner. Do not blend in another animal or invent features.",
74 '',
75 `STYLE: ${ingredient}`,
76 '',
77 BUST_COMPOSITION,
78 '',
79 'CLEAN OUTPUT: no border, frame, mat, vignette, caption, signature, watermark, or lettering of any kind — just the portrait.',
80 ].join('\n');
81}
82
83// Otto keeps the proven verbatim landscape-oil prompt from
84// generate-otto-landscape.mjs (a legacy gallery look, not a catalog style).
85const LANDSCAPE_OIL_PROMPT = `Create a classical landscape oil-style portrait of the pet shown in the reference image — the look of a 19th-century Romantic-era oil painting on canvas, with the pet as the central subject in an autumn outdoor scene.
86
87Canvas requirements:
88- 1:1 square aspect ratio (equal width and height)
89- The artwork is a full-bleed oil painting on canvas — no border, no mat, no frame inside the image. The painted scene fills the entire canvas edge-to-edge.
90
91Subject:
92- Preserve the pet's identity exactly: breed, coat colour and pattern, markings, eye colour, fur length, and distinctive features must match the reference photo
93- Pose: pet sitting or standing in a confident 3/4 turn toward the viewer, head held high, alert, characterful
94
95Scene:
96- Place the pet in a romantic autumn landscape — golden-orange foliage, soft turning leaves on the ground, a hint of distant rolling hills or a meadow, warm low-angle late-afternoon sunlight
97- The scene composition keeps the pet as the unmistakable hero in the foreground, with the landscape behind in soft painterly falloff
98
99Style:
100- Classical oil-on-canvas aesthetic in the lineage of George Stubbs, John Emms, and 19th-century pet-portrait painters
101- Visible brushwork — soft confident strokes following fur direction and the contours of the leaves and ground
102- Layered glazes producing a warm Old-Master colour palette: burnt sienna, ochre, raw umber, cadmium yellow accents on the leaves, soft greens in the distance, warm flesh-tones on the pet's coat
103- Soft chiaroscuro lighting from a single warm light source — gentle shadow under the pet grounding it in the scene
104- Visible canvas-weave texture across the painted surface
105
106Composition and framing — strict:
107- The painted scene FILLS THE FULL CANVAS edge-to-edge. No empty white space, no border, no mat.
108- Position the pet's head and eyes in the upper-middle of the canvas (about 25-35% down from the top), with comfortable breathing room above filled with foliage / sky.
109- The pet's body fills the central composition; the landscape wraps around it.
110- Never crop the head, ears, eyes, muzzle, or nose.
111
112The mood should feel warm, romantic, classical, and gallery-ready — a Romantic-era oil pet portrait you'd find hanging in an old country house.`;
113
114// Stage 3 — place a finished square artwork inside a frame on a wall.
115// Style-agnostic version of the generate-lifestyle.mjs framing prompt.
116function lifestylePrompt(frame, scene) {
117 return `Editorial interior photograph. Place the supplied artwork inside a ${frame}, hanging on a wall (or leaning naturally against one) inside ${scene}. The framed artwork is the focal point — centered, clearly readable, no distortion.
118
119CRITICAL — the supplied image IS the artwork that goes inside the frame: the ENTIRE supplied square source image must appear inside the frame opening in full, as supplied. DO NOT CROP, TRIM, ZOOM IN ON, RE-COMPOSE, or RE-PAINT the source artwork. Every corner of the supplied square is visible inside the frame, never cut off, never extended, never re-imagined. The source image is the artwork; the room is a backdrop around it.
120
121CRITICAL — reproduce the COMPLETE supplied artwork inside the frame exactly as given — the pet AND its full painted background, every corner. DO NOT crop down to just the pet, DO NOT isolate the pet on a plain white mat, DO NOT drop, blur, flatten, or replace the artwork's background, and DO NOT substitute any other picture.
122
123CRITICAL — frame profile: the frame is a SIMPLE, FLAT, THIN, CONTEMPORARY rectangular strip in the finish requested. NO 3D depth, NO raised molding, NO bevel, NO carved ornament, NO scrollwork, NO baroque embellishment, NO antique-style frame profile. Just a clean flat strip sitting flush around the artwork — the kind a contemporary gallery uses.
124
125Real-world lighting and shadow on the frame; subtle wall texture. Magazine-quality interior photography, soft natural light, no people, no text overlay.`;
126}
127
128// ── Pet jobs ─────────────────────────────────────────────────────────
129const PETS = [
130 {
131 id: 'otto',
132 before: 'before-otto-v2.jpg',
133 after: 'after-otto-landscape-oil-v2.jpg',
134 lifestyle: 'lifestyle-otto-landscape-v3.jpg',
135 beforePrompt: `A photoreal hero portrait photograph of a fluffy tan-and-white Shih Tzu with a long flowing silky coat, a single small top-knot tied above the forehead, big dark round soulful eyes, a short pushed-in muzzle, and a glossy black button nose. The dog faces the camera in a soft 3/4 turn, head held high, alert and characterful, a small king. Three-quarter chest crop — head and chest dominate the frame, lower body fades softly. Soft natural daylight from a single window source, gentle warm reflected fill, clean catchlights in both eyes. Background is a quiet, slightly out-of-focus soft cream / oat backdrop with very gentle vignetting — no scenery, no props, no text. Sharp focus on the eyes and muzzle, gentle falloff on the coat tips. Editorial pet photography, magazine-cover quality. Realistic adult-dog coat texture with individual hairs catchable in highlights, no painted or illustrated quality, no cartoon, no AI-cute aesthetic.`,
136 afterPrompt: LANDSCAPE_OIL_PROMPT,
137 frame:
138 'thin soft-white canvas float frame with a clean rectangular profile (NOT ornate, NOT carved). The painted canvas FILLS the interior of the frame EDGE-TO-EDGE — NO mat, NO matte border, NO white space around the artwork. Only a thin dark recess strip between the canvas edge and the frame moulding, the signature canvas-float look',
139 scene:
140 'a warm country-house study with a deep brown leather wingback chair, a small wood writing desk, a brass desk lamp, rich oak floorboards, and warm afternoon light — the framed canvas hangs above the chair',
141 },
142 {
143 id: 'teddy',
144 before: 'before-teddy.jpg',
145 after: 'after-teddy-mixedmedia-v3.jpg',
146 lifestyle: 'lifestyle-teddy-mixedmedia-v4.jpg',
147 beforePrompt: `A photoreal hero portrait photograph of a long-haired Yorkshire Terrier with a silky, well-groomed steel-blue-and-tan coat parted down the back, two small muted blue-grey ribbon bows holding up the topknot above the forehead, dark soulful round eyes, a small black button nose, and a tiny, well-groomed, slightly skeptical expression. The dog faces the camera straight-on with a soft head tilt, ears framed by the long fur. Three-quarter chest crop — head and chest dominate the frame, lower body fades softly. Soft natural daylight from a single window source, gentle warm reflected fill, clean catchlights in both eyes. Background is a quiet, slightly out-of-focus soft cream / oat backdrop with very gentle vignetting — no scenery, no props, no text. Sharp focus on the eyes and muzzle, gentle falloff on the silky coat tips. Editorial pet photography, magazine-cover quality. Realistic adult-dog silky coat texture with individual hairs catchable in highlights, no painted or illustrated quality, no cartoon, no AI-cute aesthetic.`,
148 afterPrompt: `Paint a rich, refined IMPASTO OIL PORTRAIT of the dog in the reference photo — a gorgeous, gallery-quality oil painting rendered ENTIRELY in confident, visible brushstrokes and thick textured paint.
149
150SUBJECT — keep the exact dog: a long-haired Yorkshire Terrier with a silky steel-blue-and-tan coat and a small grey ribbon bow in its topknot. Instantly recognizable, with a warm, endearing expression.
151
152PAINTERLY TREATMENT — the most important thing: the ENTIRE portrait, INCLUDING the face and eyes, is hand-painted in expressive oil — NOT photographic. Confident directional brushstrokes follow the flow of the fur; thick impasto ridges and palette-knife highlights catch the light; the muzzle and eyes are softly blended but clearly painted. Warm, harmonious palette (honey, caramel, slate-grey, cream, soft umber). It must read as ONE cohesive, finished, beautiful oil painting in the spirit of Sargent or a fine contemporary pet-portrait painter.
153
154STRICTLY AVOID: a photo-real or hyper-real face sitting on a loose body; scratchy black scribbled lines; chaotic scraped marks; runny paint drips; bare canvas or blotchy, unfinished passages. Every part of the painting is intentional and refined.
155
156COMPOSITION: square 1:1, filled edge to edge. Head and chest fill the frame, eyes about a third down from the top. The lower chest melts GENTLY into soft painterly strokes near the bottom — no hard cut-out, no drips. A soft, warm, brushed background of gentle painterly tones, never scraped or scribbled. Never crop the head, ears, eyes, muzzle, or nose.
157
158CLEAN OUTPUT: no border, frame, mat, caption, signature, watermark, or lettering — just the painting.`,
159 frame:
160 'thin soft-white canvas float frame with a clean rectangular profile (NOT ornate, NOT carved). The painted canvas FILLS the interior of the frame EDGE-TO-EDGE — NO mat, NO matte border, NO white space around the artwork. Only a thin dark recess strip between the canvas edge and the frame moulding, the signature canvas-float look',
161 scene:
162 'a sunlit modern living room with a cream linen sofa, a warm-oak side table, a small monstera plant, and soft daylight from a tall window — the framed canvas hangs on a soft warm-white wall',
163 },
164 {
165 id: 'ziggy',
166 before: 'before-ziggy.jpg',
167 after: 'after-ziggy-popart.jpg',
168 lifestyle: 'lifestyle-ziggy-popart.jpg',
169 beforePrompt: `A photoreal hero portrait photograph of an adult ginger orange tabby cat with a warm, vivid ginger coat showing bold classic mackerel tabby stripes, a clean white chest blaze and chin, a soft pink nose, white whiskers, and large round amber-green eyes with a clean catchlight. The cat sits upright in a confident 3/4 turn toward the camera, head held high, ears perked forward, composed and characterful — a small sun with strong opinions. Three-quarter chest crop — head and chest dominate the frame, lower body fades softly. Soft natural daylight from a single window source, gentle warm reflected fill. Background is a quiet, slightly out-of-focus soft cream / oat backdrop with very gentle vignetting — no scenery, no props, no text. Sharp focus on the eyes and muzzle, gentle falloff on the coat. Editorial pet photography, magazine-cover quality. Realistic adult-cat fur texture with individual hairs catchable in highlights, no painted or illustrated quality, no cartoon, no AI-cute aesthetic — a real adult family cat photographed candidly.`,
170 afterPrompt: styledArtworkPrompt('pop-art', STYLE_INGREDIENTS.popart),
171 frame: 'thin contemporary soft-white frame with a snow-white mat — clean rectangular profile, NO ornament, NO depth, NO carving',
172 scene:
173 'a bright, cheerful breakfast nook with a round white table, two pale-wood chairs, a small ceramic vase of tulips, and crisp morning sunlight; the framed artwork hangs on a clean white wall; fresh and upbeat atmosphere',
174 },
175];
176
177// ── Gemini call (with one retry) ─────────────────────────────────────
178async function gemini({ prompt, refPath, aspect }) {
179 const parts = [{ text: prompt }];
180 if (refPath) {
181 const bytes = fs.readFileSync(refPath);
182 const mime = refPath.endsWith('.png') ? 'image/png' : 'image/jpeg';
183 parts.push({ inline_data: { mime_type: mime, data: bytes.toString('base64') } });
184 }
185 const imageConfig = { aspectRatio: aspect || '1:1' };
186 if (IMAGE_SIZE && IMAGE_SIZE !== '1K') imageConfig.imageSize = IMAGE_SIZE;
187 const body = {
188 contents: [{ parts }],
189 generationConfig: { responseModalities: ['image', 'text'], imageConfig },
190 };
191 const url = `https://generativelanguage.googleapis.com/v1beta/models/${MODEL}:generateContent`;
192
193 let lastErr;
194 for (let attempt = 1; attempt <= 2; attempt++) {
195 try {
196 const r = await fetch(url, {
197 method: 'POST',
198 headers: { 'x-goog-api-key': GEMINI_KEY, 'content-type': 'application/json' },
199 body: JSON.stringify(body),
200 });
201 if (!r.ok) throw new Error(`${r.status} ${r.statusText}: ${(await r.text()).slice(0, 300)}`);
202 const json = await r.json();
203 const out = json?.candidates?.[0]?.content?.parts ?? [];
204 for (const part of out) {
205 const data = part?.inline_data?.data ?? part?.inlineData?.data;
206 if (data) return Buffer.from(data, 'base64');
207 }
208 throw new Error('no image data in response');
209 } catch (e) {
210 lastErr = e;
211 if (attempt < 2) await new Promise((res) => setTimeout(res, 1500));
212 }
213 }
214 throw lastErr;
215}
216
217async function saveJpeg(buf, outName, { maxW, maxH, quality }) {
218 const outPath = path.join(PORTRAITS, outName);
219 await sharp(buf)
220 .resize({ width: maxW, height: maxH, fit: 'inside', withoutEnlargement: true })
221 .jpeg({ quality, mozjpeg: true })
222 .toFile(outPath);
223 const kb = Math.round(fs.statSync(outPath).size / 1024);
224 console.log(` ✓ ${outName} (${kb} KB)`);
225}
226
227const ONLY = process.env.ONLY ? new Set(process.env.ONLY.split(',').map((s) => s.trim())) : null;
228const STAGES = process.env.STAGES
229 ? new Set(process.env.STAGES.split(',').map((s) => s.trim()))
230 : new Set(['before', 'after', 'lifestyle']);
231
232async function runPet(pet) {
233 const beforePath = path.join(PORTRAITS, pet.before);
234 const afterPath = path.join(PORTRAITS, pet.after);
235
236 if (STAGES.has('before')) {
237 console.log(` [${pet.id}] before…`);
238 const buf = await gemini({ prompt: pet.beforePrompt, aspect: '3:4' });
239 await saveJpeg(buf, pet.before, { maxW: 1500, maxH: 2000, quality: 88 });
240 }
241 if (STAGES.has('after')) {
242 if (!fs.existsSync(beforePath)) throw new Error(`missing ${pet.before} (run the 'before' stage first)`);
243 console.log(` [${pet.id}] after (styled artwork)…`);
244 const buf = await gemini({ prompt: pet.afterPrompt, refPath: beforePath, aspect: '1:1' });
245 // High quality — this is the input to the lifestyle stage.
246 await saveJpeg(buf, pet.after, { maxW: 2048, maxH: 2048, quality: 94 });
247 }
248 if (STAGES.has('lifestyle')) {
249 if (!fs.existsSync(afterPath)) throw new Error(`missing ${pet.after} (run the 'after' stage first)`);
250 console.log(` [${pet.id}] lifestyle (framed on a wall)…`);
251 const buf = await gemini({ prompt: lifestylePrompt(pet.frame, pet.scene), refPath: afterPath, aspect: '1:1' });
252 await saveJpeg(buf, pet.lifestyle, { maxW: 1400, maxH: 1400, quality: 86 });
253 }
254}
255
256const targets = ONLY ? PETS.filter((p) => ONLY.has(p.id)) : PETS;
257console.log(`Model: ${MODEL} @ ${IMAGE_SIZE}`);
258console.log(`Pets: ${targets.map((p) => p.id).join(', ')}`);
259console.log(`Stages: ${[...STAGES].join(', ')}\n`);
260
261const results = await Promise.allSettled(targets.map(runPet));
262let fails = 0;
263results.forEach((r, i) => {
264 if (r.status === 'rejected') {
265 fails++;
266 console.error(` ✗ ${targets[i].id}: ${r.reason?.message || r.reason}`);
267 }
268});
269console.log(`\nDone. ${results.length - fails}/${results.length} pets fully succeeded.`);
270process.exit(fails ? 1 : 0);