#!/usr/bin/env node // One-off content refresh: regenerate Otto + Teddy and mint a new pop-art // cat (Ziggy) for the home-feature trio. Three stages per pet, all via // Gemini Nano Banana Pro, written to public/portraits as optimized JPEG: // // 1) before-{id}.jpg text->image (3:4 phone-snapshot look) // 2) after-{id}-{style}.jpg before->styled square artwork (the print) // 3) lifestyle-{id}-{style}.jpg artwork->framed-on-a-wall room shot // // Style ingredients mirror app/lib/image-gen.ts; the landscape-oil prompt // and the lifestyle framing prompt mirror the proven one-off scripts. // // Usage: // node scripts/generate-otto-teddy-ziggy.mjs // ONLY=ziggy node scripts/generate-otto-teddy-ziggy.mjs # one pet // STAGES=lifestyle node scripts/generate-otto-teddy-ziggy.mjs # one stage // // Pets run in parallel; stages within a pet run in order (each feeds the // next). Reads GEMINI_API_KEY from the environment or .env.local. import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import sharp from 'sharp'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(__dirname, '..'); const PORTRAITS = path.join(ROOT, 'public/portraits'); const MODEL = 'gemini-3-pro-image'; const IMAGE_SIZE = process.env.GEMINI_IMAGE_SIZE || '2K'; 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 (env or .env.local)'); process.exit(1); } // ── Shared prompt fragments ────────────────────────────────────────── const STYLE_INGREDIENTS = { mixedmedia: '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.', popart: '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.', }; const BUST_COMPOSITION = '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.'; // geminiBase() equivalent from app/lib/image-gen.ts — subject fidelity + // the per-style ingredient + a bust composition + clean output. function styledArtworkPrompt(styleName, ingredient) { return [ `Recreate the pet from the reference photo as a ${styleName} portrait.`, '', "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.", '', `STYLE: ${ingredient}`, '', BUST_COMPOSITION, '', 'CLEAN OUTPUT: no border, frame, mat, vignette, caption, signature, watermark, or lettering of any kind — just the portrait.', ].join('\n'); } // Otto keeps the proven verbatim landscape-oil prompt from // generate-otto-landscape.mjs (a legacy gallery look, not a catalog style). const 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. Canvas requirements: - 1:1 square aspect ratio (equal width and height) - 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. Subject: - Preserve the pet's identity exactly: breed, coat colour and pattern, markings, eye colour, fur length, and distinctive features must match the reference photo - Pose: pet sitting or standing in a confident 3/4 turn toward the viewer, head held high, alert, characterful Scene: - 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 - The scene composition keeps the pet as the unmistakable hero in the foreground, with the landscape behind in soft painterly falloff Style: - Classical oil-on-canvas aesthetic in the lineage of George Stubbs, John Emms, and 19th-century pet-portrait painters - Visible brushwork — soft confident strokes following fur direction and the contours of the leaves and ground - 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 - Soft chiaroscuro lighting from a single warm light source — gentle shadow under the pet grounding it in the scene - Visible canvas-weave texture across the painted surface Composition and framing — strict: - The painted scene FILLS THE FULL CANVAS edge-to-edge. No empty white space, no border, no mat. - 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. - The pet's body fills the central composition; the landscape wraps around it. - Never crop the head, ears, eyes, muzzle, or nose. The mood should feel warm, romantic, classical, and gallery-ready — a Romantic-era oil pet portrait you'd find hanging in an old country house.`; // Stage 3 — place a finished square artwork inside a frame on a wall. // Style-agnostic version of the generate-lifestyle.mjs framing prompt. function lifestylePrompt(frame, scene) { 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. CRITICAL — 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. CRITICAL — 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. CRITICAL — 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. Real-world lighting and shadow on the frame; subtle wall texture. Magazine-quality interior photography, soft natural light, no people, no text overlay.`; } // ── Pet jobs ───────────────────────────────────────────────────────── const PETS = [ { id: 'otto', before: 'before-otto-v2.jpg', after: 'after-otto-landscape-oil-v2.jpg', lifestyle: 'lifestyle-otto-landscape-v3.jpg', 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.`, afterPrompt: LANDSCAPE_OIL_PROMPT, frame: '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', scene: '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', }, { id: 'teddy', before: 'before-teddy.jpg', after: 'after-teddy-mixedmedia-v3.jpg', lifestyle: 'lifestyle-teddy-mixedmedia-v4.jpg', 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.`, 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. SUBJECT — 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. PAINTERLY 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. STRICTLY 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. COMPOSITION: 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. CLEAN OUTPUT: no border, frame, mat, caption, signature, watermark, or lettering — just the painting.`, frame: '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', scene: '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', }, { id: 'ziggy', before: 'before-ziggy.jpg', after: 'after-ziggy-popart.jpg', lifestyle: 'lifestyle-ziggy-popart.jpg', 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.`, afterPrompt: styledArtworkPrompt('pop-art', STYLE_INGREDIENTS.popart), frame: 'thin contemporary soft-white frame with a snow-white mat — clean rectangular profile, NO ornament, NO depth, NO carving', scene: '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', }, ]; // ── Gemini call (with one retry) ───────────────────────────────────── async function gemini({ prompt, refPath, aspect }) { const parts = [{ text: prompt }]; if (refPath) { const bytes = fs.readFileSync(refPath); const mime = refPath.endsWith('.png') ? 'image/png' : 'image/jpeg'; parts.push({ inline_data: { mime_type: mime, data: bytes.toString('base64') } }); } const imageConfig = { aspectRatio: aspect || '1:1' }; if (IMAGE_SIZE && IMAGE_SIZE !== '1K') imageConfig.imageSize = IMAGE_SIZE; const body = { contents: [{ parts }], generationConfig: { responseModalities: ['image', 'text'], imageConfig }, }; const url = `https://generativelanguage.googleapis.com/v1beta/models/${MODEL}:generateContent`; let lastErr; for (let attempt = 1; attempt <= 2; attempt++) { try { 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, 300)}`); const json = await r.json(); const out = json?.candidates?.[0]?.content?.parts ?? []; for (const part of out) { const data = part?.inline_data?.data ?? part?.inlineData?.data; if (data) return Buffer.from(data, 'base64'); } throw new Error('no image data in response'); } catch (e) { lastErr = e; if (attempt < 2) await new Promise((res) => setTimeout(res, 1500)); } } throw lastErr; } async function saveJpeg(buf, outName, { maxW, maxH, quality }) { const outPath = path.join(PORTRAITS, outName); await sharp(buf) .resize({ width: maxW, height: maxH, fit: 'inside', withoutEnlargement: true }) .jpeg({ quality, mozjpeg: true }) .toFile(outPath); const kb = Math.round(fs.statSync(outPath).size / 1024); console.log(` ✓ ${outName} (${kb} KB)`); } const ONLY = process.env.ONLY ? new Set(process.env.ONLY.split(',').map((s) => s.trim())) : null; const STAGES = process.env.STAGES ? new Set(process.env.STAGES.split(',').map((s) => s.trim())) : new Set(['before', 'after', 'lifestyle']); async function runPet(pet) { const beforePath = path.join(PORTRAITS, pet.before); const afterPath = path.join(PORTRAITS, pet.after); if (STAGES.has('before')) { console.log(` [${pet.id}] before…`); const buf = await gemini({ prompt: pet.beforePrompt, aspect: '3:4' }); await saveJpeg(buf, pet.before, { maxW: 1500, maxH: 2000, quality: 88 }); } if (STAGES.has('after')) { if (!fs.existsSync(beforePath)) throw new Error(`missing ${pet.before} (run the 'before' stage first)`); console.log(` [${pet.id}] after (styled artwork)…`); const buf = await gemini({ prompt: pet.afterPrompt, refPath: beforePath, aspect: '1:1' }); // High quality — this is the input to the lifestyle stage. await saveJpeg(buf, pet.after, { maxW: 2048, maxH: 2048, quality: 94 }); } if (STAGES.has('lifestyle')) { if (!fs.existsSync(afterPath)) throw new Error(`missing ${pet.after} (run the 'after' stage first)`); console.log(` [${pet.id}] lifestyle (framed on a wall)…`); const buf = await gemini({ prompt: lifestylePrompt(pet.frame, pet.scene), refPath: afterPath, aspect: '1:1' }); await saveJpeg(buf, pet.lifestyle, { maxW: 1400, maxH: 1400, quality: 86 }); } } const targets = ONLY ? PETS.filter((p) => ONLY.has(p.id)) : PETS; console.log(`Model: ${MODEL} @ ${IMAGE_SIZE}`); console.log(`Pets: ${targets.map((p) => p.id).join(', ')}`); console.log(`Stages: ${[...STAGES].join(', ')}\n`); const results = await Promise.allSettled(targets.map(runPet)); let fails = 0; results.forEach((r, i) => { if (r.status === 'rejected') { fails++; console.error(` ✗ ${targets[i].id}: ${r.reason?.message || r.reason}`); } }); console.log(`\nDone. ${results.length - fails}/${results.length} pets fully succeeded.`); process.exit(fails ? 1 : 0);