#!/usr/bin/env node // Regenerate the home-feature Teddy (now a NEW dog) and the Hannah/Renee // testimonial pets (Tucker, Gus), each with THREE stages: // // 1) before-{id}.jpg a CASUAL amateur phone snapshot — relaxed, // candid pose (deliberately NOT the portrait pose; // the before doesn't need to be good) // 2) after-{id}-{style}.jpg the finished portrait — RE-POSED to a // dignified hero pose, painterly/pop-art, gorgeous // 3) lifestyle-{id}-{style}.jpg that artwork framed on a wall in a room // // The before and after are the SAME dog (identity preserved) in DIFFERENT // poses — the real "casual photo in → beautiful portrait out" story. // // node scripts/generate-teddy-tucker-gus.mjs // ONLY=teddy STAGES=before node scripts/generate-teddy-tucker-gus.mjs 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 k = line.slice(0, eq).trim(); let v = line.slice(eq + 1).trim(); if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1); if (!(k in process.env)) process.env[k] = v; } } loadEnvLocal(); const GEMINI_KEY = process.env.GEMINI_API_KEY; if (!GEMINI_KEY) { console.error('GEMINI_API_KEY not set'); process.exit(1); } // ── Shared after-prompt builders (RE-POSE to a hero pose, keep identity) ── const REPOSE = `IMPORTANT — POSE: render the dog in a dignified HERO PORTRAIT pose — sitting or standing tall in a confident 3/4 turn toward the viewer, head up, alert, composed. You MAY change the pose from the reference photo; the reference is ONLY for the dog's identity. Do NOT copy the casual snapshot pose. IDENTITY — keep the EXACT same dog as the reference: same breed, coat colour and markings, fur texture/length, ear shape, eye colour, nose, and distinctive features. It must be unmistakably the same dog, just beautifully posed.`; function painterlyOil(subject) { return `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} ${REPOSE} PAINTERLY TREATMENT — most important: the ENTIRE portrait, INCLUDING the face and eyes, is hand-painted in expressive oil — NOT photographic. Confident directional brushstrokes follow 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. 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 face on a loose body; scratchy black scribbled lines; chaotic scraped marks; runny paint drips; bare canvas or blotchy unfinished passages. COMPOSITION: square 1:1, filled edge to edge. Head and chest fill the frame, eyes about a third down from the top. Lower chest melts gently into soft painterly strokes near the bottom — no hard cut-out, no drips. Soft, warm, brushed background of gentle painterly tones. Never crop the head, ears, eyes, muzzle, or nose. CLEAN OUTPUT: no border, frame, mat, caption, signature, watermark, or lettering — just the painting.`; } function popArt(subject) { return `Create a bold contemporary POP-ART painting of the dog in the reference photo. ${subject} ${REPOSE} STYLE: 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. Only the COLOUR is reimagined — never the anatomy or identity. Quiet hand-painted neutral ground with a few faint muted colour blocks. COMPOSITION: square 1:1, filled edge to edge. Head and chest in the upper-middle; lower chest fades toward the bottom. Never crop the head, ears, eyes, muzzle, or nose. CLEAN OUTPUT: no border, frame, mat, caption, signature, watermark, or lettering.`; } // Stage 3 — place the finished square artwork inside a frame on a wall. function lifestylePrompt(frame, scene) { return `Editorial interior photograph. Place the supplied artwork inside a ${frame}, hanging on a wall inside ${scene}. The framed artwork is the focal point — centered, clearly readable, no distortion. CRITICAL — the supplied square image IS the artwork: reproduce the ENTIRE supplied image inside the frame opening in full, exactly as supplied. DO NOT crop, zoom, re-compose, re-paint, or substitute it. Every corner of the supplied square is visible inside the frame. CRITICAL — frame profile: a SIMPLE, FLAT, THIN, CONTEMPORARY rectangular strip in the finish requested. NO 3D depth, raised molding, bevel, carved ornament, scrollwork, or antique profile — a clean flat strip 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.`; } const CANVAS_FLOAT = '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'; const WHITE_MAT = 'thin contemporary soft-white frame with a snow-white mat — clean rectangular profile, NO ornament, NO depth, NO carving'; // ── Pets ───────────────────────────────────────────────────────────── const PETS = [ { id: 'teddy', before: 'before-teddy-v2.jpg', after: 'after-teddy-mixedmedia-v4.jpg', lifestyle: 'lifestyle-teddy-mixedmedia-v5.jpg', beforePrompt: `A casual, candid iPhone SNAPSHOT of an apricot-and-cream Goldendoodle with a soft, fluffy, slightly shaggy curly teddy-bear coat, dark round eyes, and a black nose. NOT a professional photo: the dog is flopped/lying on a beige living-room sofa, relaxed, head tilted and looking slightly off to the side (not at the camera), maybe mid-blink — an ordinary moment. Imperfect amateur framing, slightly off-centre, flat ordinary indoor lighting, faint phone-camera softness. The kind of quick photo a real owner snaps. A genuine photograph, no illustration, no text, no border.`, afterPrompt: painterlyOil('SUBJECT: an apricot-and-cream Goldendoodle with a soft fluffy curly teddy-bear coat, dark round eyes, black nose — warm and endearing.'), frame: CANVAS_FLOAT, scene: 'a sunlit modern living room with a cream linen sofa, a warm-oak side table, and a small monstera plant — the framed canvas hangs on a soft warm-white wall', }, { id: 'tucker', before: 'before-tucker.jpg', after: 'after-tucker-mixedmedia-v2.jpg', lifestyle: 'lifestyle-tucker-mixedmedia-v2.jpg', beforePrompt: `A casual, candid iPhone SNAPSHOT of a Golden Retriever PUPPY with a fluffy pale-gold coat, floppy ears, and a soft hopeful expression. NOT a professional photo: the puppy sits on a kitchen floor looking UP at the phone with a toy near its paws, a little clumsy and off-balance, ears askew. Imperfect amateur framing shot from above, slightly off-centre, flat ordinary kitchen lighting, faint phone-camera softness. The kind of quick photo a real owner snaps. A genuine photograph, no illustration, no text, no border.`, afterPrompt: painterlyOil('SUBJECT: a Golden Retriever puppy with a fluffy pale-gold coat, floppy ears, dark soulful eyes, and the exact hopeful "I want something" look.'), frame: CANVAS_FLOAT, scene: 'a sunlit modern living room with a cream linen sofa, a warm-oak coffee table with a small stack of art books, and soft daylight from a tall window — the framed canvas hangs on a soft warm-white wall above the sofa', }, { id: 'gus', before: 'before-gus.jpg', after: 'after-gus-popart-v2.jpg', lifestyle: 'lifestyle-gus-popart-v2.jpg', beforePrompt: `A casual, candid iPhone SNAPSHOT of a Pembroke Welsh Corgi with the classic red-and-white coat, big upright ears, and a huge happy open-mouth grin with the tongue out. NOT a professional photo: the corgi stands on a sunny backyard patio caught mid-trot, body at an angle, looking off-frame, a bit of motion blur. Imperfect amateur framing, off-centre, harsh midday outdoor light. The kind of quick photo a real owner snaps. A genuine photograph, no illustration, no text, no border.`, afterPrompt: popArt('SUBJECT: a Pembroke Welsh Corgi with the classic red-and-white coat, big upright ears, and a joyful open-mouth grin — the most ridiculous, happy dog alive.'), frame: WHITE_MAT, scene: 'a bright, cheerful breakfast nook with a round white table, two pale-wood chairs, and crisp morning sunlight — the framed artwork hangs on a clean white wall', }, // ─── Befores-only for the remaining 3 testimonials (Daniel/Marcus/Sasha&Lee). // Their portraits already exist on the CDN; we just need casual snapshots // to pair them with, matching Hannah/Renee. Run with STAGES=before. { id: 'willow', before: 'before-willow.jpg', after: '', lifestyle: '', afterPrompt: '', frame: '', scene: '', beforePrompt: `A casual, candid iPhone SNAPSHOT of an adult Border Collie with the classic black-and-white coat — black mask with a slim white blaze down the muzzle, white chest and paws, a feathered black-and-white tail. The dog stands alert on a grassy lawn in soft afternoon light, in a 3/4 turn looking AT the camera with ears up, mouth slightly open, tongue just visible — clearly mid-play, not lying down. NOT a professional photo: a little off-centre, slightly tilted horizon, ordinary outdoor light, a hint of phone-camera softness. The kind of quick photo a real owner snaps. A genuine photograph, no illustration, no text, no border.`, }, { id: 'nova', before: 'before-nova.jpg', after: '', lifestyle: '', afterPrompt: '', frame: '', scene: '', beforePrompt: `A casual, candid iPhone SNAPSHOT of an adult Bernese Mountain Dog — the classic tricolour coat (jet-black body, rust-brown cheeks and legs, crisp white blaze down the muzzle, white chest), a big square head, and dark expressive eyes. The dog lies sprawled on his side on a hardwood floor at home, half on a rug, looking sleepy and lazy with one ear flopped down, paws relaxed, clearly resting NOT posed. NOT a professional photo: shot from a low angle, slightly off-centre, ordinary warm indoor lamp light. The kind of quick photo a real owner snaps. A genuine photograph, no illustration, no text, no border.`, }, { id: 'waffle', before: 'before-waffle.jpg', after: '', lifestyle: '', afterPrompt: '', frame: '', scene: '', beforePrompt: `A casual, candid iPhone SNAPSHOT of a Standard Smooth-Coat Dachshund with the classic red-mahogany coat, long body and stubby legs, long floppy ears, and a long pointed muzzle with a glossy black nose. The dog is curled up nose-to-tail asleep on a tan corduroy couch cushion, eyes mostly closed, ears draped over the cushion edge, a small striped blanket nearby. NOT a professional photo: shot from above at a slight angle, slightly off-centre, soft warm window light. The kind of quick photo a real owner snaps. A genuine photograph, no illustration, no text, no border.`, }, ]; async function gemini({ prompt, refPath, aspect }) { const parts = [{ text: prompt }]; if (refPath) { const bytes = fs.readFileSync(refPath); parts.push({ inline_data: { mime_type: refPath.endsWith('.png') ? 'image/png' : 'image/jpeg', 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(); for (const part of (json?.candidates?.[0]?.content?.parts ?? [])) { const data = part?.inline_data?.data ?? part?.inlineData?.data; if (data) return Buffer.from(data, 'base64'); } throw new Error('no image data'); } catch (e) { lastErr = e; if (attempt < 2) await new Promise(r => setTimeout(r, 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); console.log(` ✓ ${outName} (${Math.round(fs.statSync(outPath).size / 1024)} 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 (casual snapshot)…`); await saveJpeg(await gemini({ prompt: pet.beforePrompt, aspect: '3:4' }), pet.before, { maxW: 1500, maxH: 2000, quality: 86 }); } if (STAGES.has('after')) { if (!fs.existsSync(beforePath)) throw new Error(`missing ${pet.before}`); console.log(` [${pet.id}] after (hero portrait, re-posed)…`); await saveJpeg(await gemini({ prompt: pet.afterPrompt, refPath: beforePath, aspect: '1:1' }), pet.after, { maxW: 2048, maxH: 2048, quality: 94 }); } if (STAGES.has('lifestyle')) { if (!fs.existsSync(afterPath)) throw new Error(`missing ${pet.after}`); console.log(` [${pet.id}] lifestyle (framed)…`); await saveJpeg(await gemini({ prompt: lifestylePrompt(pet.frame, pet.scene), refPath: afterPath, aspect: '1:1' }), 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}\nPets: ${targets.map(p => p.id).join(', ')}\nStages: ${[...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 succeeded.`); process.exit(fails ? 1 : 0);