#!/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 Veo-class image-to-video tool. // // Stages: // estimate no requests: the expected total for every clip in the plan, to quote to the user and get // one yes on before the first paid call // keyframe one start frame per clip from the pet photos (Nano Banana Pro edit, 9:16, 2K) // draft cheap motion test per clip: Seedance 2.0 mini, 480p, silent // final the clip with sound: Kling 3 pro (default), Veo 3.1 fast 720p or Seedance 2.5 // // Usage: // node scripts/build-requests.mjs --plan plan.json --stage estimate|keyframe|draft|final // [--clip 1|all] [--out requests/] [--inline] [--model veo|kling|seedance] [--silent] // // --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', 'clip', 'out', 'inline', 'model', 'silent']) const SWITCHES = new Set(['inline', 'silent']) 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 = { veo: { model: 'fal-ai/veo3.1/fast/image-to-video', name: 'Veo 3.1 fast 720p', audio: 0.15, silent: 0.1, durations: [4, 6, 8] }, kling: { model: 'fal-ai/kling-video/v3/pro/image-to-video', name: 'Kling 3 pro', audio: 0.168, silent: 0.112, durations: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] }, seedance: { model: 'bytedance/seedance-2.5/image-to-video', name: 'Seedance 2.5 720p', audio: 0.473, silent: 0.473, durations: [4, 5, 6, 7, 8, 9, 10, 11, 12] }, } const SPECIES = { dog: 'dog', cat: 'cat', other: 'animal of its kind' } 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 [--clip N|all] [--out dir] [--inline] [--model veo|kling|seedance] [--silent]') 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 pet = plan.pet ?? {} const finalKey = opts.model ?? brief.final_model ?? 'kling' const final = FINALS[finalKey] if (!final) fail(`--model must be veo, kling or seedance, not "${finalKey}".`) const duration = Number(brief.duration ?? 8) if (!final.durations.includes(duration)) fail(`brief.duration ${brief.duration} is not available on ${final.name}. Use ${final.durations.join(', ')} seconds.`) const audio = !opts.silent && brief.audio !== false const allClips = plan.clips ?? [] if (!allClips.length) fail('The plan has no clips.') let clips = allClips if (opts.clip && opts.clip !== 'all') { const n = Number(opts.clip) if (!Number.isInteger(n)) fail(`--clip takes a clip number or "all", not "${opts.clip}".`) clips = allClips.filter((c) => c.n === n) if (!clips.length) fail(`There is no clip ${n} in the plan.`) } const round = (v) => Number(v.toFixed(3)) const finalCost = round((audio ? final.audio : final.silent) * duration) const draftCost = round(DRAFT.perSecond * duration) if (opts.stage === 'estimate') { const n = allClips.length const lines = [ [`Keyframes: ${n} x Nano Banana Pro edit 2K`, n * KEYFRAME.cost], [`Drafts: ${n} x ${duration} s Seedance 2.0 mini 480p`, n * draftCost], [`Finals: ${n} x ${duration} s ${final.name}${audio ? ' with sound' : ' silent'}`, n * finalCost], ] const total = lines.reduce((a, [, v]) => a + v, 0) const withRerolls = total + n * KEYFRAME.cost + finalCost for (const [label, v] of lines) console.log(` ${label.padEnd(58)} $${v.toFixed(2)}`) console.log(` ${'Without re-rolls'.padEnd(58)} $${total.toFixed(2)}`) console.log(` ${'With one keyframe re-roll per clip and one final re-roll'.padEnd(58)} $${withRerolls.toFixed(2)}`) const others = Object.entries(FINALS).filter(([k]) => k !== finalKey).map(([, f]) => `${f.name} $${((audio ? f.audio : f.silent) * duration).toFixed(2)}`) console.log(`\n One ${duration} s final on the other models: ${others.join(', ')}.`) console.log(`\nQuote to the user: about $${total.toFixed(2)} for ${n} clip(s), 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')}` } const lock = field(pet.lock, 'pet.lock') const species = SPECIES[pet.kind] ?? SPECIES.other const gen = JSON.parse(readFileSync(join(root, 'assets', 'generation-input.json'), 'utf8')) const requests = [] for (const c of clips) { const where = `clip ${c.n}` const person = c.person === 'hands' ? 'hands' : 'none' // The lock is said once, up front; scene and action text call it "the pet". const withPet = (text) => text.replace(/(^|[.!?]\s+)\{\{PET\}\}/g, '$1The pet').replaceAll('{{PET}}', 'the pet') if (opts.stage === 'keyframe') { const photos = pet.photos ?? [] if (!photos.length || photos.length > 3) fail(`pet.photos must list 1 to 3 photos of the pet, not ${photos.length}.`) const refs = photos.map((p, i) => imageRef(p, `Pet photo ${i + 1}`)) let room = '' if (plan.references?.room) { refs.push(imageRef(plan.references.room, 'Room photo')) room = ' The room is the one in the last reference image: the same cabinets, walls, floor and light.' } const people = person === 'hands' ? 'The only person is seen as a hand and forearm, the rest out of frame, never a face. No other animals.' : 'No people and no other animals anywhere in the frame.' const prompt = [ "Vertical 9:16 photo: one frame from a casual handheld phone video filmed in a real, lived-in home, at the pet's eye level with the phone's normal lens.", `The pet is the one in the reference photos: ${sentence(lock)} Keep it exactly as it is: the same breed look, coat colour and pattern, markings in the same places, eye colour, ear shape, body size and proportions. Do not change, idealise or recolour it, and keep it its real size next to the furniture.`, sentence(withPet(field(c.scene, `${where} scene`))) + room, people, 'Natural, slightly uneven home light, a little phone noise, everyday clutter, true-to-life animal anatomy with four legs and normal paws.', "The pet's face and the action sit in the middle of the frame, clear of the top 12% and the bottom 20%.", 'Unbranded appliances and objects, no text, no logos, no readable screens, no watermark.', ].join(' ').replace(/\s+/g, ' ').trim() requests.push({ id: `${c.id}-keyframe`, model: KEYFRAME.model, input: { prompt, image_urls: refs, ...gen.keyframe.input }, approx_cost_usd: KEYFRAME.cost }) continue } if (!c.keyframe) fail(`${where} has no approved keyframe yet. Generate it, put it beside the pet photos, and put its path in "keyframe".`) const people = person === 'hands' ? 'Only the hand and forearm are ever seen, never a face, and no other people or animals appear.' : 'No people and no other animals appear.' const prompt = [ "Handheld phone video, one continuous take at the pet's eye level, the phone held fairly steady with a slight natural hand sway, no zoom, no cuts.", sentence(withPet(field(c.action, `${where} action`))), 'The pet keeps exactly its look from the first frame: the same coat colour and pattern, markings, eyes and size.', `It moves like a real ${species}, with simple paw and head movements and natural weight. It stays calm and playful throughout and never falls, slips or looks scared.`, people, `Audio: ${sentence(field(c.sound, `${where} sound`))}`, c.music ? '' : 'No music.', 'No speech, no voiceover, no subtitles or text on screen.', ].filter(Boolean).join(' ').replace(/\s+/g, ' ').trim() const image = imageRef(c.keyframe, `${where} keyframe`) if (opts.stage === 'draft') { const input = { prompt: prompt.replace(/ Audio: .*?(?= No speech)/, ''), image_url: image, ...gen.video.draft.input, duration: String(duration) } requests.push({ id: `${c.id}-draft`, model: DRAFT.model, input, approx_cost_usd: draftCost }) continue } const negative = `${gen.video.negative_prompt}${c.music ? '' : ', music'}` let input if (finalKey === 'veo') input = { prompt, image_url: image, ...gen.video.final.veo.input, duration: `${duration}s`, generate_audio: audio, negative_prompt: negative } else if (finalKey === 'kling') input = { prompt, start_image_url: image, ...gen.video.final.kling.input, duration: String(duration), generate_audio: audio, negative_prompt: negative } else input = { prompt, image_url: image, ...gen.video.final.seedance.input, duration: String(duration), generate_audio: audio } requests.push({ id: `${c.id}-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).`) }