#!/usr/bin/env node // Builds the exact model requests for one stage from plan.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), or paste the prompt and images into any Nano-Banana-class image editor and // Kling-class image-to-video tool. // // Stages: // estimate no requests: the expected total, to quote to the user and get one yes on before the first paid call // keyframe the "after" still from the cropped before photo (Nano Banana Pro edit, 9:16, 2K) // draft a cheap motion test: Seedance 2.0 mini, 480p, silent (not for the people version: it refuses faces) // final the silent after clip: Kling 3 pro (default), Veo 3.1 fast or Seedance 2.5 // // The loading bar, the freeze and the flash are never requested from a model: assemble-reveal.mjs draws them. // // Usage: // node scripts/build-requests.mjs --plan plan.json --stage estimate|keyframe|draft|final // [--out requests/] [--inline] [--model kling|veo|seedance] // // --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 { fileURLToPath } from 'node:url' const FLAGS = new Set(['plan', 'stage', 'out', 'inline', 'model']) const SWITCHES = new Set(['inline']) const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp' } const KEYFRAME = { model: 'fal-ai/nano-banana-pro/edit', cost: 0.15 } const DRAFT = { model: 'bytedance/seedance-2.0/mini/image-to-video', perSecond: 0.0721 } const FINALS = { kling: { model: 'fal-ai/kling-video/v3/pro/image-to-video', name: 'Kling 3 pro', silent: 0.112, durations: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] }, veo: { model: 'fal-ai/veo3.1/fast/image-to-video', name: 'Veo 3.1 fast 720p', silent: 0.1, durations: [4, 6, 8] }, seedance: { model: 'bytedance/seedance-2.5/image-to-video', name: 'Seedance 2.5 720p', silent: 0.473, durations: [4, 5, 6, 7, 8, 9, 10, 11, 12] }, } const WORD = { pet: 'pet', room: 'room', product: 'product', sketch: 'drawing', person: 'person' } const root = join(dirname(fileURLToPath(import.meta.url)), '..') 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 plan.json --stage estimate|keyframe|draft|final [--out dir] [--inline] [--model kling|veo|seedance]') if (!['estimate', 'keyframe', 'draft', 'final'].includes(opts.stage)) fail(`--stage must be estimate, keyframe, draft or final, not "${opts.stage}".`) if (opts.inline && !opts.out) fail('--inline writes large data URIs; use it with --out .') if (!existsSync(opts.plan)) fail(`Plan not found: ${opts.plan}. Create it with scripts/build-plan.mjs.`) let plan try { plan = JSON.parse(readFileSync(opts.plan, 'utf8')) } catch { fail(`${opts.plan} is not valid JSON.`) } const base = dirname(resolve(opts.plan)) const rel = (p) => (isAbsolute(p) ? p : join(base, p)) const brief = plan.brief ?? {} const subject = plan.subject ?? {} const reveal = plan.reveal ?? {} const isPerson = subject.kind === 'person' const finalKey = opts.model ?? brief.final_model ?? 'kling' const final = FINALS[finalKey] if (!final) fail(`--model must be kling, veo or seedance, not "${finalKey}".`) const duration = Number(brief.after ?? 5) if (!final.durations.includes(duration)) fail(`brief.after ${brief.after} s is not available on ${final.name}. Use ${final.durations.join(', ')} seconds.`) if (isPerson && finalKey === 'seedance') fail('Seedance refuses a clearly visible realistic face. The people version uses Kling.') const useDraft = brief.draft !== false && !isPerson const round = (v) => Number(v.toFixed(3)) const finalCost = round(final.silent * duration) const draftCost = round(DRAFT.perSecond * duration) if (opts.stage === 'estimate') { const lines = [['After still: Nano Banana Pro edit 2K', KEYFRAME.cost]] if (useDraft) lines.push([`Draft: ${duration} s Seedance 2.0 mini 480p, silent`, draftCost]) lines.push([`Final: ${duration} s ${final.name}, silent`, finalCost]) lines.push(['Loading bar, freeze, flash and beat marker (ffmpeg, local)', 0]) const total = lines.reduce((a, [, v]) => a + v, 0) const withRerolls = total + KEYFRAME.cost + finalCost for (const [label, v] of lines) console.log(` ${label.padEnd(62)} $${v.toFixed(2)}`) console.log(` ${'Without re-rolls'.padEnd(62)} $${total.toFixed(2)}`) console.log(` ${'With one still re-roll and one final re-roll'.padEnd(62)} $${withRerolls.toFixed(2)}`) const others = Object.entries(FINALS).filter(([k]) => k !== finalKey).map(([, f]) => `${f.name} $${(f.silent * duration).toFixed(2)}`) console.log(`\n One ${duration} s silent final on the other models: ${others.join(', ')}.`) if (isPerson) console.log('\n People version: no draft, because Seedance refuses a clearly visible realistic face. The first Kling final is the test.') else if (!useDraft) console.log('\n No draft (--no-draft): the first Kling final is the test.') console.log(`\nQuote to the user: about $${total.toFixed(2)} for one reveal, up to about $${withRerolls.toFixed(2)} with re-rolls.`) 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 = (text) => typeof text === 'string' && text.includes('FILL:') function field(text, where) { if (typeof text !== 'string' || !text.trim()) fail(`${where} is empty. Write it in ${opts.plan} first.`) if (unfilled(text)) fail(`${where} still contains "FILL:". Write it in ${opts.plan} first.`) return text.trim() } const sentence = (text) => (/[.!?]$/.test(text) ? text : `${text}.`) 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')}` } if (isPerson) { const c = plan.consent ?? {} if (!c.confirmed || !c.own_photo_or_written_consent || !c.adult || !c.not_a_public_figure) fail('A people reveal needs consent.confirmed, own_photo_or_written_consent, adult and not_a_public_figure all true in the plan (references/safety-and-likeness.md).') field(c.statement, 'consent.statement') } const lock = field(subject.lock, 'subject.lock') const kind = WORD[subject.kind] ?? 'subject' const gen = JSON.parse(readFileSync(join(root, 'assets', 'generation-input.json'), 'utf8')) const requests = [] if (opts.stage === 'keyframe') { if (!subject.prepared) fail('subject.prepared is empty. Run scripts/prepare-before.mjs and put the 9:16 photo there.') const refs = [imageRef(subject.prepared, 'Before photo'), ...(subject.refs ?? []).map((p, i) => imageRef(p, `Reference photo ${i + 1}`))] const extra = refs.length > 1 ? ' The other reference photos show the product or details to match exactly; use them for that and for nothing else.' : '' const people = isPerson ? "Keep the person's face, hair, skin tone, age, build and expression exactly as in the photo. Only the styling named below changes. No other people." : subject.kind === 'pet' ? 'No people and no other animals anywhere in the frame.' : 'No people and no animals anywhere in the frame.' const prompt = [ 'Edit the first reference photo into its "after" frame, vertical 9:16.', `Keep the camera position, framing, angle, lens, background, light and phone-photo look exactly as in the photo, so that a cut between the two reads as the same moment. The ${kind} stays at the same size and in the same place in the frame.${extra}`, `What must not change: ${sentence(lock)}`, sentence(field(reveal.after, 'reveal.after')), people, 'Natural, slightly imperfect phone-photo quality with the same noise and colour as the reference, not a polished studio look. The main subject sits in the middle of the frame, clear of the top 12% and the bottom 20%.', 'No text, no logos, no watermark, no loading bar, no screen or interface elements.', ].join(' ').replace(/\s+/g, ' ').trim() requests.push({ id: 'reveal-after-keyframe', model: KEYFRAME.model, input: { prompt, image_urls: refs, ...gen.keyframe.input }, approx_cost_usd: KEYFRAME.cost }) } else { if (!plan.files?.keyframe) fail('files.keyframe is empty. Generate the after still, put it beside the before photo, and put its path there.') if (opts.stage === 'draft' && !useDraft) fail(isPerson ? 'No draft for the people version: Seedance refuses a clearly visible realistic face. Go straight to the Kling final and treat it as the test.' : 'brief.draft is false in the plan (--no-draft), so there is no draft stage. The Kling final is the test.') const people = isPerson ? 'The person keeps exactly their face, hair and look from the first frame and moves only a little. No other people appear.' : subject.kind === 'pet' ? 'The pet keeps exactly its coat, markings, eyes and size from the first frame, and moves like a real animal: calm, comfortable, never scared, never falling. No people and no other animals appear.' : 'Nobody and no animal appears.' const prompt = [ sentence(field(reveal.camera, 'reveal.camera')), sentence(field(reveal.motion, 'reveal.motion')), subject.kind === 'pet' || isPerson ? '' : `The ${kind} keeps exactly its look from the first frame: the same shape, colours and details.`, people, 'One continuous shot from the first frame: no cuts, no fades, no flash, no white frames. No text, captions, loading bar, progress bar or interface on screen. No sound is needed.', ].filter(Boolean).join(' ').replace(/\s+/g, ' ').trim() const image = imageRef(plan.files.keyframe, 'After still') if (opts.stage === 'draft') { const input = { prompt, image_url: image, ...gen.video.draft.input, duration: String(duration) } requests.push({ id: 'reveal-draft', model: DRAFT.model, input, approx_cost_usd: draftCost }) } else { let input if (finalKey === 'kling') input = { prompt, start_image_url: image, ...gen.video.final.kling.input, duration: String(duration), negative_prompt: gen.video.negative_prompt } else if (finalKey === 'veo') input = { prompt, image_url: image, ...gen.video.final.veo.input, duration: `${duration}s`, negative_prompt: gen.video.negative_prompt } else input = { prompt, image_url: image, ...gen.video.final.seedance.input, duration: String(duration) } requests.push({ id: `reveal-final-${finalKey}`, model: final.model, input, approx_cost_usd: finalCost }) } } 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).`) }