Branchwell

Lumen & Gesso / website · lumengesso.com / scripts / generate-hugo-landscape.mjs

Raw 5.7 KB on f4d070c0cd6547ed6432bda0f7f1dc2cb2181b18
1#!/usr/bin/env node
2// One-off: create a NEW dog (Hugo, a Hungarian Vizsla) and render the
3// catalog example for the Landscape style.
4//
5// Step 1 before-hugo.jpg — a candid "phone snap" reference
6// photo (text-to-image), the kind
7// a customer would upload.
8// Step 2 after-hugo-landscape-oil.png — that dog rendered through the
9// canonical LANDSCAPE_OIL prompt
10// (image-to-image), the catalog tile.
11//
12// Both steps run on gemini-3-pro-image (Nano Banana Pro) — it
13// renders the classical-oil landscape noticeably richer than gpt-image-2,
14// and matches the other painterly catalog tiles. Output is left at the
15// model's default (~1024²), matching every other after-*.png tile.
16//
17// The Landscape prompt is read straight out of app/data/portraitPrompts.ts
18// so the example always reflects the live style definition.
19//
20// Usage: GEMINI_API_KEY in .env.local (auto-loaded), then:
21// node scripts/generate-hugo-landscape.mjs
22
23import fs from 'node:fs';
24import path from 'node:path';
25import { fileURLToPath } from 'node:url';
26
27const __dirname = path.dirname(fileURLToPath(import.meta.url));
28const ROOT = path.resolve(__dirname, '..');
29
30function loadEnvLocal() {
31 const p = path.join(ROOT, '.env.local');
32 if (!fs.existsSync(p)) return;
33 for (const raw of fs.readFileSync(p, 'utf8').split('\n')) {
34 const line = raw.trim();
35 if (!line || line.startsWith('#')) continue;
36 const eq = line.indexOf('=');
37 if (eq < 0) continue;
38 const key = line.slice(0, eq).trim();
39 let val = line.slice(eq + 1).trim();
40 if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
41 val = val.slice(1, -1);
42 }
43 if (!(key in process.env)) process.env[key] = val;
44 }
45}
46loadEnvLocal();
47
48const GEMINI_KEY = process.env.GEMINI_API_KEY;
49if (!GEMINI_KEY) {
50 console.error('GEMINI_API_KEY not set (looked in env + .env.local)');
51 process.exit(1);
52}
53
54const MODEL = 'gemini-3-pro-image';
55const PORTRAITS = path.resolve(ROOT, 'public/portraits');
56const BEFORE_PATH = path.join(PORTRAITS, 'before-hugo.jpg');
57const AFTER_PATH = path.join(PORTRAITS, 'after-hugo-landscape-oil.png');
58
59// New dog: Hugo, a Hungarian Vizsla — warm rust coat that glows in the
60// classical autumn-landscape palette.
61const BEFORE_PROMPT =
62 `A natural, candid pet photograph — the kind a customer would casually snap with their phone. ` +
63 `Composition: head-and-shoulders to bust crop, the subject occupying roughly the centre 60-75% of a square frame with comfortable margin on all four sides. ` +
64 `Subject: a Hungarian Vizsla dog sitting calmly outdoors, sleek short golden-rust coat, long velvety drop ears, soft amber eyes looking directly at the camera, gentle alert expression, a little wet nose, warm late-afternoon golden-hour light, blurred green lawn and a few trees softly out of focus behind. ` +
65 `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. ` +
66 `Aspect ratio: square (1:1).`;
67
68// Pull the live LANDSCAPE_OIL prompt out of the TS module as plain text
69// (no TS runtime needed) so this example tracks the real style definition.
70function extractConst(name) {
71 const ts = fs.readFileSync(path.join(ROOT, 'app/data/portraitPrompts.ts'), 'utf8');
72 const m = ts.match(new RegExp('const ' + name + ' = `([\\s\\S]*?)`;', 'm'));
73 if (!m) throw new Error('Could not find prompt const: ' + name);
74 return m[1];
75}
76
77function pickImageB64(json) {
78 const parts = json?.candidates?.[0]?.content?.parts ?? [];
79 for (const part of parts) {
80 const data = part?.inline_data?.data ?? part?.inlineData?.data;
81 if (data) return data;
82 }
83 return null;
84}
85
86async function gemini(parts, label) {
87 const body = {
88 contents: [{ parts }],
89 generationConfig: { responseModalities: ['image', 'text'] },
90 };
91 const url = `https://generativelanguage.googleapis.com/v1beta/models/${MODEL}:generateContent`;
92 console.log(`→ ${label} (${MODEL})`);
93 const r = await fetch(url, {
94 method: 'POST',
95 headers: { 'x-goog-api-key': GEMINI_KEY, 'content-type': 'application/json' },
96 body: JSON.stringify(body),
97 });
98 if (!r.ok) {
99 const text = await r.text();
100 throw new Error(`${r.status} ${r.statusText}: ${text.slice(0, 600)}`);
101 }
102 const b64 = pickImageB64(await r.json());
103 if (!b64) throw new Error('No image data in Gemini response');
104 return Buffer.from(b64, 'base64');
105}
106
107// Sniff the real container so the reference mime is honest regardless of
108// the .jpg extension.
109function mimeOf(buf) {
110 if (buf[0] === 0x89 && buf[1] === 0x50) return 'image/png';
111 return 'image/jpeg';
112}
113
114// ─── Step 1: the new dog's reference photo ──────────────────────────
115const beforeBuf = await gemini([{ text: BEFORE_PROMPT }], 'before-hugo.jpg — candid Vizsla reference');
116fs.writeFileSync(BEFORE_PATH, beforeBuf);
117console.log(` ✓ ${path.relative(ROOT, BEFORE_PATH)} (${beforeBuf.length.toLocaleString()} bytes)`);
118
119// ─── Step 2: the Landscape-style catalog example ────────────────────
120const LANDSCAPE_OIL = extractConst('LANDSCAPE_OIL');
121const afterBuf = await gemini(
122 [
123 { text: LANDSCAPE_OIL },
124 { inline_data: { mime_type: mimeOf(beforeBuf), data: beforeBuf.toString('base64') } },
125 ],
126 'after-hugo-landscape-oil.png — Landscape style render',
127);
128fs.writeFileSync(AFTER_PATH, afterBuf);
129console.log(` ✓ ${path.relative(ROOT, AFTER_PATH)} (${afterBuf.length.toLocaleString()} bytes)`);
130
131console.log('\nDone.');