import 'server-only'; import { PORTRAIT_PROMPTS } from '@/app/data/portraitPrompts'; import { STYLE_CATALOG, type PortraitPromptId } from '@/app/data/styleCatalog'; import { GEMINI_IMAGE_MODEL, type ImageModel } from './image-models'; // ─── Aspect ratio (frame-shape-aware generation) ───────────────────── // // Frames are square or portrait (see PRODUCTS in pricing.ts: 1/1, 4/5, // 3/4, 2/3, 11/14, 5/7, 5/6). Rather than always generating a square and // cropping (which loses composition control), we generate natively in // the frame's shape so the model composes for the real canvas. Each // model supports a limited set of output shapes, so we snap the frame // aspect to the nearest the model can do and let cropToAspect() finish // to the EXACT frame ratio (so the printed file always matches the frame). // • Gemini imageConfig.aspectRatio — 1:1 / 4:5 / 3:4 / 2:3 cover our // portrait frames; the model supports more. // • This app requests 1024x1024 (square), 1024x1536 (2:3 portrait), // or 1536x1024 (landscape) for OpenAI. Portrait frames snap to // 2:3 then crop. export type GeminiAspect = '1:1' | '4:5' | '3:4' | '2:3' | '5:4' | '4:3' | '3:2'; export type OpenAiSize = '1024x1024' | '1024x1536' | '1536x1024'; export type AspectSpec = { /** The customer's frame aspect as a clean label, e.g. '3:4'. */ label: string; orientation: 'square' | 'portrait' | 'landscape'; /** Nearest Gemini-supported aspectRatio. */ gemini: GeminiAspect; /** Nearest OpenAI size. */ openaiSize: OpenAiSize; }; const GEMINI_PORTRAIT: ReadonlyArray = [['4:5', 0.8], ['3:4', 0.75], ['2:3', 2 / 3]]; const GEMINI_LANDSCAPE: ReadonlyArray = [['5:4', 1.25], ['4:3', 4 / 3], ['3:2', 1.5]]; function nearestGemini(cands: ReadonlyArray, ratio: number): GeminiAspect { let best = cands[0]; for (const c of cands) if (Math.abs(c[1] - ratio) < Math.abs(best[1] - ratio)) best = c; return best[0]; } /** Map a frame aspect string ('W / H' from pricing.ts, e.g. '3 / 4') to * the nearest model-supported output shapes. Defaults to square on * empty / unparseable input. */ export function aspectSpecFromFrame(aspectStr: string | null | undefined): AspectSpec { const square: AspectSpec = { label: '1:1', orientation: 'square', gemini: '1:1', openaiSize: '1024x1024' }; if (!aspectStr) return square; const m = aspectStr.match(/^\s*(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)\s*$/); if (!m) return square; const w = parseFloat(m[1]); const h = parseFloat(m[2]); if (!(w > 0) || !(h > 0)) return square; const ratio = w / h; const label = `${m[1]}:${m[2]}`; if (Math.abs(ratio - 1) < 0.02) return { ...square, label }; if (ratio < 1) return { label, orientation: 'portrait', gemini: nearestGemini(GEMINI_PORTRAIT, ratio), openaiSize: '1024x1536' }; return { label, orientation: 'landscape', gemini: nearestGemini(GEMINI_LANDSCAPE, ratio), openaiSize: '1536x1024' }; } /** Short, authoritative output-shape directive, prepended to a prompt so * the model composes for the frame instead of a square. */ export function aspectDirective(spec: AspectSpec): string { if (spec.orientation === 'square') { return 'OUTPUT FORMAT: 1:1 square (equal width and height). Fill the canvas edge to edge.'; } const dir = spec.orientation === 'portrait' ? 'taller than wide' : 'wider than tall'; return [ `OUTPUT FORMAT: ${spec.label} ${spec.orientation} — ${dir}. Compose for this exact shape, NOT a square.`, '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).', ].join(' '); } /** Re-shape a square-canonical prompt for a non-square frame: swap the * literal "1:1 / square" composition phrases for the frame aspect and * prepend the directive. No-op for square frames (the canonical prompts * are already square). */ export function withAspect(prompt: string, spec: AspectSpec): string { if (spec.orientation === 'square') return prompt; const shaped = prompt .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`) .replace(/\bSquare 1:1 canvas\b/g, `${spec.label} ${spec.orientation} canvas`) .replace(/\bsquare 1:1\b/gi, `${spec.label} ${spec.orientation}`); return aspectDirective(spec) + '\n\n' + shaped; } /** AI-facing descriptions of each font option (the Builder's FONTS dict * is a CSS-only client construct; the model needs a stylistic * description instead of a font-family name it can't load). Keys must * stay in sync with the FontId set in Builder.tsx. */ export type LetteringFontId = 'modern' | 'editorial' | 'display' | 'italic' | 'serif' | 'script' | 'hand' | 'soft'; const FONT_DESCRIPTIONS: Record = { modern: { description: 'a tracked-out modern geometric sans-serif (DM Sans-style), medium weight, generous letterspacing', uppercase: true, label: 'Modern' }, editorial: { description: 'a refined classical serif (Newsreader-style), medium weight, with subtle letterspacing', uppercase: true, label: 'Editorial' }, display: { description: 'a tall, thin display serif (Italiana-style), light weight, with airy letterspacing', uppercase: true, label: 'Display' }, italic: { description: 'a flowing italic classical serif (Cormorant Garamond italic-style), elegant and unhurried', uppercase: false, label: 'Italic' }, serif: { description: 'a classic high-contrast serif (Playfair Display-style), gracious and editorial', uppercase: false, label: 'Classic' }, script: { description: 'an elegant looping cursive script (Pinyon Script-style), flowing and delicate', uppercase: false, label: 'Script' }, hand: { description: 'a relaxed handwritten marker (Caveat-style), warm and personal', uppercase: false, label: 'Handwritten' }, soft: { description: 'a soft rounded modern sans-serif (Outfit-style), friendly and contemporary', uppercase: false, label: 'Soft sans' }, }; /** Look up the human-readable label for a font id, or null if unknown. */ export function letteringFontLabel(fontId: string | null | undefined): string | null { if (!fontId) return null; return FONT_DESCRIPTIONS[fontId as LetteringFontId]?.label ?? null; } /** Prepend the customer's free-text note to the artist as an explicit * request the model should honour. The Builder collects this on every * order (catalog and custom style), but until now only the Gemini * custom-style prompt actually read it — every other path silently * dropped it. No-op for null / blank. */ export function withArtistNote( prompt: string, note: string | null | undefined, ): string { const trimmed = (note ?? '').trim(); if (!trimmed) return prompt; const directive = [ `CUSTOMER NOTE — read carefully: "${trimmed}"`, `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.`, ].join('\n'); return directive + '\n\n' + prompt; } /** Inject lettering instructions into a prompt when the customer asked * for their pet's name on the artwork. Like the background colour: the * original design had the name composited in post-process, but that * step was never wired up — the AI is the only thing that can put * pixels into the print file. This directive overrides every "no text / * no lettering" instruction in the base prompts so the AI actually * renders the name. No-op when there's no name, no font, includeName * is false, or the font id isn't one we know. */ export function withLettering( prompt: string, lettering: { name: string | null; fontId: string | null; include: boolean } | null | undefined, ): string { if (!lettering || !lettering.include) return prompt; const name = (lettering.name ?? '').trim(); if (!name) return prompt; const font = FONT_DESCRIPTIONS[lettering.fontId as LetteringFontId]; if (!font) return prompt; const displayName = font.uppercase ? name.toUpperCase() : name; const casing = font.uppercase ? 'ALL CAPS' : 'the casing shown'; const directive = [ `NAME LETTERING — strict: render the pet's name "${displayName}" (${casing}) across the upper area of the canvas in ${font.description}.`, `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.`, ].join('\n'); return directive + '\n\n' + prompt; } /** Substitute {{BG_HEX}} / {{BG_LABEL}} placeholders inside a prompt with * the customer's chosen background colour. Used by both defaultPromptFor * (OpenAI prose briefs) and geminiPromptFor (Gemini ingredient prompts). * When bg is null/undefined (catalog styles like cubist that carry their * own ground and have no placeholders), this is a no-op; when bg is * set, every placeholder occurrence is replaced. */ function substituteBackground(prompt: string, bg: { hex: string; label: string } | null | undefined): string { if (!bg) { // Defensive fallback: any prompt that does contain placeholders but // was called without a bg gets a sensible white default rather than // shipping literal "{{BG_HEX}}" text to the model. return prompt .replace(/\{\{BG_HEX\}\}/g, '#FFFFFF') .replace(/\{\{BG_LABEL\}\}/g, 'white'); } return prompt .replace(/\{\{BG_HEX\}\}/g, bg.hex) .replace(/\{\{BG_LABEL\}\}/g, bg.label); } export function defaultPromptFor( styleId: string, name: string | null, bg?: { hex: string; label: string } | null, ): string { const entry = PORTRAIT_PROMPTS.find(p => p.id === styleId); if (!entry) return ''; return substituteBackground( entry.prompt.replace(/\{\{NAME\}\}/g, name ?? ''), bg, ); } /** Marker used by both customStyleStarterPrompt and the admin editor to * splice/replace a style-description block inside the prompt text. Keep * this stable — the editor's Analyze button does a find-and-replace on * this exact header so re-analyses don't stack. */ export const STYLE_REFERENCE_BLOCK_MARKER = '## STYLE REFERENCE (from your uploaded image)'; /** Starter prompt for custom-style commissions. The customer uploaded * a style reference; this prompt instructs the model to render their * pet in that reference's style. Admin still edits to taste before * generating. * * On Gemini the style image is sent alongside as a final reference * part — the positional instructions header (built by * buildReferenceHeader) is prepended automatically by generateImage(). * * On OpenAI the style image CAN'T travel — /images/edits accepts subject * photos but no separate style image. The admin clicks "Analyze style" which calls * GPT-4o Vision to describe the style, and that description is * injected here as the STYLE_REFERENCE_BLOCK_MARKER section. When * styleDescription is omitted, the section is omitted too. */ export function customStyleStarterPrompt(name: string | null, styleDescription?: string | null): string { const named = name ? ` titled "${name}" hand-lettered above` : ''; const lines = [ 'Render a portrait of the pet shown in the SUBJECT reference (image 1) in the visual style of the STYLE reference (image 2).', '', 'Subject fidelity — strict:', "- Preserve the pet's breed, coat pattern, markings, eye color, ears, and distinguishing features exactly as shown in image 1.", '- Keep the pet recognizable to its owner. Do not blend in features from the style reference.', '', 'Style fidelity — high:', '- Match the medium, brushwork, palette, contrast, line quality, texture, and mood of image 2.', '- If image 2 is a painting, render as a painting in that exact technique. If a photograph, mimic its lighting + grade.', '- Apply the style to the SUBJECT only — do not borrow image 2\'s subject, scenery, or composition unless explicitly instructed below.', '', 'Composition:', '- Square 1:1 canvas. Pet head and chest fill the frame, eyes in the upper-middle third.', '- Tight crop; minimal background; the style reference\'s palette informs the background tone if applicable.', `- Portrait hero pose, 3/4 view, dignified and alert${named}.`, '', 'The output should feel like the customer\'s pet was painted by the same hand that made the style reference.', ]; if (styleDescription && styleDescription.trim()) { lines.push( '', STYLE_REFERENCE_BLOCK_MARKER, '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.', '', styleDescription.trim(), ); } return lines.join('\n'); } // ─── Gemini ("Nano Banana") prompt builders ────────────────────────── // // Gemini Nano Banana Pro responds better to short, structured, plain- // language direction than to the long prose briefs we feed gpt-image-2. // So when the admin generates on Gemini we DON'T reuse the OpenAI image // prompt — we build a separate "ingredient" prompt: a compact base // (the basics every L&G portrait needs — subject fidelity, composition, // a clean surround) with the per-style "ingredients" (the essence of // the look, distilled from the full briefs in portraitPrompts.ts) // slotted in. For custom-style orders the "ingredients" are the // customer-uploaded style reference itself — Gemini sees it directly as // image 2 — so that variant leans on the image and just supplies the // basics plus any artist note. Nothing here overrides the pet's // identity or the reference. /** Per-style essence injected into the Gemini base template. Distilled * from the full briefs in portraitPrompts.ts — kept tight on purpose * (Gemini does better with concise direction). The lettering variants * (…-plain / named) reuse their base style's ingredients. */ const GEMINI_STYLE_INGREDIENTS: Record = { watercolor: '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.', lineart: '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.', 'lineart-plain': '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.', cubist: '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.', ukiyoe: '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.', thangka: '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.', 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.', charcoal: '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.', 'charcoal-plain': '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.', vector: '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.', 'vector-plain': '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.', 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.', risograph: '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.', athome: '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.', neoexpressionist: '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.', 'landscape-oil': '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.', named: '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.', 'named-plain': '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.', }; /** Composition variants — most styles are a tight bust, but a few need * their own framing (named reserves a top band for lettering; riso * runs full-bleed; neo-expressionist is a standing full body; the * retro photo is a full scene). */ type GeminiComposition = 'bust' | 'named' | 'fullbleed' | 'standing' | 'scene' | 'landscapescene'; const GEMINI_COMPOSITION_BLOCKS: Record = { 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.', 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.', 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.', 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.', 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.', 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.', }; const GEMINI_STYLE_COMPOSITION: Partial> = { named: 'named', 'named-plain': 'named', risograph: 'fullbleed', neoexpressionist: 'standing', athome: 'scene', 'landscape-oil': 'landscapescene', }; function geminiBase(styleName: string, ingredients: string, comp: GeminiComposition): string { return [ `Recreate the pet (or pets) from the reference photo(s) as a ${styleName} portrait.`, '', '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.', '', `STYLE: ${ingredients}`, '', GEMINI_COMPOSITION_BLOCKS[comp], '', '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.', ].join('\n'); } /** Gemini "ingredient" prompt for a catalog style. Returns '' for an * unknown styleId (mirrors defaultPromptFor). The bg is substituted * into {{BG_HEX}}/{{BG_LABEL}} placeholders for styles whose ingredient * text carries them (the hasSolidBackground set); a no-op for styles * that carry their own painted ground. */ export function geminiPromptFor( styleId: string, bg?: { hex: string; label: string } | null, ): string { const ingredients = GEMINI_STYLE_INGREDIENTS[styleId as PortraitPromptId]; if (!ingredients) return ''; const styleName = STYLE_CATALOG.find(s => s.id === styleId)?.name ?? 'fine-art'; const comp = GEMINI_STYLE_COMPOSITION[styleId as PortraitPromptId] ?? 'bust'; return substituteBackground(geminiBase(styleName, ingredients, comp), bg); } /** Gemini "ingredient" prompt for a custom-style commission. The * customer's uploaded style reference IS the style ingredient — Gemini * receives it as the final style image (generateImage prepends the * positional header via buildReferenceHeader), so this just supplies * subject fidelity, the composition basics, and the customer's artist * note. */ export function geminiCustomStylePrompt(artistNote?: string | null): string { const note = (artistNote ?? '').trim(); const lines = [ 'Render the pet from the SUBJECT reference (image 1) in the visual style of the STYLE reference (image 2).', '', '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.', '', '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.', '', '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.', ]; if (note) { lines.push( '', `CUSTOMER REQUEST: "${note}" — honour this where it does not conflict with keeping the pet recognizable.`, ); } lines.push( '', '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.', ); return lines.join('\n'); } /** Wrap an admin's free-text tweak ("same but with a red background") * into an edit instruction for the refine loop. The reference image * handed to generateImage in refine mode is a PRIOR generation, so the * prompt's job is to change only what's asked and hold everything else * steady. Works on both engines: OpenAI /images/edits edits the prior * render directly; Gemini gets it as the single reference image. */ export function buildRefinePrompt(instruction: string): string { return [ 'Edit the provided image (a finished pet portrait).', `Change ONLY the following: ${instruction.trim()}`, '', "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.", '', 'CLEAN OUTPUT: no added border, frame, mat, caption, signature, watermark, or lettering.', ].join('\n'); } export function buildCustomerRevisionPrompt(feedback: string, studioNotes: string, spec: AspectSpec, widerFramingPrepared = false): string { return [ 'Edit the supplied published portrait. The customer’s requested changes are the highest priority for this edit.', '', 'CUSTOMER FEEDBACK (verbatim):', feedback.trim(), '', '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.', widerFramingPrepared ? '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.' : '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.', ...(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.'] : []), '', '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.', `OUTPUT: ${spec.label} ${spec.orientation} aspect ratio, artwork edge to edge. No added presentation frame, padding, signature, or watermark.`, 'Before rendering, check that the most important requested changes will be easy to see compared with the source.', ].join('\n'); } /** OpenAI second-pass prompt for the Gemini→OpenAI chain. OpenAI sees the * freshly-generated Gemini render as its single reference image; this * tells it to finish/refine that image rather than restyle it. */ export function buildChainRefinePrompt(): string { return [ 'You are given a finished, stylized pet portrait as the reference image.', "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.", 'Do not restyle, recolor, re-pose, or change the background.', '', 'Square 1:1. CLEAN OUTPUT: no added border, frame, mat, caption, signature, watermark, or lettering.', ].join('\n'); } type GenArgs = { model: ImageModel; prompt: string; /** Subject reference photo bytes (PNG/JPEG) and mime type — the pet. * For a multi-pet commission this is the FIRST pet (image 1); the rest * travel in additionalSubjectReferences. */ referenceBytes: Buffer; referenceMime: 'image/png' | 'image/jpeg'; /** * Extra SUBJECT photos (pets 2..N) for a multi-pet commission. The * customer can upload up to four pets and we combine them into one * portrait. Empty / omitted for the common single-pet order. Gemini * receives each as its own inline_data part; OpenAI as additional * image[] entries. The positional reference header (built in * generateImage) tells the model that each image is a different pet to * render together. */ additionalSubjectReferences?: Array<{ bytes: Buffer; mime: 'image/png' | 'image/jpeg' }>; /** * Optional display names for the subjects, image 1..N — used only to * label each pet inside the positional reference header (e.g. 'Image 1 * = "Bella"'). Missing / blank entries fall back to a generic label. */ subjectLabels?: string[]; /** * Optional STYLE reference image — when the customer paid for a * custom-style commission they uploaded a painting / photo / reference * whose visual style we should mimic. Gemini accepts this as a second * inline_data part; OpenAI's /images/edits is single-image so the * style ref is silently ignored on that path (admin should pick the * Gemini model when a custom style is attached). */ styleReferenceBytes?: Buffer; styleReferenceMime?: 'image/png' | 'image/jpeg'; /** OpenAI only — defaults to 1024x1024. */ size?: OpenAiSize; /** * Gemini only — output aspect ratio (imageConfig.aspectRatio). * Defaults to '1:1'. Set from the customer's frame so the render is * composed for the real canvas shape; OpenAI uses `size` instead. */ aspectRatio?: GeminiAspect; /** * Gemini Nano Banana Pro only — output resolution tier. The API * defaults to '1K' (1024×1024) when omitted. * '2K' = 2048×2048 (~4× pixels, ~2× cost, ~2× latency vs 1K). * '4K' = 4096×4096 (~16× pixels, ~4× cost, ~4× latency vs 1K). * Customer-facing renders always pass '4K' (the print file IS the * approved preview — see the generate route). Only drop to 1K/2K for * throwaway experiments where speed/cost matters more than detail. */ geminiImageSize?: '1K' | '2K' | '4K'; }; /** Build the positional-reference header prepended to a prompt when more * than one image is attached, so the model knows what each indexed image * is. Covers three shapes: * • 1 subject, no style → '' (a lone pet photo needs no header). * • 1 subject + style → the classic two-image SUBJECT/STYLE split. * • N subjects (+ style) → each image 1..N is a DIFFERENT pet to render * together in one portrait; the style ref (if any) is the last image. * subjectLabels[i] optionally names image i+1 (e.g. the pet's name). */ function buildReferenceHeader( subjectCount: number, hasStyleRef: boolean, subjectLabels?: string[], ): string { if (subjectCount <= 1 && !hasStyleRef) return ''; const lines: string[] = []; const label = (i: number) => { const name = subjectLabels?.[i]?.trim(); return name ? ` — "${name}"` : ''; }; if (subjectCount <= 1) { // Single subject + style reference — the original two-image case. lines.push( 'You are given TWO reference images.', ` • Image 1 = SUBJECT reference${label(0)}: the pet to portray. Preserve breed, markings, eye color, and identifying features faithfully.`, ' • 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.', ); } else { // Multiple subjects (multi-pet commission). Enumerate each pet, then // the optional style ref as the final image. const total = subjectCount + (hasStyleRef ? 1 : 0); lines.push(`You are given ${total} reference images.`); for (let i = 0; i < subjectCount; i++) { lines.push(` • Image ${i + 1} = SUBJECT reference${label(i)}: one pet to include in the portrait.`); } lines.push( `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.`, ); if (hasStyleRef) { lines.push( ` • 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.`, ); } } lines.push('The prompt below is additional guidance on top of these references.', ''); return lines.join('\n') + '\n'; } /** Generate an image. Returns the raw PNG/JPEG bytes from the model. */ export async function generateImage(args: GenArgs): Promise { if (args.model === GEMINI_IMAGE_MODEL) { return generateViaGemini(args); } return generateViaOpenAI(args); } async function generateViaOpenAI(args: GenArgs): Promise { const key = process.env.OPENAI_API_KEY; if (!key) throw new Error('OPENAI_API_KEY not set'); if (args.styleReferenceBytes) { 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).'); } // Subject photos: the primary pet plus any additional pets (multi-pet // commission). OpenAI's image-edit endpoint takes multiple subject // images via repeated image[] fields, so all pets reach the model. const subjects = [ { bytes: args.referenceBytes, mime: args.referenceMime }, ...(args.additionalSubjectReferences ?? []), ]; // Tell the model what each attached image is when there's more than one. // OpenAI never receives the style ref, so the header only describes the // subject pets (hasStyleRef = false here). const header = buildReferenceHeader(subjects.length, false, args.subjectLabels); const form = new FormData(); form.set('model', args.model); form.set('prompt', header + args.prompt); form.set('size', args.size ?? '1024x1024'); form.set('n', '1'); // Single image uses the proven `image` field; multiple pets use the // `image[]` array form the edits endpoint expects for multi-image input. const field = subjects.length > 1 ? 'image[]' : 'image'; subjects.forEach((s, i) => { const blob = new Blob([new Uint8Array(s.bytes)], { type: s.mime }); form.append(field, blob, `reference-${i + 1}.${s.mime === 'image/png' ? 'png' : 'jpg'}`); }); const res = await fetch('https://api.openai.com/v1/images/edits', { method: 'POST', headers: { Authorization: `Bearer ${key}` }, body: form, }); if (!res.ok) { console.error('[image-gen] OpenAI error', { model: args.model, status: res.status, requestId: res.headers.get('x-request-id') }); const text = await res.text(); throw new Error(`OpenAI ${res.status}: ${text.slice(0, 400)}`); } const json = await res.json() as { data?: { b64_json?: string }[] }; const b64 = json?.data?.[0]?.b64_json; if (!b64) throw new Error('OpenAI returned no image data'); return Buffer.from(b64, 'base64'); } async function generateViaGemini(args: GenArgs): Promise { const key = process.env.GEMINI_API_KEY; if (!key) throw new Error('GEMINI_API_KEY not set'); // imageConfig is optional but required to request anything bigger // than the 1K default. Verified against the live Gemini Nano Banana // Pro API — `imageSize` accepts '1K' / '2K' / '4K' (1024 / 2048 / // 4096 px square). aspectRatio is included whenever imageConfig is // present so the model knows the target shape. // // Reference images travel as inline_data parts in positional order: // the subject pets first (image 1..N), then the optional style image // last. A positional header prepended to the prompt tells the model what // each indexed image is. Order matters — the model uses positional // indexing, and multi-pet orders rely on every pet being attached. const imageSize = args.geminiImageSize; const hasStyleRef = !!args.styleReferenceBytes && !!args.styleReferenceMime; const subjects = [ { bytes: args.referenceBytes, mime: args.referenceMime }, ...(args.additionalSubjectReferences ?? []), ]; const header = buildReferenceHeader(subjects.length, hasStyleRef, args.subjectLabels); const promptText = header + args.prompt; const requestParts: Array> = [{ text: promptText }]; for (const s of subjects) { requestParts.push({ inline_data: { mime_type: s.mime, data: s.bytes.toString('base64') } }); } if (hasStyleRef) { requestParts.push({ inline_data: { mime_type: args.styleReferenceMime!, data: args.styleReferenceBytes!.toString('base64'), }, }); } // Always send imageConfig so the output aspect ratio is controlled // (defaults to 1:1). imageSize is only added for 2K/4K (1K is default). const imageConfig: Record = { aspectRatio: args.aspectRatio ?? '1:1' }; if (imageSize && imageSize !== '1K') imageConfig.imageSize = imageSize; const body: Record = { contents: [{ parts: requestParts }], generationConfig: { responseModalities: ['image', 'text'], imageConfig }, }; const url = `https://generativelanguage.googleapis.com/v1beta/models/${args.model}:generateContent`; const res = await fetch(url, { method: 'POST', headers: { 'x-goog-api-key': key, 'content-type': 'application/json' }, body: JSON.stringify(body), }); if (!res.ok) { console.error('[image-gen] Gemini error', { model: args.model, status: res.status }); if (res.status === 402) throw new Error('Gemini billing is out of credits. Select OpenAI to generate this portrait.'); const text = await res.text(); throw new Error(`Gemini ${res.status}: ${text.slice(0, 400)}`); } const json = await res.json() as { candidates?: { content?: { parts?: { inline_data?: { data?: string }; inlineData?: { data?: string } }[] } }[]; }; const parts = json?.candidates?.[0]?.content?.parts ?? []; for (const part of parts) { const data = part?.inline_data?.data ?? part?.inlineData?.data; if (data) return Buffer.from(data, 'base64'); } throw new Error('Gemini returned no image data'); } /** Fetch a reference image by URL and return bytes + detected mime. */ export async function fetchReference(url: string): Promise<{ bytes: Buffer; mime: 'image/png' | 'image/jpeg' }> { const res = await fetch(url); if (!res.ok) throw new Error(`Reference fetch ${res.status} for ${url}`); const buf = Buffer.from(await res.arrayBuffer()); // CF Images serves PNG by default for the `public` variant; sniff to be safe. const isPng = buf[0] === 0x89 && buf[1] === 0x50; return { bytes: buf, mime: isPng ? 'image/png' : 'image/jpeg' }; }