// Article reel with narration: up to five article links become a narrated, // captioned news reel. Per article: 2 credits for the read and 8 for its two // slides; once: 6 for the script, 9 for the narration, 6 for the music and 2 // per started minute of narration for the word timings; the final is 15 // credits for each started 10 seconds. Five articles and a 50-second reel are // about 148 credits. The Preview is free. // The calls of the page https://api.oneupai.com/docs/recipes/article-reel, in // its order, as one program. // // export ONEUP_API_KEY="oneup_live_…" # your Builder key // npx tsx run.mts "https://…/story-1" "https://…/story-2" # Node.js 20+ // // ONEUP_BASE_URL changes the host (default https://api.oneupai.com). Every // answer is printed as it arrives. const API = process.env.ONEUP_BASE_URL ?? "https://api.oneupai.com"; const KEY = process.env.ONEUP_API_KEY; if (!KEY) throw new Error("Set ONEUP_API_KEY to your API key first"); const LINKS = process.argv.slice(2); if (LINKS.length < 1 || LINKS.length > 5) throw new Error("Give one to five article links as arguments"); const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const retryKey = () => ({ "Idempotency-Key": crypto.randomUUID() }); // One API call: the answer is printed and returned; a refusal stops here. // A 429 carries Retry-After: wait that long, then send the SAME request again // with the SAME Idempotency-Key, which can never charge twice. async function call( method: string, path: string, body?: object, headers?: Record ) { for (;;) { const res = await fetch(API + path, { signal: AbortSignal.timeout(60_000), method, headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json", ...headers, }, body: body && JSON.stringify(body), }); const json = await res.json(); console.log(JSON.stringify(json)); if (res.status === 429) { await sleep(Number(res.headers.get("Retry-After") ?? 5) * 1000); continue; } if (!res.ok) throw new Error(`${res.status} ${json.error}: ${json.message}`); return json; } } const submit = async (alias: string, body: object): Promise => (await call("POST", `/v1/queue/submit/${alias}`, body, retryKey())).ticket; // Waits for a queued job (every 2 s for 30 s, then every 5 s); its result. async function waitFor(ticket: string) { const started = Date.now(); let status = await call("GET", `/v1/queue/status/${ticket}`); while (status.status !== "COMPLETED" && status.status !== "FAILED") { await sleep(Date.now() - started < 30_000 ? 2000 : 5000); status = await call("GET", `/v1/queue/status/${ticket}`); } return call("GET", `/v1/queue/result/${ticket}`); } async function render(projectId: string, versionId: string, kind: string) { let r = await call( "POST", "/v1/renders", { alias: "oneup/render-timeline", project_id: projectId, version_id: versionId, kind, }, retryKey() ); const renderId = r.render_id; while (r.status !== "COMPLETED" && r.status !== "FAILED") { await sleep(5000); r = await call("GET", `/v1/renders/${renderId}`); } return r; } // 1. Read each page (2 credits each; a page it cannot use is refunded). type Article = { title: string; site: string; text: string }; const articles: Article[] = []; for (const url of LINKS) articles.push( (await call("POST", "/v1/run/oneup/web-read-article", { url }, retryKey())) .output ); // 2. The script, as JSON. The prompt and the context share one limit of // 16,000 characters, counted as JSON (a line break or a quote is two), so // each article gets an even share of what the prompt leaves. const SHAPE = "{ hook, items: [{ headline, narration, slide_a, slide_b }] }"; const prompt = `Write a 50-second news reel as JSON: ${SHAPE}. One item per article, ` + "in the order given. hook is one short line shown before the first item. " + "narration is what the voice says for that item, in one or two short " + "sentences. slide_a and slide_b each describe a picture for it. Answer " + "with one fenced json block."; const fit = (text: string, max: number) => { while (JSON.stringify(text).length > max) text = text.slice(0, Math.floor(text.length * 0.9)); return text; }; const share = Math.floor( (15_500 - JSON.stringify(prompt).length) / LINKS.length ); const context = articles .map((a) => fit(`${a.title}\n${a.site}\n${a.text}`, share)) .join("\n\n"); type Script = { hook: string; items: { headline: string; narration: string; slide_a: string; slide_b: string; }[]; }; // The JSON block of the answer, or what is wrong with it. function readScript(output: string): Script | string { const block = /```(?:json)?\s*\n([\s\S]*?)```/.exec(output); let s: Script; try { s = JSON.parse(block ? block[1]! : output); } catch { return "the answer has no JSON block that parses"; } if (typeof s?.hook !== "string" || !s.hook) return "hook must be a string"; if (!Array.isArray(s.items) || !s.items.length) return "items must be a list with at least one item"; for (const [i, item] of s.items.entries()) for (const k of ["headline", "narration", "slide_a", "slide_b"] as const) if (typeof item?.[k] !== "string" || !item[k]) return `items[${i}].${k} must be a string`; return s; } const first = await call( "POST", "/v1/run/oneup/text-script", { prompt, context }, retryKey() ); let script = readScript(first.output); if (typeof script === "string") { // One repair call quoting the problem, then stop. const repair = await call( "POST", "/v1/run/oneup/text-script", { prompt: `Your JSON had this problem: ${script}. Answer again with only the corrected JSON, shaped ${SHAPE}, in one fenced json block.`, context: fit(first.output, 12_000), }, retryKey() ); script = readScript(repair.output); if (typeof script === "string") throw new Error(`the script: ${script}`); } const { hook, items } = script; // 3. Two slides per item, the narration, the music; then wait for each. const slideBody = (text: string) => ({ prompt: text, quality: "medium", image_size: { width: 736, height: 1280 }, output_format: "jpeg", }); const slideTickets: [string, string][] = []; for (const item of items) slideTickets.push([ await submit("oneup/image-generate-standard", slideBody(item.slide_a)), await submit("oneup/image-generate-standard", slideBody(item.slide_b)), ]); // The narration, cut at a sentence end under 1,000 characters. let narration = items.map((item) => item.narration).join(" "); if (narration.length > 1000) { const cut = narration.slice(0, 1000); const end = Math.max( cut.lastIndexOf(". "), cut.lastIndexOf("! "), cut.lastIndexOf("? ") ); narration = end > 0 ? cut.slice(0, end + 1) : cut; } const voiceTicket = await submit("oneup/speech-standard", { prompt: narration, }); const musicTicket = await submit("oneup/audio-song", { prompt: "calm newsroom bed, no vocals", lyrics_prompt: "[Instrumental]", }); const slides: [string, string][] = []; for (const [a, b] of slideTickets) slides.push([ (await waitFor(a)).assets[0].asset_id, (await waitFor(b)).assets[0].asset_id, ]); const voice = (await waitFor(voiceTicket)).assets[0]; const music = (await waitFor(musicTicket)).assets[0].asset_id; // 4. The word timings of the narration, and its length. const words = await waitFor( await submit("oneup/speech-transcribe", { audio_url: voice.url }) ); const annotationId = words.annotation.annotation_id; const narrationMs = (await call("GET", `/v1/assets/${voice.asset_id}/url`)) .duration_ms; if (typeof narrationMs !== "number") throw new Error("the narration's length is not known"); // 5. The Timeline: a 3-second hook slide, then two segments per item, each // half of that item's share of the narration. const pushIn = { op: "kenburns", from: { x: 0.5, y: 0.5, zoom: 1 }, to: { x: 0.5, y: 0.5, zoom: 1.1 }, ease: "ease_in_out", }; const pan = { op: "kenburns", from: { x: 0.55, y: 0.5, zoom: 1.1 }, to: { x: 0.45, y: 0.5, zoom: 1.1 }, ease: "ease_in_out", }; const total = 3000 + narrationMs; const weight = items.reduce((sum, item) => sum + item.narration.length, 0); const segments: object[] = [ { id: "hook", source: { $asset: slides[0]![0] }, fit: "cover", duration: 3000, effects: [pushIn], transition_out: { op: "cut", duration: 0 }, }, ]; const overlays: object[] = [ { id: "hook_text", kind: "text", content: hook, style: "headline", position: "center", range: { from: 0, to: 3000 }, }, ]; let at = 3000; items.forEach((item, i) => { const ms = i === items.length - 1 ? total - at : Math.round((narrationMs * item.narration.length) / weight); const half = Math.floor(ms / 2); const [a, b] = slides[i]!; segments.push( { id: `a${i + 1}s1`, source: { $asset: a }, fit: "cover", duration: half, effects: [pushIn], }, { id: `a${i + 1}s2`, source: { $asset: b }, fit: "cover", duration: ms - half, effects: [pan], } ); const range = { from: at, to: at + ms }; overlays.push( { id: `a${i + 1}_headline`, kind: "text", content: item.headline, style: "headline", position: "top", range, }, { id: `a${i + 1}_source`, kind: "text", content: articles[Math.min(i, articles.length - 1)]!.site, style: "lower_third", position: "bottom", range, } ); at += ms; }); // The last segment fades out. (segments[segments.length - 1] as { effects: object[] }).effects.push({ op: "fade", from: 1, to: 0, duration: 600, }); const timeline = { v: "1.6", output: { aspect: "9:16", resolution: 1080, fps: 30, container: "mp4" }, segments, overlays, audio: [ { id: "voiceover", role: "voiceover", source: { $asset: voice.asset_id }, range: { from: 3000, to: total }, }, { id: "bed", role: "music", source: { $asset: music }, range: { from: 0, to: total }, loop: true, gain: -16, fade_in: 600, fade_out: 1000, ducking: { against: "voiceover", amount_db: -12, attack: 120, release: 400, }, }, ], // The transcript's word times start at 0 in the narration file; the // narration starts at 3 s, so `offset` moves every word there. captions: [ { id: "captions", source: { $annotation: annotationId }, language: "en", highlight: "word_by_word", style: { preset: "caption_bold_outline" }, offset: 3000, range: { from: 3000, to: total }, }, ], }; // 6. Save it, a free Preview, the final, then the MP4's link (an hour). const project = await call("POST", "/v1/projects", { agent_slug: "oneup/render-timeline", }); const projectId = project.project_id; const version = await call("PUT", `/v1/projects/${projectId}/timeline`, { timeline, }); await render(projectId, version.version_id, "preview"); const final = await render(projectId, version.version_id, "final"); await call("GET", `/v1/queue/result/${final.ticket}`);