Branchwell

Lumen & Gesso / website · lumengesso.com / app / lib / image-gen.ts

1import 'server-only';
2import { PORTRAIT_PROMPTS } from '@/app/data/portraitPrompts';
3import { STYLE_CATALOG, type PortraitPromptId } from '@/app/data/styleCatalog';
4import { GEMINI_IMAGE_MODEL, type ImageModel } from './image-models';
5
6// ─── Aspect ratio (frame-shape-aware generation) ─────────────────────
7//
8// Frames are square or portrait (see PRODUCTS in pricing.ts: 1/1, 4/5,
9// 3/4, 2/3, 11/14, 5/7, 5/6). Rather than always generating a square and
10// cropping (which loses composition control), we generate natively in
11// the frame's shape so the model composes for the real canvas. Each
12// model supports a limited set of output shapes, so we snap the frame
13// aspect to the nearest the model can do and let cropToAspect() finish
14// to the EXACT frame ratio (so the printed file always matches the frame).
15// • Gemini imageConfig.aspectRatio — 1:1 / 4:5 / 3:4 / 2:3 cover our
16// portrait frames; the model supports more.
17// • This app requests 1024x1024 (square), 1024x1536 (2:3 portrait),
18// or 1536x1024 (landscape) for OpenAI. Portrait frames snap to
19// 2:3 then crop.
20
21export type GeminiAspect = '1:1' | '4:5' | '3:4' | '2:3' | '5:4' | '4:3' | '3:2';
22export type OpenAiSize = '1024x1024' | '1024x1536' | '1536x1024';
23
24export type AspectSpec = {
25 /** The customer's frame aspect as a clean label, e.g. '3:4'. */
26 label: string;
27 orientation: 'square' | 'portrait' | 'landscape';
28 /** Nearest Gemini-supported aspectRatio. */
29 gemini: GeminiAspect;
30 /** Nearest OpenAI size. */
31 openaiSize: OpenAiSize;
32};
33
34const GEMINI_PORTRAIT: ReadonlyArray<readonly [GeminiAspect, number]> = [['4:5', 0.8], ['3:4', 0.75], ['2:3', 2 / 3]];
35const GEMINI_LANDSCAPE: ReadonlyArray<readonly [GeminiAspect, number]> = [['5:4', 1.25], ['4:3', 4 / 3], ['3:2', 1.5]];
36
37function nearestGemini(cands: ReadonlyArray<readonly [GeminiAspect, number]>, ratio: number): GeminiAspect {
38 let best = cands[0];
39 for (const c of cands) if (Math.abs(c[1] - ratio) < Math.abs(best[1] - ratio)) best = c;
40 return best[0];
41}
42
43/** Map a frame aspect string ('W / H' from pricing.ts, e.g. '3 / 4') to
44 * the nearest model-supported output shapes. Defaults to square on
45 * empty / unparseable input. */
46export function aspectSpecFromFrame(aspectStr: string | null | undefined): AspectSpec {
47 const square: AspectSpec = { label: '1:1', orientation: 'square', gemini: '1:1', openaiSize: '1024x1024' };
48 if (!aspectStr) return square;
49 const m = aspectStr.match(/^\s*(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)\s*$/);
50 if (!m) return square;
51 const w = parseFloat(m[1]);
52 const h = parseFloat(m[2]);
53 if (!(w > 0) || !(h > 0)) return square;
54 const ratio = w / h;
55 const label = `${m[1]}:${m[2]}`;
56 if (Math.abs(ratio - 1) < 0.02) return { ...square, label };
57 if (ratio < 1) return { label, orientation: 'portrait', gemini: nearestGemini(GEMINI_PORTRAIT, ratio), openaiSize: '1024x1536' };
58 return { label, orientation: 'landscape', gemini: nearestGemini(GEMINI_LANDSCAPE, ratio), openaiSize: '1536x1024' };
59}
60
61/** Short, authoritative output-shape directive, prepended to a prompt so
62 * the model composes for the frame instead of a square. */
63export function aspectDirective(spec: AspectSpec): string {
64 if (spec.orientation === 'square') {
65 return 'OUTPUT FORMAT: 1:1 square (equal width and height). Fill the canvas edge to edge.';
66 }
67 const dir = spec.orientation === 'portrait' ? 'taller than wide' : 'wider than tall';
68 return [
69 `OUTPUT FORMAT: ${spec.label} ${spec.orientation} — ${dir}. Compose for this exact shape, NOT a square.`,
70 'Fill the frame edge to edge with no letterbox bars, padding, or empty margins. Keep the pet whole, with its head and eyes safely inside the frame (head/eyes about a quarter to a third down from the top).',
71 ].join(' ');
72}
73
74/** Re-shape a square-canonical prompt for a non-square frame: swap the
75 * literal "1:1 / square" composition phrases for the frame aspect and
76 * prepend the directive. No-op for square frames (the canonical prompts
77 * are already square). */
78export function withAspect(prompt: string, spec: AspectSpec): string {
79 if (spec.orientation === 'square') return prompt;
80 const shaped = prompt
81 .replace(/1:1 square aspect ratio(?: \(equal width and height\))?\.?/gi, `${spec.label} ${spec.orientation} aspect ratio — fill it edge to edge, no bars or padding`)
82 .replace(/\bSquare 1:1 canvas\b/g, `${spec.label} ${spec.orientation} canvas`)
83 .replace(/\bsquare 1:1\b/gi, `${spec.label} ${spec.orientation}`);
84 return aspectDirective(spec) + '\n\n' + shaped;
85}
86
87/** AI-facing descriptions of each font option (the Builder's FONTS dict
88 * is a CSS-only client construct; the model needs a stylistic
89 * description instead of a font-family name it can't load). Keys must
90 * stay in sync with the FontId set in Builder.tsx. */
91export type LetteringFontId = 'modern' | 'editorial' | 'display' | 'italic' | 'serif' | 'script' | 'hand' | 'soft';
92
93const FONT_DESCRIPTIONS: Record<LetteringFontId, { description: string; uppercase: boolean; label: string }> = {
94 modern: { description: 'a tracked-out modern geometric sans-serif (DM Sans-style), medium weight, generous letterspacing', uppercase: true, label: 'Modern' },
95 editorial: { description: 'a refined classical serif (Newsreader-style), medium weight, with subtle letterspacing', uppercase: true, label: 'Editorial' },
96 display: { description: 'a tall, thin display serif (Italiana-style), light weight, with airy letterspacing', uppercase: true, label: 'Display' },
97 italic: { description: 'a flowing italic classical serif (Cormorant Garamond italic-style), elegant and unhurried', uppercase: false, label: 'Italic' },
98 serif: { description: 'a classic high-contrast serif (Playfair Display-style), gracious and editorial', uppercase: false, label: 'Classic' },
99 script: { description: 'an elegant looping cursive script (Pinyon Script-style), flowing and delicate', uppercase: false, label: 'Script' },
100 hand: { description: 'a relaxed handwritten marker (Caveat-style), warm and personal', uppercase: false, label: 'Handwritten' },
101 soft: { description: 'a soft rounded modern sans-serif (Outfit-style), friendly and contemporary', uppercase: false, label: 'Soft sans' },
102};
103
104/** Look up the human-readable label for a font id, or null if unknown. */
105export function letteringFontLabel(fontId: string | null | undefined): string | null {
106 if (!fontId) return null;
107 return FONT_DESCRIPTIONS[fontId as LetteringFontId]?.label ?? null;
108}
109
110/** Prepend the customer's free-text note to the artist as an explicit
111 * request the model should honour. The Builder collects this on every
112 * order (catalog and custom style), but until now only the Gemini
113 * custom-style prompt actually read it — every other path silently
114 * dropped it. No-op for null / blank. */
115export function withArtistNote(
116 prompt: string,
117 note: string | null | undefined,
118): string {
119 const trimmed = (note ?? '').trim();
120 if (!trimmed) return prompt;
121 const directive = [
122 `CUSTOMER NOTE — read carefully: "${trimmed}"`,
123 `Honour this request where it does not conflict with keeping the pet recognisable or with the base style direction below. Treat it as the customer's voice on what matters most for THIS portrait.`,
124 ].join('\n');
125 return directive + '\n\n' + prompt;
126}
127
128/** Inject lettering instructions into a prompt when the customer asked
129 * for their pet's name on the artwork. Like the background colour: the
130 * original design had the name composited in post-process, but that
131 * step was never wired up — the AI is the only thing that can put
132 * pixels into the print file. This directive overrides every "no text /
133 * no lettering" instruction in the base prompts so the AI actually
134 * renders the name. No-op when there's no name, no font, includeName
135 * is false, or the font id isn't one we know. */
136export function withLettering(
137 prompt: string,
138 lettering: { name: string | null; fontId: string | null; include: boolean } | null | undefined,
139): string {
140 if (!lettering || !lettering.include) return prompt;
141 const name = (lettering.name ?? '').trim();
142 if (!name) return prompt;
143 const font = FONT_DESCRIPTIONS[lettering.fontId as LetteringFontId];
144 if (!font) return prompt;
145 const displayName = font.uppercase ? name.toUpperCase() : name;
146 const casing = font.uppercase ? 'ALL CAPS' : 'the casing shown';
147 const directive = [
148 `NAME LETTERING — strict: render the pet's name "${displayName}" (${casing}) across the upper area of the canvas in ${font.description}.`,
149 `Place the name horizontally centred in the top ~20% of the canvas, comfortably above the pet's head with breathing room on all sides. The text must be CLEAN, CRISP typography — properly kerned, properly proportioned, perfectly readable — NEVER hand-painted by the artist, NEVER stylised as part of the artwork, NEVER warped, distorted, or misspelled. The name is the ONLY text in the image; no signatures, captions, or other lettering. This overrides every other instruction in the prompt about "no text", "no letters", "no lettering", "no typography", or about leaving the top of the canvas blank.`,
150 ].join('\n');
151 return directive + '\n\n' + prompt;
152}
153
154/** Substitute {{BG_HEX}} / {{BG_LABEL}} placeholders inside a prompt with
155 * the customer's chosen background colour. Used by both defaultPromptFor
156 * (OpenAI prose briefs) and geminiPromptFor (Gemini ingredient prompts).
157 * When bg is null/undefined (catalog styles like cubist that carry their
158 * own ground and have no placeholders), this is a no-op; when bg is
159 * set, every placeholder occurrence is replaced. */
160function substituteBackground(prompt: string, bg: { hex: string; label: string } | null | undefined): string {
161 if (!bg) {
162 // Defensive fallback: any prompt that does contain placeholders but
163 // was called without a bg gets a sensible white default rather than
164 // shipping literal "{{BG_HEX}}" text to the model.
165 return prompt
166 .replace(/\{\{BG_HEX\}\}/g, '#FFFFFF')
167 .replace(/\{\{BG_LABEL\}\}/g, 'white');
168 }
169 return prompt
170 .replace(/\{\{BG_HEX\}\}/g, bg.hex)
171 .replace(/\{\{BG_LABEL\}\}/g, bg.label);
172}
173
174export function defaultPromptFor(
175 styleId: string,
176 name: string | null,
177 bg?: { hex: string; label: string } | null,
178): string {
179 const entry = PORTRAIT_PROMPTS.find(p => p.id === styleId);
180 if (!entry) return '';
181 return substituteBackground(
182 entry.prompt.replace(/\{\{NAME\}\}/g, name ?? ''),
183 bg,
184 );
185}
186
187/** Marker used by both customStyleStarterPrompt and the admin editor to
188 * splice/replace a style-description block inside the prompt text. Keep
189 * this stable — the editor's Analyze button does a find-and-replace on
190 * this exact header so re-analyses don't stack. */
191export const STYLE_REFERENCE_BLOCK_MARKER = '## STYLE REFERENCE (from your uploaded image)';
192
193/** Starter prompt for custom-style commissions. The customer uploaded
194 * a style reference; this prompt instructs the model to render their
195 * pet in that reference's style. Admin still edits to taste before
196 * generating.
197 *
198 * On Gemini the style image is sent alongside as a final reference
199 * part — the positional instructions header (built by
200 * buildReferenceHeader) is prepended automatically by generateImage().
201 *
202 * On OpenAI the style image CAN'T travel — /images/edits accepts subject
203 * photos but no separate style image. The admin clicks "Analyze style" which calls
204 * GPT-4o Vision to describe the style, and that description is
205 * injected here as the STYLE_REFERENCE_BLOCK_MARKER section. When
206 * styleDescription is omitted, the section is omitted too. */
207export function customStyleStarterPrompt(name: string | null, styleDescription?: string | null): string {
208 const named = name ? ` titled "${name}" hand-lettered above` : '';
209 const lines = [
210 'Render a portrait of the pet shown in the SUBJECT reference (image 1) in the visual style of the STYLE reference (image 2).',
211 '',
212 'Subject fidelity — strict:',
213 "- Preserve the pet's breed, coat pattern, markings, eye color, ears, and distinguishing features exactly as shown in image 1.",
214 '- Keep the pet recognizable to its owner. Do not blend in features from the style reference.',
215 '',
216 'Style fidelity — high:',
217 '- Match the medium, brushwork, palette, contrast, line quality, texture, and mood of image 2.',
218 '- If image 2 is a painting, render as a painting in that exact technique. If a photograph, mimic its lighting + grade.',
219 '- Apply the style to the SUBJECT only — do not borrow image 2\'s subject, scenery, or composition unless explicitly instructed below.',
220 '',
221 'Composition:',
222 '- Square 1:1 canvas. Pet head and chest fill the frame, eyes in the upper-middle third.',
223 '- Tight crop; minimal background; the style reference\'s palette informs the background tone if applicable.',
224 `- Portrait hero pose, 3/4 view, dignified and alert${named}.`,
225 '',
226 'The output should feel like the customer\'s pet was painted by the same hand that made the style reference.',
227 ];
228 if (styleDescription && styleDescription.trim()) {
229 lines.push(
230 '',
231 STYLE_REFERENCE_BLOCK_MARKER,
232 'Use the following description (generated by analyzing the uploaded style reference) as your primary guide to the style, especially when generating via OpenAI image-edit which only sees the subject photo.',
233 '',
234 styleDescription.trim(),
235 );
236 }
237 return lines.join('\n');
238}
239
240// ─── Gemini ("Nano Banana") prompt builders ──────────────────────────
241//
242// Gemini Nano Banana Pro responds better to short, structured, plain-
243// language direction than to the long prose briefs we feed gpt-image-2.
244// So when the admin generates on Gemini we DON'T reuse the OpenAI image
245// prompt — we build a separate "ingredient" prompt: a compact base
246// (the basics every L&G portrait needs — subject fidelity, composition,
247// a clean surround) with the per-style "ingredients" (the essence of
248// the look, distilled from the full briefs in portraitPrompts.ts)
249// slotted in. For custom-style orders the "ingredients" are the
250// customer-uploaded style reference itself — Gemini sees it directly as
251// image 2 — so that variant leans on the image and just supplies the
252// basics plus any artist note. Nothing here overrides the pet's
253// identity or the reference.
254
255/** Per-style essence injected into the Gemini base template. Distilled
256 * from the full briefs in portraitPrompts.ts — kept tight on purpose
257 * (Gemini does better with concise direction). The lettering variants
258 * (…-plain / named) reuse their base style's ingredients. */
259const GEMINI_STYLE_INGREDIENTS: Record<PortraitPromptId, string> = {
260 watercolor:
261 'soft, flowing watercolour painting — gentle wet-on-wet colour bleeds, loose expressive brushwork, light luminous palette, edges fading softly into the ground. Background is a solid uniform fill of {{BG_HEX}} ({{BG_LABEL}}) with no paper texture, no gradient, no tint variation; only the pet carries watercolour.',
262 lineart:
263 'refined black pen-and-ink line drawing — confident deliberate ink strokes, layered contour lines and directional hatching following the fur, richly detailed eyes. The ONLY dark pixels are the black ink lines; every other pixel is a uniform fill of {{BG_HEX}} ({{BG_LABEL}}). No colour fills, no shading except hatching, no second tint anywhere in the surround.',
264 'lineart-plain':
265 'refined black pen-and-ink line drawing — confident deliberate ink strokes, layered contour lines and directional hatching following the fur, richly detailed eyes. The ONLY dark pixels are the black ink lines; every other pixel is a uniform fill of {{BG_HEX}} ({{BG_LABEL}}). No colour fills, no shading except hatching, no second tint anywhere in the surround.',
266 cubist:
267 'Picasso-style cubist portrait — fracture the pet into geometric planes and overlapping facets showing several viewpoints at once, bold black contour lines, flat painterly colour fields, oil-on-canvas texture. Restrained earthy palette (ochre, terracotta, muted blue/green, bone) with one sparing saturated accent. Quiet near-flat hand-painted colour-field background.',
268 ukiyoe:
269 'Japanese ukiyo-e woodblock print — bold sumi-black key-block outlines, flat colour fields with bokashi (graduated washes), visible woodgrain and washi paper texture. Indigo / sumi / persimmon / vermilion / mineral-green / mustard palette. Traditional woodblock backdrop with subtle bokashi; no florals, no kanji or seal stamps.',
270 thangka:
271 'Tibetan thangka painting — fine calligraphic mineral-pigment outlines, flat saturated colour with layered tonal washes, generous gold-leaf accents and a soft gold nimbus behind the head. Lapis, vermilion, malachite, gold, ochre palette. Richly painted ground with scrolling clouds and snow peaks. Include the mantra "Om Mani Padme Hum" in formal Tibetan Uchen script in a single cartouche along the bottom — the only text in the image.',
272 mixedmedia:
273 '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.',
274 charcoal:
275 'hand-drawn charcoal portrait — dry compressed charcoal, vine charcoal and graphite, confident hatching with smudged shadow transitions, deep velvety blacks in the eyes and nose, highlights left as the ground colour showing through. Background is a uniform solid fill of {{BG_HEX}} ({{BG_LABEL}}) with no paper texture, no gradient; only the charcoal/graphite marks carry pixels darker than the ground.',
276 'charcoal-plain':
277 'hand-drawn charcoal portrait — dry compressed charcoal, vine charcoal and graphite, confident hatching with smudged shadow transitions, deep velvety blacks in the eyes and nose, highlights left as the ground colour showing through. Background is a uniform solid fill of {{BG_HEX}} ({{BG_LABEL}}) with no paper texture, no gradient; only the charcoal/graphite marks carry pixels darker than the ground.',
278 vector:
279 'highly detailed vector illustration — many flat, hard-edged colour shapes, a posterised palette of 18–25 tones, fur built from many small directional tuft shapes, crisp dark outlines on the silhouette and every internal boundary, layered eye and nose detail. No gradients, no airbrushing. Surround is a single uniform fill of {{BG_HEX}} ({{BG_LABEL}}); the bold black keyline around the pet defines its silhouette against the ground.',
280 'vector-plain':
281 'highly detailed vector illustration — many flat, hard-edged colour shapes, a posterised palette of 18–25 tones, fur built from many small directional tuft shapes, crisp dark outlines on the silhouette and every internal boundary, layered eye and nose detail. No gradients, no airbrushing. Surround is a single uniform fill of {{BG_HEX}} ({{BG_LABEL}}); the bold black keyline around the pet defines its silhouette against the ground.',
282 popart:
283 '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.',
284 risograph:
285 'risograph screen-print in 2–3 inks — flat overlapping ink fields, coarse halftone-dot shading, a 1–2px registration offset, bold dark contour outlines, faint paper-fibre texture. One saturated ink ground (teal / magenta / mustard / persimmon / cobalt / sumi-black) plus one geometric corner motif bleeding off two edges. No floral motifs.',
286 athome:
287 'a bright, bubbly, joyful 1978 disco-era Kodachrome photograph of the pet inside a glossy late-1970s kitchen — avocado-green fridge, harvest-gold Formica, checkerboard linoleum, a bubbling lava lamp, a disco ball, daisy/smiley wallpaper, chrome accents. Saturated optimistic colour, bright well-exposed daylight, only a hint of fine film grain. The pet must read as a REAL photographed pet (real fur and eyes), sharp hero in focus. NO distress/scratches/light-leaks, no modern objects, no people in frame.',
288 neoexpressionist:
289 'a raw Basquiat-inspired neo-expressionist graffiti-on-canvas painting — thick wobbly black contour, layered slabs of saturated paint (hot pink, cobalt, cadmium yellow, vermilion, cream, black), visible drips and scratched marks. A large signature gold/yellow three-point CROWN floats above the head, plus 2–3 large icons (a capital M/W, an arrow, an X, a halo, a smiley, a heart) — bold and confident, never spelling readable words.',
290 'landscape-oil':
291 'a classical 19th-century oil painting on canvas — confident loaded brushwork following the fur and the forms of the land, soft blended sky, warm broken colour and richer impasto on the coat highlights, glossy expressive eyes. The pet is the foreground hero seated or standing in a soft painterly outdoor landscape — rolling fields or meadow, a few full-foliage trees, distant hills, a luminous golden-hour / early-autumn sky. The landscape carries its own painted ground and gently frames the animal without competing with its face. Heirloom, gallery-painting mood. No text or signature.',
292 named:
293 'a loose, expressive painterly portrait — confident semi-realistic oil/gouache with aggressively visible gestural brushstrokes following the fur; a crisp, detailed face (glossy eyes, clear nose) while the outer fur and lower body feather and dissolve softly INTO the surrounding ground rather than a hard cut-out. Background is a uniform solid fill of {{BG_HEX}} ({{BG_LABEL}}); the upper ~25% stays clean ground so a name can be lettered there via a separate instruction.',
294 'named-plain':
295 'a loose, expressive painterly portrait — confident semi-realistic oil/gouache with aggressively visible gestural brushstrokes following the fur; a crisp, detailed face (glossy eyes, clear nose) while the outer fur and lower body feather and dissolve softly INTO the surrounding ground rather than a hard cut-out. Background is a uniform solid fill of {{BG_HEX}} ({{BG_LABEL}}); the upper ~25% stays clean ground for breathing room.',
296};
297
298/** Composition variants — most styles are a tight bust, but a few need
299 * their own framing (named reserves a top band for lettering; riso
300 * runs full-bleed; neo-expressionist is a standing full body; the
301 * retro photo is a full scene). */
302type GeminiComposition = 'bust' | 'named' | 'fullbleed' | 'standing' | 'scene' | 'landscapescene';
303
304const GEMINI_COMPOSITION_BLOCKS: Record<GeminiComposition, string> = {
305 bust: '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.',
306 named: 'COMPOSITION: square 1:1. The pet sits in the lower two-thirds; keep the upper ~30% a clean, empty band (the pet’s name is lettered there afterwards in post). Crisp detailed face; outer fur and lower body feather softly into the surround.',
307 fullbleed: 'COMPOSITION: square 1:1 with the saturated ink ground running FULL-BLEED to all four edges — no inner frame, border, mat, or paper margin of any kind. Head and eyes in the upper-middle; lower chest fades toward the bottom. Never crop the face.',
308 standing: 'COMPOSITION: square 1:1. STANDING full-body hero pose with all four paws visible, held inside a crop-safe centre with comfortable margin on ALL FOUR sides — nothing touches an edge. Head/ears ~20–30% down; paws ~80–90% down with a floor margin below. The painted ground fills the canvas behind the pet.',
309 scene: 'COMPOSITION: square 1:1 with the kitchen scene filling the frame edge to edge. The pet is the sharp hero in the central third, head and eyes ~25–40% down. Never crop the face.',
310 landscapescene: 'COMPOSITION: square 1:1 with the painted landscape filling the frame edge to edge (no white margin or border). The pet is the foreground hero on the ground plane, head and eyes ~30–45% down, with open landscape above, below, and to both sides. This square is cropped to the customer\'s frame (wide, square, or tall), so keep the WHOLE pet — especially the entire head, ears, eyes, muzzle, and nose — inside a crop-safe centre with generous margin (12–15%) on all four sides; only the surrounding scenery may be trimmed, never the animal.',
311};
312
313const GEMINI_STYLE_COMPOSITION: Partial<Record<PortraitPromptId, GeminiComposition>> = {
314 named: 'named',
315 'named-plain': 'named',
316 risograph: 'fullbleed',
317 neoexpressionist: 'standing',
318 athome: 'scene',
319 'landscape-oil': 'landscapescene',
320};
321
322function geminiBase(styleName: string, ingredients: string, comp: GeminiComposition): string {
323 return [
324 `Recreate the pet (or pets) from the reference photo(s) as a ${styleName} portrait.`,
325 '',
326 'SUBJECT — most important: keep the exact pet (or pets) from the photo(s). Same breed, coat colour and markings, eye colour, ear shape, nose, and distinctive features — each must stay instantly recognizable to its owner. If several pets are provided, include them ALL together in one portrait. Do not blend in another animal or invent features.',
327 '',
328 `STYLE: ${ingredients}`,
329 '',
330 GEMINI_COMPOSITION_BLOCKS[comp],
331 '',
332 'CLEAN OUTPUT: no border, frame, mat, vignette, caption, signature, watermark, or lettering of any kind — just the portrait. Any name is added afterwards in post-process.',
333 ].join('\n');
334}
335
336/** Gemini "ingredient" prompt for a catalog style. Returns '' for an
337 * unknown styleId (mirrors defaultPromptFor). The bg is substituted
338 * into {{BG_HEX}}/{{BG_LABEL}} placeholders for styles whose ingredient
339 * text carries them (the hasSolidBackground set); a no-op for styles
340 * that carry their own painted ground. */
341export function geminiPromptFor(
342 styleId: string,
343 bg?: { hex: string; label: string } | null,
344): string {
345 const ingredients = GEMINI_STYLE_INGREDIENTS[styleId as PortraitPromptId];
346 if (!ingredients) return '';
347 const styleName = STYLE_CATALOG.find(s => s.id === styleId)?.name ?? 'fine-art';
348 const comp = GEMINI_STYLE_COMPOSITION[styleId as PortraitPromptId] ?? 'bust';
349 return substituteBackground(geminiBase(styleName, ingredients, comp), bg);
350}
351
352/** Gemini "ingredient" prompt for a custom-style commission. The
353 * customer's uploaded style reference IS the style ingredient — Gemini
354 * receives it as the final style image (generateImage prepends the
355 * positional header via buildReferenceHeader), so this just supplies
356 * subject fidelity, the composition basics, and the customer's artist
357 * note. */
358export function geminiCustomStylePrompt(artistNote?: string | null): string {
359 const note = (artistNote ?? '').trim();
360 const lines = [
361 'Render the pet from the SUBJECT reference (image 1) in the visual style of the STYLE reference (image 2).',
362 '',
363 'SUBJECT — most important: preserve the exact pet from image 1 — breed, coat colour and markings, eye colour, ears, nose, and distinctive features. Keep it instantly recognizable. Do NOT borrow the subject, pose, or scenery from image 2.',
364 '',
365 'STYLE: study image 2 and match its medium, palette, brushwork, line quality, texture, lighting, and mood. If image 2 is a painting, paint in that exact technique; if it is a photograph, mimic its lighting and grade. Apply that style to the pet only.',
366 '',
367 'COMPOSITION: square 1:1, filled edge to edge. Head and eyes in the upper-middle (about 20–35% down); lower chest fades off the bottom. Never crop the head, ears, eyes, muzzle, or nose.',
368 ];
369 if (note) {
370 lines.push(
371 '',
372 `CUSTOMER REQUEST: "${note}" — honour this where it does not conflict with keeping the pet recognizable.`,
373 );
374 }
375 lines.push(
376 '',
377 'CLEAN OUTPUT: no added border, frame, caption, signature, watermark, or text. Do not override the pet’s identity or the look of the style reference.',
378 );
379 return lines.join('\n');
380}
381
382/** Wrap an admin's free-text tweak ("same but with a red background")
383 * into an edit instruction for the refine loop. The reference image
384 * handed to generateImage in refine mode is a PRIOR generation, so the
385 * prompt's job is to change only what's asked and hold everything else
386 * steady. Works on both engines: OpenAI /images/edits edits the prior
387 * render directly; Gemini gets it as the single reference image. */
388export function buildRefinePrompt(instruction: string): string {
389 return [
390 'Edit the provided image (a finished pet portrait).',
391 `Change ONLY the following: ${instruction.trim()}`,
392 '',
393 "Preserve the pet's identity and all details outside the requested edit. When the edit changes the framing, position, palette, or background, apply that change visibly.",
394 '',
395 'CLEAN OUTPUT: no added border, frame, mat, caption, signature, watermark, or lettering.',
396 ].join('\n');
397}
398
399export function buildCustomerRevisionPrompt(feedback: string, studioNotes: string, spec: AspectSpec, widerFramingPrepared = false): string {
400 return [
401 'Edit the supplied published portrait. The customer’s requested changes are the highest priority for this edit.',
402 '',
403 'CUSTOMER FEEDBACK (verbatim):',
404 feedback.trim(),
405 '',
406 'Apply every requested change, including changes to camera distance, subject size, crop, placement, palette or background. The reference is the starting point, so matching its existing framing is secondary to the requested edit.',
407 widerFramingPrepared
408 ? 'The reference already places the pet farther back on the canvas. Keep the pet at this smaller scale and position. Repaint and blend the outer margins into the surrounding scene across all four edges, with no seams, repeated edge details, or border. Do not enlarge or crop back in on the pet.'
409 : 'If the customer asks to pull back, move the subject farther away, or zoom out, make the pet visibly smaller in the frame and reveal more surrounding scene on all sides. For a slight pullback, aim for about 10–15% less apparent head width than the reference. Adding detail behind the same crop does not accomplish a pullback.',
410 ...(studioNotes.trim() ? ['', 'STUDIO NOTES (only to clarify or implement the customer’s request):', studioNotes.trim(), 'Where these notes conflict with the customer, follow the customer.'] : []),
411 '',
412 'Preserve the pet’s identity, coat markings, eye color, and any style and image details the customer did not ask to change. Keep effects or symbols the customer explicitly requested as part of the artwork.',
413 `OUTPUT: ${spec.label} ${spec.orientation} aspect ratio, artwork edge to edge. No added presentation frame, padding, signature, or watermark.`,
414 'Before rendering, check that the most important requested changes will be easy to see compared with the source.',
415 ].join('\n');
416}
417
418/** OpenAI second-pass prompt for the Gemini→OpenAI chain. OpenAI sees the
419 * freshly-generated Gemini render as its single reference image; this
420 * tells it to finish/refine that image rather than restyle it. */
421export function buildChainRefinePrompt(): string {
422 return [
423 'You are given a finished, stylized pet portrait as the reference image.',
424 "Re-render it preserving the subject's identity, the art style, medium, palette, brushwork, line quality, texture, and composition exactly. Refine detail, edges, and overall finish.",
425 'Do not restyle, recolor, re-pose, or change the background.',
426 '',
427 'Square 1:1. CLEAN OUTPUT: no added border, frame, mat, caption, signature, watermark, or lettering.',
428 ].join('\n');
429}
430
431type GenArgs = {
432 model: ImageModel;
433 prompt: string;
434 /** Subject reference photo bytes (PNG/JPEG) and mime type — the pet.
435 * For a multi-pet commission this is the FIRST pet (image 1); the rest
436 * travel in additionalSubjectReferences. */
437 referenceBytes: Buffer;
438 referenceMime: 'image/png' | 'image/jpeg';
439 /**
440 * Extra SUBJECT photos (pets 2..N) for a multi-pet commission. The
441 * customer can upload up to four pets and we combine them into one
442 * portrait. Empty / omitted for the common single-pet order. Gemini
443 * receives each as its own inline_data part; OpenAI as additional
444 * image[] entries. The positional reference header (built in
445 * generateImage) tells the model that each image is a different pet to
446 * render together.
447 */
448 additionalSubjectReferences?: Array<{ bytes: Buffer; mime: 'image/png' | 'image/jpeg' }>;
449 /**
450 * Optional display names for the subjects, image 1..N — used only to
451 * label each pet inside the positional reference header (e.g. 'Image 1
452 * = "Bella"'). Missing / blank entries fall back to a generic label.
453 */
454 subjectLabels?: string[];
455 /**
456 * Optional STYLE reference image — when the customer paid for a
457 * custom-style commission they uploaded a painting / photo / reference
458 * whose visual style we should mimic. Gemini accepts this as a second
459 * inline_data part; OpenAI's /images/edits is single-image so the
460 * style ref is silently ignored on that path (admin should pick the
461 * Gemini model when a custom style is attached).
462 */
463 styleReferenceBytes?: Buffer;
464 styleReferenceMime?: 'image/png' | 'image/jpeg';
465 /** OpenAI only — defaults to 1024x1024. */
466 size?: OpenAiSize;
467 /**
468 * Gemini only — output aspect ratio (imageConfig.aspectRatio).
469 * Defaults to '1:1'. Set from the customer's frame so the render is
470 * composed for the real canvas shape; OpenAI uses `size` instead.
471 */
472 aspectRatio?: GeminiAspect;
473 /**
474 * Gemini Nano Banana Pro only — output resolution tier. The API
475 * defaults to '1K' (1024×1024) when omitted.
476 * '2K' = 2048×2048 (~4× pixels, ~2× cost, ~2× latency vs 1K).
477 * '4K' = 4096×4096 (~16× pixels, ~4× cost, ~4× latency vs 1K).
478 * Customer-facing renders always pass '4K' (the print file IS the
479 * approved preview — see the generate route). Only drop to 1K/2K for
480 * throwaway experiments where speed/cost matters more than detail.
481 */
482 geminiImageSize?: '1K' | '2K' | '4K';
483};
484
485/** Build the positional-reference header prepended to a prompt when more
486 * than one image is attached, so the model knows what each indexed image
487 * is. Covers three shapes:
488 * • 1 subject, no style → '' (a lone pet photo needs no header).
489 * • 1 subject + style → the classic two-image SUBJECT/STYLE split.
490 * • N subjects (+ style) → each image 1..N is a DIFFERENT pet to render
491 * together in one portrait; the style ref (if any) is the last image.
492 * subjectLabels[i] optionally names image i+1 (e.g. the pet's name). */
493function buildReferenceHeader(
494 subjectCount: number,
495 hasStyleRef: boolean,
496 subjectLabels?: string[],
497): string {
498 if (subjectCount <= 1 && !hasStyleRef) return '';
499
500 const lines: string[] = [];
501 const label = (i: number) => {
502 const name = subjectLabels?.[i]?.trim();
503 return name ? ` — "${name}"` : '';
504 };
505
506 if (subjectCount <= 1) {
507 // Single subject + style reference — the original two-image case.
508 lines.push(
509 'You are given TWO reference images.',
510 ` • Image 1 = SUBJECT reference${label(0)}: the pet to portray. Preserve breed, markings, eye color, and identifying features faithfully.`,
511 ' • Image 2 = STYLE reference: the visual style/medium/mood to render in. Mimic its palette, brushwork, texture, composition, and overall aesthetic — but apply that style to the SUBJECT from image 1, not to any subject in image 2.',
512 );
513 } else {
514 // Multiple subjects (multi-pet commission). Enumerate each pet, then
515 // the optional style ref as the final image.
516 const total = subjectCount + (hasStyleRef ? 1 : 0);
517 lines.push(`You are given ${total} reference images.`);
518 for (let i = 0; i < subjectCount; i++) {
519 lines.push(` • Image ${i + 1} = SUBJECT reference${label(i)}: one pet to include in the portrait.`);
520 }
521 lines.push(
522 `Images 1–${subjectCount} are ${subjectCount} DIFFERENT pets. Render ALL of them TOGETHER in ONE unified portrait — naturally grouped side by side, each pet clearly recognizable from its own photo, at realistic relative scale. Do NOT blend them into a single animal and do NOT drop any pet.`,
523 );
524 if (hasStyleRef) {
525 lines.push(
526 ` • Image ${total} = STYLE reference: the visual style/medium/mood to render in. Mimic its palette, brushwork, texture, composition, and overall aesthetic — apply that style to the pets from images 1–${subjectCount}, not to any subject in the style image.`,
527 );
528 }
529 }
530 lines.push('The prompt below is additional guidance on top of these references.', '');
531 return lines.join('\n') + '\n';
532}
533
534/** Generate an image. Returns the raw PNG/JPEG bytes from the model. */
535export async function generateImage(args: GenArgs): Promise<Buffer> {
536 if (args.model === GEMINI_IMAGE_MODEL) {
537 return generateViaGemini(args);
538 }
539 return generateViaOpenAI(args);
540}
541
542async function generateViaOpenAI(args: GenArgs): Promise<Buffer> {
543 const key = process.env.OPENAI_API_KEY;
544 if (!key) throw new Error('OPENAI_API_KEY not set');
545
546 if (args.styleReferenceBytes) {
547 console.warn('[image-gen] OpenAI /images/edits does not accept a separate STYLE reference image — it will NOT be sent. Switch model to Gemini for full custom-style support (or use Analyze style to inject a text description).');
548 }
549
550 // Subject photos: the primary pet plus any additional pets (multi-pet
551 // commission). OpenAI's image-edit endpoint takes multiple subject
552 // images via repeated image[] fields, so all pets reach the model.
553 const subjects = [
554 { bytes: args.referenceBytes, mime: args.referenceMime },
555 ...(args.additionalSubjectReferences ?? []),
556 ];
557
558 // Tell the model what each attached image is when there's more than one.
559 // OpenAI never receives the style ref, so the header only describes the
560 // subject pets (hasStyleRef = false here).
561 const header = buildReferenceHeader(subjects.length, false, args.subjectLabels);
562
563 const form = new FormData();
564 form.set('model', args.model);
565 form.set('prompt', header + args.prompt);
566 form.set('size', args.size ?? '1024x1024');
567 form.set('n', '1');
568 // Single image uses the proven `image` field; multiple pets use the
569 // `image[]` array form the edits endpoint expects for multi-image input.
570 const field = subjects.length > 1 ? 'image[]' : 'image';
571 subjects.forEach((s, i) => {
572 const blob = new Blob([new Uint8Array(s.bytes)], { type: s.mime });
573 form.append(field, blob, `reference-${i + 1}.${s.mime === 'image/png' ? 'png' : 'jpg'}`);
574 });
575
576 const res = await fetch('https://api.openai.com/v1/images/edits', {
577 method: 'POST',
578 headers: { Authorization: `Bearer ${key}` },
579 body: form,
580 });
581 if (!res.ok) {
582 console.error('[image-gen] OpenAI error', { model: args.model, status: res.status, requestId: res.headers.get('x-request-id') });
583 const text = await res.text();
584 throw new Error(`OpenAI ${res.status}: ${text.slice(0, 400)}`);
585 }
586 const json = await res.json() as { data?: { b64_json?: string }[] };
587 const b64 = json?.data?.[0]?.b64_json;
588 if (!b64) throw new Error('OpenAI returned no image data');
589 return Buffer.from(b64, 'base64');
590}
591
592async function generateViaGemini(args: GenArgs): Promise<Buffer> {
593 const key = process.env.GEMINI_API_KEY;
594 if (!key) throw new Error('GEMINI_API_KEY not set');
595
596 // imageConfig is optional but required to request anything bigger
597 // than the 1K default. Verified against the live Gemini Nano Banana
598 // Pro API — `imageSize` accepts '1K' / '2K' / '4K' (1024 / 2048 /
599 // 4096 px square). aspectRatio is included whenever imageConfig is
600 // present so the model knows the target shape.
601 //
602 // Reference images travel as inline_data parts in positional order:
603 // the subject pets first (image 1..N), then the optional style image
604 // last. A positional header prepended to the prompt tells the model what
605 // each indexed image is. Order matters — the model uses positional
606 // indexing, and multi-pet orders rely on every pet being attached.
607 const imageSize = args.geminiImageSize;
608 const hasStyleRef = !!args.styleReferenceBytes && !!args.styleReferenceMime;
609
610 const subjects = [
611 { bytes: args.referenceBytes, mime: args.referenceMime },
612 ...(args.additionalSubjectReferences ?? []),
613 ];
614 const header = buildReferenceHeader(subjects.length, hasStyleRef, args.subjectLabels);
615 const promptText = header + args.prompt;
616
617 const requestParts: Array<Record<string, unknown>> = [{ text: promptText }];
618 for (const s of subjects) {
619 requestParts.push({ inline_data: { mime_type: s.mime, data: s.bytes.toString('base64') } });
620 }
621 if (hasStyleRef) {
622 requestParts.push({
623 inline_data: {
624 mime_type: args.styleReferenceMime!,
625 data: args.styleReferenceBytes!.toString('base64'),
626 },
627 });
628 }
629
630 // Always send imageConfig so the output aspect ratio is controlled
631 // (defaults to 1:1). imageSize is only added for 2K/4K (1K is default).
632 const imageConfig: Record<string, unknown> = { aspectRatio: args.aspectRatio ?? '1:1' };
633 if (imageSize && imageSize !== '1K') imageConfig.imageSize = imageSize;
634 const body: Record<string, unknown> = {
635 contents: [{ parts: requestParts }],
636 generationConfig: { responseModalities: ['image', 'text'], imageConfig },
637 };
638 const url = `https://generativelanguage.googleapis.com/v1beta/models/${args.model}:generateContent`;
639 const res = await fetch(url, {
640 method: 'POST',
641 headers: { 'x-goog-api-key': key, 'content-type': 'application/json' },
642 body: JSON.stringify(body),
643 });
644 if (!res.ok) {
645 console.error('[image-gen] Gemini error', { model: args.model, status: res.status });
646 if (res.status === 402) throw new Error('Gemini billing is out of credits. Select OpenAI to generate this portrait.');
647 const text = await res.text();
648 throw new Error(`Gemini ${res.status}: ${text.slice(0, 400)}`);
649 }
650 const json = await res.json() as {
651 candidates?: { content?: { parts?: { inline_data?: { data?: string }; inlineData?: { data?: string } }[] } }[];
652 };
653 const parts = json?.candidates?.[0]?.content?.parts ?? [];
654 for (const part of parts) {
655 const data = part?.inline_data?.data ?? part?.inlineData?.data;
656 if (data) return Buffer.from(data, 'base64');
657 }
658 throw new Error('Gemini returned no image data');
659}
660
661/** Fetch a reference image by URL and return bytes + detected mime. */
662export async function fetchReference(url: string): Promise<{ bytes: Buffer; mime: 'image/png' | 'image/jpeg' }> {
663 const res = await fetch(url);
664 if (!res.ok) throw new Error(`Reference fetch ${res.status} for ${url}`);
665 const buf = Buffer.from(await res.arrayBuffer());
666 // CF Images serves PNG by default for the `public` variant; sniff to be safe.
667 const isPng = buf[0] === 0x89 && buf[1] === 0x50;
668 return { bytes: buf, mime: isPng ? 'image/png' : 'image/jpeg' };
669}