#!/usr/bin/env node // Builds the exact image requests for the cover art from series.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 // any 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 cover per title at low quality, 720 x 1280, to agree subjects, the title band and the look // final the finished art at medium quality, 1088 x 1936. Do cover 1 first (--cover 1); once it is approved, // put its path in references.anchor, and covers 2 onwards carry it as the look reference (--cover rest) // // Usage: // node scripts/build-requests.mjs --series series.json --stage estimate|draft|final // [--cover 1|all|rest|2,3,4] [--quality low|medium|high] [--out requests/] [--inline] // // Every cover's art is text-free: the exact title is drawn later by scripts/compose-covers.mjs. // --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 cover's "draft": its final carries it as a reference, // so the finished cover 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(['series', 'stage', 'cover', 'quality', '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.series || !opts.stage) fail('Usage: node scripts/build-requests.mjs --series series.json --stage estimate|draft|final [--cover 1|all|rest|2,3] [--out dir] [--inline]') if (opts.stage === 'keyframe') fail('This Skill has no keyframe stage: use --stage draft for rough covers, then --stage final.') 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 (!existsSync(opts.series)) fail(`Plan not found: ${opts.series}. Create it with scripts/new-series.mjs.`) let plan try { plan = JSON.parse(readFileSync(opts.series, 'utf8')) } catch { fail(`${opts.series} 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 !== 'reel-cover-set/1') fail(`${opts.series} schema is "${plan.schema}", expected reel-cover-set/1 (make it with scripts/new-series.mjs).`) const base = dirname(resolve(opts.series)) const rel = (p) => (isAbsolute(p) ? p : join(base, p)) const series = plan.series ?? {} const style = plan.style ?? {} const covers = plan.covers ?? [] const palette = Array.isArray(plan.palette) ? plan.palette : [] const maxRefs = gen.max_references ?? 3 if (![3, 6, 9].includes(covers.length)) fail(`The plan has ${covers.length} covers. Plan 3, 6 or 9 (full rows of the profile grid).`) covers.forEach((c, i) => { if (c.n !== i + 1) fail(`Covers must be numbered 1 to ${covers.length} in order (found ${c.n} at position ${i + 1}).`) }) const people = series.people ?? 'none' if (!['none', 'fictional', 'real-with-consent'].includes(people)) fail(`series.people must be none, fictional or real-with-consent, not "${people}".`) const withPerson = covers.filter((c) => c.still && c.still_has_person) const consentProblem = withPerson.length && (people !== 'real-with-consent' || series.consent_confirmed !== true) ? `Cover(s) ${withPerson.map((c) => c.n).join(', ')} use a still with a person in it. Set series.people to "real-with-consent" and series.consent_confirmed to true only after the person shown (or everyone shown) has agreed in plain words to appear. Never use a photo of a celebrity, a public figure, a child or anyone who has not agreed; otherwise remove the still or crop the person out.` : '' 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 per1024 = gen.approx_cost.per_1024_square const perRef = gen.approx_cost.per_reference_image const cost = ({ size, quality }, refs) => (per1024[quality] * size.width * size.height) / (1024 * 1024) + refs * perRef /** The references one cover will carry at a stage, before any file is read. */ function plannedRefs(c, stage, assumeDrafts) { const out = [] if (c.still) out.push(['still', c.still]) if (stage === 'final') { if (c.n !== 1) out.push(['anchor', plan.references?.anchor || '(approved cover 1)']) if (c.draft || assumeDrafts) out.push(['draft', c.draft || '(approved draft)']) } return out.slice(0, maxRefs) } if (opts.stage === 'estimate') { const draft = stageOf('draft') const final = stageOf('final') const sum = (stage, s, assume) => covers.reduce((a, c) => a + cost(s, plannedRefs(c, stage, assume).length), 0) const drafts = sum('draft', draft, false) const finalsAfterDrafts = sum('final', final, true) const finalsOnly = sum('final', final, false) const reroll = cost(final, Math.min(maxRefs, 2 + (covers.some((c) => c.still) ? 1 : 0))) const stills = covers.filter((c) => c.still).length console.log(`Set: ${covers.length} covers for "${series.name ?? '(no name)'}", ${stills} with a still from your own video.`) console.log(` ${`Drafts (quality ${draft.quality}, ${draft.size.width} x ${draft.size.height})`.padEnd(58)} $${drafts.toFixed(2)}`) console.log(` ${`Finals after drafts (quality ${final.quality}, ${final.size.width} x ${final.size.height})`.padEnd(58)} $${finalsAfterDrafts.toFixed(2)}`) console.log(` ${'Finals with no drafts first'.padEnd(58)} $${finalsOnly.toFixed(2)}`) console.log(` ${'A re-roll of one final (about)'.padEnd(58)} $${reroll.toFixed(2)}`) const usual = drafts + finalsAfterDrafts const top = usual + 2 * reroll 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 titles, the grid preview 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.') if (consentProblem) console.error(`\nwarning: ${consentProblem}`) if (style.position && !gen.empty_space[style.position]) console.error(`warning: style.position "${style.position}" is not top, middle or bottom.`) process.exit(0) } if (consentProblem) fail(consentProblem) const unfilled = (t) => typeof t === 'string' && t.includes('FILL:') 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 (plan.look.includes('{{colour}}') && !palette.length) fail('The look has {{colour}} but the palette is empty.') const space = gen.empty_space[style.position ?? 'top'] if (!space) fail(`style.position must be top, middle or bottom, not "${style.position}".`) 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'}. For a video, export one frame first.`) 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 = covers if (opts.cover && opts.cover !== 'all') { if (opts.cover === 'rest') picked = covers.filter((c) => c.n !== 1) else { const wanted = opts.cover.split(',').map((x) => Number(x.trim())) if (wanted.some((n) => !Number.isInteger(n))) fail(`--cover takes a cover number, a list like 2,3,4, "rest" or "all", not "${opts.cover}".`) picked = wanted.map((n) => covers.find((c) => c.n === n) ?? fail(`There is no cover ${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 cover that is mostly seen small.') const requests = [] for (const c of picked) { const where = `cover ${c.n}` if (typeof c.subject !== 'string' || !c.subject.trim() || unfilled(c.subject)) fail(`${where} has no subject yet. Write what it shows in series.json (references/prompt-patterns.md).`) if (/["“”]/.test(c.subject) || /\b(?:text|title|caption|words?|lettering|reads?|saying|logo)\b/i.test(c.subject)) { console.error(`warning: ${where} subject mentions words, quotes or a logo. The art must stay text-free; the title is drawn later. Describe only the picture.`) } const colour = palette.length ? palette[(c.n - 1) % palette.length] : '' const look = plan.look.replace(/\{\{colour\}\}/g, colour).trim().replace(/[.]$/, '') const refs = [] const lines = [] if (c.still) { refs.push(imageRef(c.still, `Still for ${where}`)) lines.push(`Reference image ${refs.length} is a frame from the creator's own video for this episode: keep its main subject, setting and the arrangement of the scene recognisable, and restyle it into the series look.`) if (c.still_has_person) { lines.push(`The person in reference image ${refs.length} must stay exactly themselves: the same identity, age range, skin tone, hair, facial structure and body. Do not change their ethnicity, add or remove features, or give them an expression, injury or action they did not have.`) } } if (opts.stage === 'final' && c.n !== 1) { if (plan.references?.anchor) { refs.push(imageRef(plan.references.anchor, 'Cover 1 art (references.anchor)')) lines.push(`Reference image ${refs.length} is cover 1 of the same series: match its art direction exactly (backdrop treatment, light direction, lens, grain and finish) and keep the same calm band for the title, but show this cover's own subject${palette.length > 1 ? ' and this cover\'s own backdrop colour as written above' : ''}. Do not copy its subject.`) } else { console.error(`warning: ${where} has no look reference. Approve cover 1 first and put its art path in references.anchor, so every final matches it.`) } } if (opts.stage === 'final' && c.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 subject instead.`) else { refs.push(imageRef(c.draft, `Draft for ${where}`)) lines.push(`Reference image ${refs.length} is the approved rough draft of this cover: keep its composition, framing and the place of every element, and render it cleanly in full detail.`) } } const stillPeople = c.still && c.still_has_person ? ' No people other than the person in the reference.' : '' const peopleRule = { none: c.still ? 'No people in the image unless they are in the reference frame.' : 'Nobody in the image.', fictional: 'Any person is a fictional adult who does not resemble any real or famous person, and never a child. No other people anywhere in the frame.', 'real-with-consent': c.still && c.still_has_person ? stillPeople.trim() : 'Any other person is a fictional adult who does not resemble any real or famous person, and never a child.', }[people] const textRule = c.still ? 'IMPORTANT: render no new words, letters, numbers, logos, signs, captions, watermarks or app interface anywhere; keep lettering only where it is printed on the creator\'s own product in the reference. The exact title is added later in code.' : 'IMPORTANT: render no words, letters, numbers, logos, signs, labels, captions, watermarks or app interface anywhere in the image. The exact title is added later in code.' const prompt = template .replace('{{look}}', () => look) .replace('{{subject}}', () => c.subject.trim().replace(/[.]$/, '')) .replace('{{space}}', () => space) .replace('{{grid_rule}}', () => gen.grid_rule) .replace('{{references}}', () => lines.join(' ')) .replace('{{people}}', () => peopleRule) .replace('{{text_rule}}', () => textRule) .replace(/\s+/g, ' ') .trim() const input = { prompt, image_size: stage.size, quality: stage.quality, ...gen.input } if (refs.length) input.image_urls = refs requests.push({ id: `cover-${String(c.n).padStart(2, '0')}-${opts.stage}`, model: refs.length ? gen.model_with_references : gen.model, input, approx_cost_usd: Number(cost(stage, 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).`) }