#!/usr/bin/env node
// Builds the exact requests for the character sheet from character.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, edit_image or generate_video with it, or paste the
// prompt (and any reference images) into any editor of that class.
//
// Stages:
// estimate no requests: the cost of every step, to quote before the first paid call
// draft the sheet at low quality (about $0.01): checks the layout, the empty label bands and the views
// sheet the sheet at high quality: one 16:9 image, text-free (the labels are drawn later by compose-sheet.mjs)
// scene scene tests, nano-banana-pro edit with the sheet as the reference (--scene 1|2|3|all)
// alt optional: the second outfit, front and back (needs wardrobe_alt)
// clip optional: 5 s of the character turning to the lens, from a scene test (--scene N [--model kling|seedance])
//
// Usage:
// node scripts/build-requests.mjs --character character.json --stage estimate|draft|sheet|scene|alt|clip
// [--scene 1|2|3|all] [--model kling|seedance] [--action "..."] [--quality low|medium|high] [--out requests/] [--inline]
//
// --inline embeds local images as data URIs (needs --out), so no photo goes on a public URL.
// 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'
import { checkCharacter, fail, parseArgs } from './character-lib.mjs'
const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp' }
const opts = parseArgs(process.argv.slice(2), ['character', 'stage', 'scene', 'model', 'action', 'quality', 'out', 'inline'], ['inline'])
if (!opts.character || !opts.stage) fail('Usage: node scripts/build-requests.mjs --character character.json --stage estimate|draft|sheet|scene|alt|clip [--scene 1|2|3|all] [--model kling|seedance] [--out dir] [--inline]')
if (!['estimate', 'draft', 'sheet', 'scene', 'alt', 'clip'].includes(opts.stage)) fail(`--stage must be estimate, draft, sheet, scene, alt or clip, not "${opts.stage}".`)
if (opts.inline && !opts.out) fail('--inline writes large data URIs; use it with --out
.')
if (!existsSync(opts.character)) fail(`Not found: ${opts.character}. Create it with scripts/new-character.mjs.`)
let ch
try {
ch = JSON.parse(readFileSync(opts.character, 'utf8'))
} catch {
fail(`${opts.character} is not valid JSON.`)
}
const gen = JSON.parse(readFileSync(new URL('../assets/generation-input.json', import.meta.url), 'utf8'))
const layout = JSON.parse(readFileSync(new URL('../assets/layout.json', import.meta.url), 'utf8'))
const template = readFileSync(new URL('../assets/prompt-template.md', import.meta.url), 'utf8')
const section = (title) => {
const m = template.match(new RegExp(`## ${title}[^\\n]*\\n+([\\s\\S]*?)(?=\\n## |$)`))
if (!m) fail(`assets/prompt-template.md has no "${title}" section.`)
return m[1].trim()
}
const { issues } = checkCharacter(ch)
// The sheet and its tests do not need the lock text to be current, but they do need real, safe locks.
const blocking = issues.filter((i) => !/lock_text/.test(i))
if (blocking.length) {
for (const i of blocking) console.error(`problem: ${i}`)
fail('Fix character.json first (scripts/new-character.mjs checks the same rules).')
}
if (issues.length) console.error('warning: the lock text is out of date. Run scripts/lock-text.mjs so the prompts carry the current locks.')
const base = dirname(resolve(opts.character))
const rel = (p) => (isAbsolute(p) ? p : join(base, p))
const W = layout.canvas.width
const H = layout.canvas.height
const per1024 = gen.approx_cost.per_1024_square
const perRef = gen.approx_cost.per_reference_image
const sheetCost = (quality, refs) => (per1024[quality] * W * H) / (1024 * 1024) + refs * perRef
const sheetRefs = ch.photo ? 1 : 0
const look = gen.looks[ch.look]
const sceneLook = gen.scene_looks[ch.look]
const pct = (v) => `${Math.round(v * 1000) / 10}`
const rng = (a, b) => `${pct(a)} to ${pct(b)} percent`
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')}`
}
const sceneCost = gen.scene.approx_cost_usd
const clipCost = (m) => Number(gen.clip[m].duration) * gen.clip[m].per_second_usd
const money = (n) => `$${n.toFixed(2)}`
if (opts.stage === 'estimate') {
const draft = sheetCost(gen.sheet.draft_quality, sheetRefs)
const sheet = sheetCost(gen.sheet.quality, sheetRefs)
const scenes = 3 * sceneCost
const alt = ch.wardrobe_alt ? sceneCost : 0
const base3 = draft + sheet + scenes
console.log(`Character sheet for "${ch.name}" (${ch.look}, ${ch.people === 'fictional' ? 'invented' : 'from the user\'s photo'}), board ${W} x ${H}.`)
const row = (label, cost) => console.log(` ${label.padEnd(66)} ${money(cost)}`)
row(`Layout draft, ${gen.sheet.model} quality ${gen.sheet.draft_quality}`, draft)
row(`Sheet, ${gen.sheet.model} quality ${gen.sheet.quality}${sheetRefs ? ' with the photo' : ''}`, sheet)
row('A sheet re-roll (about)', sheet)
row(`Three scene tests, ${gen.scene.model}`, scenes)
if (ch.wardrobe_alt) row('Second outfit, front and back (optional)', alt)
row(`Test clip, ${gen.clip.kling.duration} s, Kling 3 Turbo Pro (optional)`, clipCost('kling'))
row(`Seedance 2.0 mini 480p, ${gen.clip.seedance.duration} s, to see if it accepts a clay face (optional; refused for photoreal and stylised 3D in the sample)`, clipCost('seedance'))
console.log(`\nQuote to the user: about ${money(base3)} for the sheet and three scene tests (about ${money(base3 + sheet)} with one sheet re-roll), about ${money(base3 + clipCost('kling'))} with the test clip. Labels, lock text, the check and the hand-off are free.`)
console.log('Get one explicit yes on this total before the first paid call, and ask again if it will be exceeded.')
process.exit(0)
}
const unfilled = (t) => typeof t !== 'string' || !t.trim() || t.includes('FILL:')
const fill = (text, values) => text.replace(/\{\{(\w+)\}\}/g, (_, k) => (k in values ? values[k] : `{{${k}}}`)).replace(/\s+/g, ' ').trim()
const lock = ch.lock_text
const requests = []
const textRule = 'IMPORTANT: render no words, letters, numbers, logos, labels, captions or watermarks anywhere, including on clothing, badges and the backdrop. The labels are added later in code.'
if (opts.stage === 'draft' || opts.stage === 'sheet') {
const t = layout.turnaround
const e = layout.expressions
const col = (i) => [t.x0 + i * (t.cell_width + t.gap), t.x0 + i * (t.cell_width + t.gap) + t.cell_width]
const views = t.views.map((v, i) => `Column ${i + 1}, x ${rng(...col(i))}: ${v.says}.`).join(' ')
const ecol = (i) => [e.x0 + i * (e.cell_width + e.gap), e.x0 + i * (e.cell_width + e.gap) + e.cell_width]
const expressions = e.items
.map((x, i) => {
const c = ecol(i % 2)
const r = e.rows[Math.floor(i / 2)]
return `${['Top left', 'Top right', 'Lower left', 'Lower right'][i]} (x ${rng(...c)}, y ${rng(...r.y)}): ${x.says}.`
})
.join(' ')
const refs = []
const lines = []
if (ch.photo) {
refs.push(imageRef(ch.photo, 'The photo (character.photo)'))
lines.push('Reference image 1 is the user\'s own photo of the person this character is. Every view shows exactly that person.')
}
const people = ch.photo
? 'The character must stay exactly the person in reference image 1: the same identity, age range, skin tone, hair, facial structure and body. Do not change their ethnicity or add or remove features. The expressions are natural to their face. The person is an adult.'
: 'The character is a fictional adult who does not resemble any real or famous person.'
const outfit = ch.wardrobe_alt ? 'Every figure wears the main wardrobe only; no second outfit is shown.' : ''
const prompt = fill(section('Sheet'), {
backdrop: gen.sheet.backdrop,
look,
lock_text: lock,
outfit_line: outfit,
people,
left_x: rng(t.x0, t.x0 + 4 * t.cell_width + 3 * t.gap),
cell_pct: `${pct(t.cell_width)} percent`,
gap_pct: `${pct(t.gap)} percent`,
fig_y: rng(...t.y),
views,
right_x: rng(e.x0, e.x0 + 2 * e.cell_width + e.gap),
expr_w_pct: `${pct(e.cell_width)} percent`,
r1_y: rng(...e.rows[0].y),
r2_y: rng(...e.rows[1].y),
expressions,
header_y1: `${pct(layout.header.y[1])} percent`,
lab_y: rng(...t.label_y),
e1_y: rng(...e.rows[0].label_y),
e2_y: rng(...e.rows[1].label_y),
references: lines.join(' '),
text_rule: textRule,
})
if (opts.quality && !['low', 'medium', 'high'].includes(opts.quality)) fail('--quality must be low, medium or high.')
const quality = opts.stage === 'draft' ? gen.sheet.draft_quality : (opts.quality ?? gen.sheet.quality)
const input = { prompt, image_size: gen.sheet.image_size, quality, num_images: gen.sheet.num_images, output_format: gen.sheet.output_format }
if (refs.length) input.image_urls = refs
requests.push({ id: opts.stage === 'draft' ? 'sheet-draft' : `sheet-${quality}`, model: refs.length ? gen.sheet.model_with_photo : gen.sheet.model, input, approx_cost_usd: Number(sheetCost(quality, refs.length).toFixed(3)) })
} else {
if (unfilled(ch.reference) || !existsSync(rel(ch.reference))) fail('character.reference is empty or missing. Approve a sheet first (compose-sheet.mjs --art ... sets it), then make the scene tests.')
const refsFor = () => {
const refs = [imageRef(ch.reference, 'The text-free sheet (character.reference)')]
const extra = []
if (ch.photo) {
refs.push(imageRef(ch.photo, 'The photo (character.photo)'))
extra.push('Reference image 2 is the user\'s own photo of the same person: the face must be exactly theirs.')
}
return { refs, extra }
}
if (opts.stage === 'scene') {
const wanted = !opts.scene || opts.scene === 'all' ? [1, 2, 3] : opts.scene.split(',').map(Number)
if (wanted.some((n) => !Number.isInteger(n) || n < 1 || n > 3)) fail('--scene takes 1, 2, 3, a list like 1,3, or all.')
for (const n of wanted) {
const s = ch.scenes.find((x) => x.n === n)
const { refs, extra } = refsFor()
const prompt = fill(section('Scene test'), { scene: `${s.prompt.charAt(0).toUpperCase()}${s.prompt.slice(1).replace(/[.]$/, '')}.`, lock_text: lock, look: sceneLook }) + (extra.length ? ` ${extra.join(' ')}` : '')
requests.push({
id: `scene-${n}`,
model: gen.scene.model,
input: { prompt, image_urls: refs, aspect_ratio: gen.scene.aspect_ratio, resolution: gen.scene.resolution, num_images: 1, output_format: gen.scene.output_format },
approx_cost_usd: sceneCost,
})
}
} else if (opts.stage === 'alt') {
if (unfilled(ch.wardrobe_alt)) fail('The character has no wardrobe_alt. Add one in character.json first.')
const { refs, extra } = refsFor()
const prompt = fill(section('Second outfit'), { backdrop: gen.sheet.backdrop, lock_text_short: ch.lock_text_short.replace(/[.]$/, ''), wardrobe_alt: `${ch.wardrobe_alt.replace(/[.]$/, '')}.`, look }) + (extra.length ? ` ${extra.join(' ')}` : '')
requests.push({ id: 'outfit-alt', model: gen.scene.model, input: { prompt, image_urls: refs, aspect_ratio: gen.scene.aspect_ratio, resolution: gen.scene.resolution, num_images: 1, output_format: gen.scene.output_format }, approx_cost_usd: sceneCost })
} else {
const n = Number(opts.scene ?? 1)
const s = ch.scenes.find((x) => x.n === n)
if (!s) fail('--scene takes 1, 2 or 3 for a clip.')
if (unfilled(s.image) || !existsSync(rel(s.image))) fail(`Scene ${n} has no image yet. Make and approve the scene tests first and put the path in character.json.`)
const model = opts.model ?? 'kling'
if (!gen.clip[model]) fail('--model must be kling or seedance.')
if (model === 'seedance' && ch.look !== 'clay') console.error('warning: Seedance refused a photoreal face and a stylised 3D face in the sample run (fal: may contain likenesses of real people), and fal may still bill the call. Use --model kling.')
const action = opts.action ?? 'The character slowly turns their head and shoulders to look straight into the lens, holds a calm steady gaze, then blinks once. The camera holds still.'
const prompt = `${action.replace(/[.]$/, '')}. Hair, outfit, props and every locked detail stay exactly as in the frame: ${ch.lock_text_short} No other people, no text, no cuts.`
const c = gen.clip[model]
const image = imageRef(s.image, `Scene ${n} image`)
const input = model === 'kling' ? { image_url: image, prompt, duration: c.duration } : { image_url: image, prompt, resolution: c.resolution, duration: c.duration, aspect_ratio: c.aspect_ratio, generate_audio: c.generate_audio }
requests.push({ id: `clip-${n}-${model}`, model: c.model, input, approx_cost_usd: Number(clipCost(model).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: ${money(total)}.`)
} else {
console.log(JSON.stringify(requests, null, 2))
console.error(`${requests.length} request(s), approximate cost ${money(total)}. Local images are shown as file: paths; use --out with --inline to embed them, or fal-run.mjs (which embeds them).`)
}