#!/usr/bin/env node // Builds the exact image requests for the loading-screen art from screen.json and prints them (or writes one JSON // file per request with --out). It calls no API. // Each request is { id, model, input, approx_cost_usd }: POST `input` to fal model `model` with your own FAL_KEY // (scripts/fal-run.mjs does this), call Meleon's generate_image or edit_image with it, or paste the prompt (and // the reference images) into any GPT-Image-class editor. // // Stages: // estimate no requests: the cost of the drafts, the finals and a re-roll, to quote before the first paid call // draft one rough screen per entry at low quality, 720 x 1280, to agree the pose, the scene and the open space // final the finished art at medium quality, 1088 x 1936. Do screen 1 first (--screen 1); once it is approved, // put its path in references.anchor, and screens 2 onwards carry it as the look reference (--screen rest) // // Usage: // node scripts/build-requests.mjs --plan screen.json --stage estimate|draft|final // [--screen 1|all|rest|2,3,4] [--quality low|medium|high] [--model gpt-image-2|nano-banana-pro] // [--out requests/] [--inline] // // The art is text-free: the caption, the loading label and the bar are drawn later by scripts/compose-screens.mjs. // --model nano-banana-pro (finals only) writes the second-opinion request: a flat $0.15 an image at 2K. // --inline embeds local images as data URIs (needs --out), so no photo goes on a public URL. // After the drafts, put each approved draft's path in that screen's "draft": its final carries it as a reference, // so the finished screen keeps the composition you agreed. // Node 18 or newer. No npm packages. import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' import { dirname, extname, isAbsolute, join, resolve } from 'node:path' const FLAGS = new Set(['plan', 'stage', 'screen', 'quality', 'model', 'out', 'inline']) const SWITCHES = new Set(['inline']) const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp' } function fail(message) { console.error(message) process.exit(1) } const opts = {} const argv = process.argv.slice(2) for (let i = 0; i < argv.length; i++) { const a = argv[i] if (!a.startsWith('--')) fail(`Unexpected argument "${a}". Flags look like --name value.`) const key = a.slice(2) if (!FLAGS.has(key)) fail(`Unknown flag --${key}. Allowed: ${[...FLAGS].map((f) => `--${f}`).join(', ')}`) if (SWITCHES.has(key)) { opts[key] = true; continue } const value = argv[i + 1] if (value === undefined || value.startsWith('--')) fail(`--${key} needs a value.`) opts[key] = value i++ } if (!opts.plan || !opts.stage) fail('Usage: node scripts/build-requests.mjs --plan screen.json --stage estimate|draft|final [--screen 1|all|rest|2,3] [--model gpt-image-2|nano-banana-pro] [--out dir] [--inline]') if (!['estimate', 'draft', 'final'].includes(opts.stage)) fail(`--stage must be estimate, draft or final, not "${opts.stage}".`) if (opts.inline && !opts.out) fail('--inline writes large data URIs; use it with --out .') if (opts.model && !['gpt-image-2', 'nano-banana-pro'].includes(opts.model)) fail(`--model must be gpt-image-2 or nano-banana-pro, not "${opts.model}".`) if (opts.model === 'nano-banana-pro' && opts.stage === 'draft') fail('Drafts always use GPT Image 2 at low quality (a few cents). --model nano-banana-pro is for finals.') if (!existsSync(opts.plan)) fail(`Plan not found: ${opts.plan}. Create it with scripts/new-screen.mjs.`) let plan try { plan = JSON.parse(readFileSync(opts.plan, 'utf8')) } catch { fail(`${opts.plan} is not valid JSON.`) } const gen = JSON.parse(readFileSync(new URL('../assets/generation-input.json', import.meta.url), 'utf8')) const template = readFileSync(new URL('../assets/prompt-template.md', import.meta.url), 'utf8').trim() if (plan.schema !== 'open-world-loading-screen/1') fail(`${opts.plan} schema is "${plan.schema}", expected open-world-loading-screen/1 (make it with scripts/new-screen.mjs).`) const base = dirname(resolve(opts.plan)) const rel = (p) => (isAbsolute(p) ? p : join(base, p)) const subject = plan.subject ?? {} const style = plan.style ?? {} const screens = plan.screens ?? [] const maxRefs = gen.max_references ?? 3 if (screens.length < 1 || screens.length > 4) fail(`The plan has ${screens.length} screens. Plan 1 to 4.`) screens.forEach((s, i) => { if (s.n !== i + 1) fail(`Screens must be numbered 1 to ${screens.length} in order (found ${s.n} at position ${i + 1}).`) }) const kind = subject.kind if (!['pet', 'product', 'character', 'person'].includes(kind)) fail(`subject.kind must be pet, product, character or person, not "${kind}".`) const side = style.side ?? 'left' if (!gen.composition[side]) fail(`style.side must be left or right, not "${side}".`) // A person needs a recorded yes, an adult and the user's own photo or written consent. Nothing else is accepted. const personProblem = kind === 'person' && (!['own-photo', 'written-consent'].includes(plan.consent?.basis) || plan.consent?.adult_confirmed !== true || plan.consent?.confirmed !== true) ? 'The hero is a person, but the plan does not record consent. Set consent.basis to "own-photo" or "written-consent", and consent.adult_confirmed and consent.confirmed to true, only after the person shown has agreed in plain words (or the photo is of the user themselves) and is an adult. Never a celebrity, a public figure or a child, and never a photo of someone who has not agreed.' : '' const personFlag = kind !== 'person' && subject.photo_has_person === true ? `subject.photo_has_person is true but the kind is "${kind}". A photo with a person in it is kind "person" with consent recorded; otherwise crop the person out.` : '' const photoProblem = kind !== 'character' && !subject.photo ? `A ${kind} needs subject.photo, the reference the art keeps recognisable.` : '' const gptCost = (size, quality, refs) => (gen.approx_cost.per_1024_square[quality] * size.width * size.height) / (1024 * 1024) + refs * gen.approx_cost.per_reference_image const stageOf = (name) => { const s = gen.stages[name] const quality = opts.quality && opts.stage === name ? opts.quality : s.quality if (!['low', 'medium', 'high'].includes(quality)) fail(`--quality must be low, medium or high, not "${quality}".`) return { size: s.image_size, quality } } const useNano = opts.stage === 'final' && opts.model === 'nano-banana-pro' /** The references one screen will carry at a stage, before any file is read. */ function plannedRefs(sc, stage, assumeDrafts) { const out = [] if (subject.photo) out.push(['photo', subject.photo]) if (stage === 'final') { if (sc.n !== 1) out.push(['anchor', plan.references?.anchor || '(approved screen 1)']) if (sc.draft || assumeDrafts) out.push(['draft', sc.draft || '(approved draft)']) } return out.slice(0, maxRefs) } if (opts.stage === 'estimate') { const draft = stageOf('draft') const final = stageOf('final') const gptFinal = (sc, assume) => gptCost(final.size, final.quality, plannedRefs(sc, 'final', assume).length) const drafts = screens.reduce((a, sc) => a + gptCost(draft.size, draft.quality, plannedRefs(sc, 'draft', false).length), 0) const finalsAfterDrafts = screens.reduce((a, sc) => a + gptFinal(sc, true), 0) const finalsOnly = screens.reduce((a, sc) => a + gptFinal(sc, false), 0) const rerollFinal = gptCost(final.size, final.quality, Math.min(maxRefs, 2 + (screens.length > 1 ? 1 : 0))) const rerollDraft = gptCost(draft.size, draft.quality, subject.photo ? 1 : 0) const nano = gen.alternative_final.approx_cost_usd console.log(`Plan: ${screens.length} screen${screens.length === 1 ? '' : 's'} for ${kind} "${subject.description ?? '(no description)'}", ${subject.photo ? 'with a reference photo' : 'no reference photo'}.`) console.log(` ${`Drafts (quality ${draft.quality}, ${draft.size.width} x ${draft.size.height})`.padEnd(64)} $${drafts.toFixed(2)}`) console.log(` ${`Finals after drafts (quality ${final.quality}, ${final.size.width} x ${final.size.height})`.padEnd(64)} $${finalsAfterDrafts.toFixed(2)}`) console.log(` ${'Finals with no drafts first'.padEnd(64)} $${finalsOnly.toFixed(2)}`) console.log(` ${'A re-roll of one draft, then its final (about)'.padEnd(64)} $${(rerollDraft + rerollFinal).toFixed(2)}`) console.log(` ${'A second-opinion final with nano-banana-pro (2K, flat)'.padEnd(64)} $${nano.toFixed(2)} each`) const usual = drafts + finalsAfterDrafts const top = usual + 2 * (rerollDraft + rerollFinal) console.log(`\nQuote to the user: about $${usual.toFixed(2)} for drafts and finals, up to about $${top.toFixed(2)} with two re-rolls (or about $${finalsOnly.toFixed(2)} for finals with no drafts). The caption, the loading bar, the profile crop and the checks are free.`) console.log('Get one explicit yes on this total before the first paid call, and ask again if it will be exceeded.') for (const p of [personProblem, personFlag, photoProblem]) if (p) console.error(`\nwarning: ${p}`) process.exit(0) } for (const p of [personProblem, personFlag, photoProblem]) if (p) fail(p) const unfilled = (t) => typeof t === 'string' && t.includes('FILL:') for (const key of ['description', 'keep']) { if (typeof subject[key] !== 'string' || !subject[key].trim() || unfilled(subject[key])) fail(`subject.${key} is empty. Say what the hero is and which features must stay recognisable.`) } if (typeof plan.look !== 'string' || !plan.look.trim() || unfilled(plan.look)) fail('The plan\'s "look" is empty. Write one sentence for the art direction, or start again with --preset.') if (typeof plan.world !== 'string' || !plan.world.trim() || unfilled(plan.world)) fail('The plan\'s "world" is empty. Say what the street around the hero holds.') function imageRef(path, what) { const abs = rel(path) if (!existsSync(abs)) fail(`${what} not found: ${abs}`) const ext = extname(abs).toLowerCase() if (!MIME[ext]) fail(`${what} must be a .jpg, .png or .webp image, not ${ext || 'a file without extension'}.`) if (!opts.inline) return `file:${abs}` if (statSync(abs).size > 8 * 1024 * 1024) fail(`${what} is over 8 MB. Save it as a JPEG under 8 MB first.`) return `data:${MIME[ext]};base64,${readFileSync(abs).toString('base64')}` } let picked = screens if (opts.screen && opts.screen !== 'all') { if (opts.screen === 'rest') picked = screens.filter((s) => s.n !== 1) else { const wanted = opts.screen.split(',').map((x) => Number(x.trim())) if (wanted.some((n) => !Number.isInteger(n))) fail(`--screen takes a screen number, a list like 2,3,4, "rest" or "all", not "${opts.screen}".`) picked = wanted.map((n) => screens.find((s) => s.n === n) ?? fail(`There is no screen ${n} in the plan.`)) } } const stage = stageOf(opts.stage) if (stage.quality === 'high') console.error('warning: high quality costs about four times medium. Medium is plenty for a screen that is mostly seen on a phone.') const requests = [] for (const sc of picked) { const where = `screen ${sc.n}` for (const key of ['pose', 'scene']) { if (typeof sc[key] !== 'string' || !sc[key].trim() || unfilled(sc[key])) fail(`${where} has no ${key} yet. Write it in screen.json (references/prompt-patterns.md).`) if (/["“”]/.test(sc[key]) || /\b(?:text|title|caption|words?|lettering|reads?|saying|logo|sign that)\b/i.test(sc[key])) { console.error(`warning: ${where} ${key} mentions words, quotes or a logo. The art must stay text-free; the caption is drawn later. Describe only the picture.`) } if (/\b(?:gun|guns|weapon|knife|bomb|police|cop|crime|robbery|heist|drugs?|blood|wanted|stolen|steal)\b/i.test(sc[key])) fail(`${where} ${key} mentions crime or violence. This format is cocky and funny: a hot dog stand, a convertible, a skateboard.`) } const refs = [] const lines = [] let photoRef = 0 if (subject.photo) { refs.push(imageRef(subject.photo, 'The hero photo (subject.photo)')) photoRef = refs.length } if (opts.stage === 'final' && sc.n !== 1) { if (plan.references?.anchor) { refs.push(imageRef(plan.references.anchor, 'Screen 1 art (references.anchor)')) lines.push(`Reference image ${refs.length} is screen 1 of the same series: match its art direction exactly (outline weight, colours, light, brush texture, finish) and keep the same open space for the caption, but show this screen's own scene and pose, with the same hero. Do not copy its scene.`) } else { console.error(`warning: ${where} has no look reference. Approve screen 1 first and put its art path in references.anchor, so every final matches it.`) } } if (opts.stage === 'final' && sc.draft) { if (refs.length >= maxRefs) console.error(`warning: ${where} already carries ${refs.length} references, so its draft is left out; describe the agreed framing in the pose and scene instead.`) else { refs.push(imageRef(sc.draft, `Draft for ${where}`)) lines.push(`Reference image ${refs.length} is the approved rough draft of this screen: keep its composition, framing and the place of every element, and render it cleanly in full detail. The hero's identity comes from reference image ${photoRef || 'the description'}, not from the draft.`) } } const heroTemplate = kind === 'character' ? (photoRef ? gen.kinds.character_with_reference : gen.kinds.character) : gen.kinds[kind] const hero = heroTemplate .replace('{{description}}', () => subject.description.trim().replace(/[.]$/, '')) .replace('{{keep}}', () => subject.keep.trim().replace(/[.]$/, '')) .replace('{{ref}}', () => String(photoRef)) const people = kind === 'person' ? 'The hero is the only person in the image; the street has no other people. The hero is an adult who has agreed to appear, never a child and never anyone famous.' : 'Nobody else is in the image: no people at all, the street is busy with cars, palms, carts, bikes and awnings only.' const textRule = kind === 'product' ? 'IMPORTANT: render no new words, letters, numbers, logos, labels, captions, watermarks, bars or interface anywhere; keep lettering only where it is printed on the product in the reference photo, and keep every sign and shop front blank. The caption and the loading bar are added later in code.' : 'IMPORTANT: render no words, letters, numbers, logos, labels, captions, watermarks, loading bars or interface anywhere in the image; every sign, shop front, awning, cart and car is blank. The caption and the loading bar are added later in code.' const prompt = template .replace('{{look}}', () => plan.look.trim().replace(/[.]$/, '')) .replace('{{world}}', () => plan.world.trim().replace(/[.]$/, '')) .replace('{{hero}}', () => hero) .replace('{{pose}}', () => sc.pose.trim().replace(/[.]$/, '')) .replace('{{scene}}', () => sc.scene.trim().replace(/[.]$/, '')) .replace('{{space}}', () => gen.composition[side]) .replace('{{grid_rule}}', () => gen.grid_rule) .replace('{{references}}', () => lines.join(' ')) .replace('{{people}}', () => people) .replace('{{safety}}', () => gen.safety_rule) .replace('{{text_rule}}', () => textRule) .replace(/\s+/g, ' ') .trim() const id = `screen-${String(sc.n).padStart(2, '0')}-${opts.stage}` if (useNano) { const alt = gen.alternative_final const input = { prompt, ...alt.input } if (refs.length) input.image_urls = refs requests.push({ id, model: refs.length ? alt.model_with_references : alt.model, input, approx_cost_usd: alt.approx_cost_usd }) } else { const input = { prompt, image_size: stage.size, quality: stage.quality, ...gen.input } if (refs.length) input.image_urls = refs requests.push({ id, model: refs.length ? gen.model_with_references : gen.model, input, approx_cost_usd: Number(gptCost(stage.size, stage.quality, refs.length).toFixed(3)) }) } } const total = requests.reduce((a, r) => a + r.approx_cost_usd, 0) if (opts.out) { mkdirSync(opts.out, { recursive: true }) for (const r of requests) writeFileSync(join(opts.out, `${r.id}.json`), JSON.stringify(r, null, 2)) console.log(`Wrote ${requests.length} request(s) to ${opts.out}. Approximate cost: $${total.toFixed(2)}.`) } else { console.log(JSON.stringify(requests, null, 2)) console.error(`${requests.length} request(s), approximate cost $${total.toFixed(2)}. Local images are shown as file: paths; use --out with --inline to embed them, or fal-run.mjs (which embeds them).`) }