Article reel with narration

On this page

Up to five article links become a narrated, captioned news reel. By the end of this page you will know each step: read each page, write the script as JSON, make two slides per article, the narration, a music bed and the word timings, then put it all together. Every step is an ordinary generation, so you can chain them with your own API key.

What it costs #

  • For each article: 2 credits for the read and 8 for its two slides (4 each).
  • Once: 7 for the script, 11 for the narration, 7 for the music and 2 for each started minute of narration for the word timings.
  • The video: 15 credits for each started 10 seconds of the final. The Preview is free.

Five articles and a 50-second reel come to 50 + 27 + 75 = 152 credits, about $1.55. The reel's length follows the narration: a longer narration makes a longer reel and bills the extra 10-second block.

The calls, in order #

for each link:
POST /v1/run/oneup/web-read-article  (Idempotency-Key)  {"url": "https://…/story"}
  → {"alias": "oneup/web-read-article",
     "output": {"title", "site", "byline"?, "published"?, "text", "images": [{"url", "width"?, "height"?, "alt"?}], "extraction_id"}}
  refunded: page_paywalled | page_not_article | page_unreadable | page_unreachable

POST /v1/run/oneup/text-script  (Idempotency-Key)
  {"prompt": "Write a 50-second news reel as JSON: { hook, items: [{ headline, narration, slide_a, slide_b }] } …",
   "context": "<an even share of the 16,000-character limit for each article: title, site, the opening of the text>"}
  → {"alias": "oneup/text-script", "output": "<a fenced json block>"}
  read the JSON; if its shape is wrong, make ONE repair call quoting the problem, then stop

for each item, once with slide_a and once with slide_b:
POST /v1/queue/submit/oneup/image-generate-standard  (Idempotency-Key)
  {"prompt": "<the slide text>", "quality": "medium", "image_size": {"width": 736, "height": 1280}, "output_format": "jpeg"}

POST /v1/queue/submit/oneup/speech-standard  (Idempotency-Key)  {"prompt": "<the narration, cut at a sentence end under 1,000 characters>"}
POST /v1/queue/submit/oneup/audio-song           (Idempotency-Key)  {"prompt": "calm newsroom bed, no vocals", "lyrics_prompt": "[Instrumental]"}
POST /v1/queue/submit/oneup/speech-transcribe      (Idempotency-Key)  {"audio_url": "<the narration's asset url>"}
  → its result carries {"annotation": {"annotation_id", "size_bytes", "url"}}

poll each ticket; send submits at your plan's pace: a 429 carries Retry-After, then retry with the SAME Idempotency-Key

POST /v1/projects                         {"agent_slug": "oneup/render-timeline"}     → {"project_id"}
PUT  /v1/projects/{project_id}/timeline   {"timeline": <the Timeline below>}      → {"version_id"}
POST /v1/renders  (Idempotency-Key)       {"alias": "oneup/render-timeline", "project_id", "version_id", "kind": "preview"}
POST /v1/renders  (Idempotency-Key)       {"alias": "oneup/render-timeline", "project_id", "version_id", "kind": "final"}
GET  /v1/renders/{render_id}              → {"status": "COMPLETED", "ticket", …}
GET  /v1/queue/result/{ticket}            → {"assets": [the MP4]}
  • The article reader takes a public https page and needs at least 300 characters of prose. It refuses a property listing site and names the right reader: 400 invalid_request with detail use_listing_extract.
  • A page it reaches but cannot use is refunded, with 422 invalid_input and one of these as detail: page_paywalled (the page says it is behind a paywall), page_not_article, page_unreadable (too little of the article came back) or page_unreachable.
  • Page reads, this one and the listing reader together, are limited to 10 a minute and 60 a day.
  • oneup/text-script is a writing model built for the Agents' scripts. Its output is text, so read the JSON block out of it yourself.

The Timeline #

A hook slide, then two segments per article, each half of that article's narration. Headline text sits on top, the site's name at the bottom. The narration plays from the end of the hook, and the music bed dips under it. The captions come from the narration's word-timed transcript, an annotation referenced as $annotation. The transcript's word times start at 0, at the start of the narration file, but the narration starts 3 seconds into the video, so the caption track carries "offset": 3000 to move every word to where it is heard. offset needs version 1.6 or newer of the Timeline language, so v is "1.6". The last segment fades out.

{
  "v": "1.6",
  "output": { "aspect": "9:16", "resolution": 1080, "fps": 30, "container": "mp4" },
  "segments": [
    { "id": "hook", "source": { "$asset": "<slide a1>" }, "fit": "cover", "duration": 3000,
      "effects": [{ "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" }],
      "transition_out": { "op": "cut", "duration": 0 } },
    { "id": "a1s1", "source": { "$asset": "<slide a1>" }, "fit": "cover", "duration": <half the item's narration>, "effects": [ … kenburns … ] },
    { "id": "a1s2", "source": { "$asset": "<slide b1>" }, "fit": "cover", "duration": <the other half> },
    "… two segments per article; the last one ends with { \"op\": \"fade\", \"from\": 1, \"to\": 0, \"duration\": 600 } in its effects …"
  ],
  "overlays": [
    { "id": "hook_text", "kind": "text", "content": "<hook>", "style": "headline", "position": "center", "range": { "from": 0, "to": 3000 } },
    { "id": "a1_headline", "kind": "text", "content": "<headline>", "style": "headline", "position": "top", "range": { "from": 3000, "to": 9666 } },
    { "id": "a1_source", "kind": "text", "content": "<site>", "style": "lower_third", "position": "bottom", "range": { "from": 3000, "to": 9666 } }
  ],
  "audio": [
    { "id": "voiceover", "role": "voiceover", "source": { "$asset": "<narration>" }, "range": { "from": 3000, "to": <3000 + narration ms> } },
    { "id": "bed", "role": "music", "source": { "$asset": "<music>" }, "range": { "from": 0, "to": <total ms> }, "loop": true, "gain": -16,
      "fade_in": 600, "fade_out": 1000, "ducking": { "against": "voiceover", "amount_db": -12, "attack": 120, "release": 400 } }
  ],
  "captions": [
    { "id": "captions", "source": { "$annotation": "<annotation_id>" }, "language": "en", "highlight": "word_by_word",
      "style": { "preset": "caption_bold_outline" }, "offset": 3000, "range": { "from": 3000, "to": <3000 + narration ms> } }
  ]
}

Run it #

Each version is one program, shown in full below and downloadable from the examples folder: run.sh (curl and jq), run.mts (Node.js 20 or newer: npx tsx run.mts) and run.py (Python 3.8 or newer: python3 run.py). Each one makes the calls above in order, prints every answer, and stops at the first call that is refused. Give it one to five article links, for example python3 run.py "https://…/story-1" "https://…/story-2".

curl
#!/usr/bin/env bash
# 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
#   bash run.sh "https://…/story-1" "https://…/story-2"
#
# Needs curl, jq and uuidgen. ONEUP_BASE_URL changes the host (default
# https://api.oneupai.com). Every answer is printed as it arrives.

set -euo pipefail
: "${ONEUP_API_KEY:?Set ONEUP_API_KEY to your API key first}"
API=${ONEUP_BASE_URL:-https://api.oneupai.com}
if [ $# -lt 1 ] || [ $# -gt 5 ]; then
  echo "Give one to five article links as arguments" >&2
  exit 1
fi
HEADERS=$(mktemp)
trap 'rm -f "$HEADERS"' EXIT

# One API call; the answer is printed and kept in OUT. 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.
api() {
  local method=$1 path=$2 wait
  shift 2
  while :; do
    OUT=$(curl -sS -D "$HEADERS" -X "$method" "$API$path" \
      -H "Authorization: Bearer $ONEUP_API_KEY" \
      -H "Content-Type: application/json" "$@")
    echo "$OUT"
    if echo "$OUT" | jq -e '.error == "rate_limited"' > /dev/null 2>&1; then
      wait=$(grep -i '^retry-after:' "$HEADERS" | tr -dc '0-9')
      sleep "${wait:-5}"
      continue
    fi
    break
  done
  if ! echo "$OUT" | jq -e 'type == "object" and (has("error") | not)' > /dev/null; then
    echo "refused: $method $path" >&2
    exit 1
  fi
}

# Starts a queued job; its ticket is left in TICKET.
submit() {
  api POST "/v1/queue/submit/$1" -H "Idempotency-Key: $(uuidgen)" -d "$2"
  TICKET=$(echo "$OUT" | jq -r .ticket)
}

# Waits for a queued job (every 2 s for 30 s, then every 5 s) and leaves its
# result in OUT.
wait_for() {
  local start=$SECONDS
  api GET "/v1/queue/status/$1"
  until echo "$OUT" | jq -e '.status == "COMPLETED" or .status == "FAILED"' > /dev/null; do
    if [ $((SECONDS - start)) -lt 30 ]; then sleep 2; else sleep 5; fi
    api GET "/v1/queue/status/$1"
  done
  api GET "/v1/queue/result/$1"
}

# Starts a render, waits for it, and leaves the finished render in OUT.
render() {
  api POST /v1/renders -H "Idempotency-Key: $(uuidgen)" \
    -d "$(jq -n --arg p "$PROJECT" --arg v "$VERSION" --arg k "$1" \
      '{alias: "oneup/render-timeline", project_id: $p, version_id: $v, kind: $k}')"
  local id
  id=$(echo "$OUT" | jq -r .render_id)
  until echo "$OUT" | jq -e '.status == "COMPLETED" or .status == "FAILED"' > /dev/null; do
    sleep 5
    api GET "/v1/renders/$id"
  done
}

# 1. Read each page (2 credits each; a page it cannot use is refunded).
ARTICLES='[]'
for url in "$@"; do
  api POST /v1/run/oneup/web-read-article -H "Idempotency-Key: $(uuidgen)" \
    -d "$(jq -n --arg u "$url" '{url: $u}')"
  ARTICLES=$(echo "$ARTICLES" | jq -c --argjson a "$(echo "$OUT" | jq -c .output)" '. + [$a]')
done

# 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.
SHAPE='{ hook, items: [{ headline, narration, slide_a, slide_b }] }'
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."
FIT='def fit($max): if (tojson | length) > $max then .[0:((length * 0.9) | floor)] | fit($max) else . end;'
# The JSON block of the answer as {script}, or {problem} saying what is wrong.
READ_SCRIPT='
  .output
  | ((capture("```(?:json)?\\s*\\n(?<j>[\\s\\S]*?)```") | .j) // .)
  | (try fromjson catch null) as $s
  | if ($s | type) != "object" then {problem: "the answer has no JSON block that parses"}
    elif ($s.hook | type) != "string" or $s.hook == "" then {problem: "hook must be a string"}
    elif ($s.items | type) != "array" or ($s.items | length) == 0 then {problem: "items must be a list with at least one item"}
    else ([$s.items | to_entries[] | .key as $i | .value as $item
            | ("headline", "narration", "slide_a", "slide_b") as $k
            | select(($item | type) != "object" or ($item[$k] | type) != "string" or $item[$k] == "")
            | "items[\($i)].\($k) must be a string"] | .[0]) as $p
      | if $p then {problem: $p} else {script: $s} end
    end'

api POST /v1/run/oneup/text-script -H "Idempotency-Key: $(uuidgen)" \
  -d "$(jq -n --arg prompt "$PROMPT" --argjson articles "$ARTICLES" "$FIT"'
    ((15500 - ($prompt | tojson | length)) / ($articles | length) | floor) as $share
    | {prompt: $prompt,
       context: ([$articles[] | "\(.title)\n\(.site)\n\(.text)" | fit($share)] | join("\n\n"))}')"
CHECK=$(echo "$OUT" | jq -c "$READ_SCRIPT")
if echo "$CHECK" | jq -e 'has("problem")' > /dev/null; then
  # One repair call quoting the problem, then stop.
  PROBLEM=$(echo "$CHECK" | jq -r .problem)
  FIRST=$(echo "$OUT" | jq -r .output)
  api POST /v1/run/oneup/text-script -H "Idempotency-Key: $(uuidgen)" \
    -d "$(jq -n --arg p "Your JSON had this problem: $PROBLEM. Answer again with only the corrected JSON, shaped $SHAPE, in one fenced json block." \
      --arg c "$FIRST" "$FIT"' {prompt: $p, context: ($c | fit(12000))}')"
  CHECK=$(echo "$OUT" | jq -c "$READ_SCRIPT")
  if echo "$CHECK" | jq -e 'has("problem")' > /dev/null; then
    echo "the script: $(echo "$CHECK" | jq -r .problem)" >&2
    exit 1
  fi
fi
SCRIPT=$(echo "$CHECK" | jq -c .script)

# 3. Two slides per item, the narration, the music; then wait for each.
SLIDE_TICKETS='[]'
COUNT=$(echo "$SCRIPT" | jq '.items | length')
for i in $(seq 0 $((COUNT - 1))); do
  for side in slide_a slide_b; do
    submit oneup/image-generate-standard "$(echo "$SCRIPT" | jq -c --argjson i "$i" --arg s "$side" \
      '{prompt: .items[$i][$s], quality: "medium", image_size: {width: 736, height: 1280}, output_format: "jpeg"}')"
    SLIDE_TICKETS=$(echo "$SLIDE_TICKETS" | jq -c --arg t "$TICKET" '. + [$t]')
  done
done

# The narration, cut at a sentence end under 1,000 characters.
NARRATION=$(echo "$SCRIPT" | jq -r '
  [.items[].narration] | join(" ")
  | if length > 1000 then
      .[0:1000] as $cut
      | ([($cut | rindex(". ")), ($cut | rindex("! ")), ($cut | rindex("? "))] | map(. // -1) | max) as $end
      | if $end > 0 then $cut[0:($end + 1)] else $cut end
    else . end')
submit oneup/speech-standard "$(jq -n --arg p "$NARRATION" '{prompt: $p}')"
VOICE_TICKET=$TICKET
submit oneup/audio-song '{"prompt": "calm newsroom bed, no vocals", "lyrics_prompt": "[Instrumental]"}'
MUSIC_TICKET=$TICKET

SLIDES='[]'
for ticket in $(echo "$SLIDE_TICKETS" | jq -r '.[]'); do
  wait_for "$ticket"
  SLIDES=$(echo "$SLIDES" | jq -c --arg id "$(echo "$OUT" | jq -r '.assets[0].asset_id')" '. + [$id]')
done
wait_for "$VOICE_TICKET"
VOICE=$(echo "$OUT" | jq -r '.assets[0].asset_id')
VOICE_URL=$(echo "$OUT" | jq -r '.assets[0].url')
wait_for "$MUSIC_TICKET"
MUSIC=$(echo "$OUT" | jq -r '.assets[0].asset_id')

# 4. The word timings of the narration, and its length.
submit oneup/speech-transcribe "$(jq -n --arg u "$VOICE_URL" '{audio_url: $u}')"
wait_for "$TICKET"
ANNOTATION=$(echo "$OUT" | jq -r .annotation.annotation_id)
api GET "/v1/assets/$VOICE/url"
NARRATION_MS=$(echo "$OUT" | jq .duration_ms)
if [ "$NARRATION_MS" = null ]; then
  echo "the narration's length is not known" >&2
  exit 1
fi

# 5. The Timeline: a 3-second hook slide, then two segments per item, each
#    half of that item's share of the narration. The transcript's word times
#    start at 0 in the narration file; the narration starts at 3 s, so the
#    caption track's offset moves every word there.
TIMELINE=$(jq -n --argjson script "$SCRIPT" --argjson articles "$ARTICLES" \
  --argjson slides "$SLIDES" --arg voice "$VOICE" --arg music "$MUSIC" \
  --arg annotation "$ANNOTATION" --argjson ms "$NARRATION_MS" '
  {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"} as $pushIn
  | {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"} as $pan
  | (3000 + $ms) as $total
  | $script.items as $items
  | ([$items[].narration | length] | add) as $weight
  | [$items[:-1][] | ($ms * (.narration | length) / $weight | round)] as $heads
  | ($heads + [$ms - ($heads | add // 0)]) as $lengths
  | [foreach $lengths[] as $l (3000; . + $l; [. - $l, $l])] as $spans
  | {
      v: "1.6",
      output: {aspect: "9:16", resolution: 1080, fps: 30, container: "mp4"},
      segments: (
        [{id: "hook", source: {"$asset": $slides[0]}, fit: "cover", duration: 3000,
          effects: [$pushIn], transition_out: {op: "cut", duration: 0}}]
        + [range(0; $items | length) as $i | ($spans[$i][1]) as $l | (($l / 2) | floor) as $half
            | {id: "a\($i + 1)s1", source: {"$asset": $slides[2 * $i]}, fit: "cover",
               duration: $half, effects: [$pushIn]},
              {id: "a\($i + 1)s2", source: {"$asset": $slides[2 * $i + 1]}, fit: "cover",
               duration: ($l - $half), effects: [$pan]}]
        | (length - 1) as $last
        | .[$last].effects += [{op: "fade", from: 1, to: 0, duration: 600}]),
      overlays: (
        [{id: "hook_text", kind: "text", content: $script.hook, style: "headline",
          position: "center", range: {from: 0, to: 3000}}]
        + [range(0; $items | length) as $i
            | {from: $spans[$i][0], to: ($spans[$i][0] + $spans[$i][1])} as $r
            | {id: "a\($i + 1)_headline", kind: "text", content: $items[$i].headline,
               style: "headline", position: "top", range: $r},
              {id: "a\($i + 1)_source", kind: "text",
               content: $articles[[$i, ($articles | length) - 1] | min].site,
               style: "lower_third", position: "bottom", range: $r}]),
      audio: [
        {id: "voiceover", role: "voiceover", source: {"$asset": $voice},
         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}}
      ],
      captions: [
        {id: "captions", source: {"$annotation": $annotation}, 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).
api POST /v1/projects -d '{"agent_slug": "oneup/render-timeline"}'
PROJECT=$(echo "$OUT" | jq -r .project_id)
api PUT "/v1/projects/$PROJECT/timeline" -d "$(jq -n --argjson t "$TIMELINE" '{timeline: $t}')"
VERSION=$(echo "$OUT" | jq -r .version_id)
render preview
render final
api GET "/v1/queue/result/$(echo "$OUT" | jq -r .ticket)"
TypeScript
// 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<string, string>
) {
  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<string> =>
  (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}`);
Python
#!/usr/bin/env python3
# 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
#   python3 run.py "https://.../story-1" "https://.../story-2"   # Python 3.8+
#
# ONEUP_BASE_URL changes the host (default https://api.oneupai.com). Every
# answer is printed as it arrives. Standard library only.

import json, os, re, sys, time, urllib.error, urllib.request, uuid

API = os.environ.get("ONEUP_BASE_URL", "https://api.oneupai.com")
KEY = os.environ["ONEUP_API_KEY"]
# The default Python User-Agent is refused before a request reaches the API;
# any name for your app works.
AGENT = "my-app/1.0"
LINKS = sys.argv[1:]
if not 1 <= len(LINKS) <= 5:
    raise SystemExit("Give one to five article links as arguments")


def call(method, path, body=None, headers=None):
    """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."""
    while True:
        request = urllib.request.Request(
            API + path,
            method=method,
            data=None if body is None else json.dumps(body).encode(),
            headers={
                "Authorization": f"Bearer {KEY}",
                "Content-Type": "application/json",
                "User-Agent": AGENT,
                **(headers or {}),
            },
        )
        try:
            with urllib.request.urlopen(request, timeout=60) as response:
                answer = json.load(response)
        except urllib.error.HTTPError as error:
            problem = json.load(error)
            print(json.dumps(problem))
            if error.code == 429:
                time.sleep(int(error.headers.get("Retry-After") or 5))
                continue
            raise SystemExit(f"{error.code} {problem['error']}: {problem['message']}")
        print(json.dumps(answer))
        return answer


def retry_key():
    return {"Idempotency-Key": str(uuid.uuid4())}


def submit(alias, body):
    return call("POST", f"/v1/queue/submit/{alias}", body, retry_key())["ticket"]


def wait_for(ticket):
    """Waits for a queued job (every 2 s for 30 s, then every 5 s); its result."""
    started = time.monotonic()
    status = call("GET", f"/v1/queue/status/{ticket}")
    while status["status"] not in ("COMPLETED", "FAILED"):
        time.sleep(2 if time.monotonic() - started < 30 else 5)
        status = call("GET", f"/v1/queue/status/{ticket}")
    return call("GET", f"/v1/queue/result/{ticket}")


def render(project_id, version_id, kind):
    r = call(
        "POST",
        "/v1/renders",
        {
            "alias": "oneup/render-timeline",
            "project_id": project_id,
            "version_id": version_id,
            "kind": kind,
        },
        retry_key(),
    )
    render_id = r["render_id"]
    while r["status"] not in ("COMPLETED", "FAILED"):
        time.sleep(5)
        r = call("GET", f"/v1/renders/{render_id}")
    return r


# 1. Read each page (2 credits each; a page it cannot use is refunded).
articles = [
    call("POST", "/v1/run/oneup/web-read-article", {"url": url}, retry_key())["output"]
    for url in LINKS
]

# 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.
SHAPE = "{ hook, items: [{ headline, narration, slide_a, slide_b }] }"
prompt = (
    f"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."
)


def fit(text, limit):
    while len(json.dumps(text)) > limit:
        text = text[: int(len(text) * 0.9)]
    return text


share = (15500 - len(json.dumps(prompt))) // len(LINKS)
context = "\n\n".join(
    fit(f"{a['title']}\n{a['site']}\n{a['text']}", share) for a in articles
)


def read_script(output):
    """The JSON block of the answer, or a string saying what is wrong."""
    block = re.search(r"```(?:json)?\s*\n(.*?)```", output, re.S)
    try:
        s = json.loads(block.group(1) if block else output)
    except ValueError:
        return "the answer has no JSON block that parses"
    if not isinstance(s, dict) or not isinstance(s.get("hook"), str) or not s["hook"]:
        return "hook must be a string"
    if not isinstance(s.get("items"), list) or not s["items"]:
        return "items must be a list with at least one item"
    for i, item in enumerate(s["items"]):
        for k in ("headline", "narration", "slide_a", "slide_b"):
            if not isinstance(item, dict) or not isinstance(item.get(k), str) or not item[k]:
                return f"items[{i}].{k} must be a string"
    return s


first = call(
    "POST",
    "/v1/run/oneup/text-script",
    {"prompt": prompt, "context": context},
    retry_key(),
)
script = read_script(first["output"])
if isinstance(script, str):
    # One repair call quoting the problem, then stop.
    repair = call(
        "POST",
        "/v1/run/oneup/text-script",
        {
            "prompt": f"Your JSON had this problem: {script}. Answer again with only the corrected JSON, shaped {SHAPE}, in one fenced json block.",
            "context": fit(first["output"], 12000),
        },
        retry_key(),
    )
    script = read_script(repair["output"])
    if isinstance(script, str):
        raise SystemExit(f"the script: {script}")
hook, items = script["hook"], script["items"]


# 3. Two slides per item, the narration, the music; then wait for each.
def slide_body(text):
    return {
        "prompt": text,
        "quality": "medium",
        "image_size": {"width": 736, "height": 1280},
        "output_format": "jpeg",
    }


slide_tickets = [
    (
        submit("oneup/image-generate-standard", slide_body(item["slide_a"])),
        submit("oneup/image-generate-standard", slide_body(item["slide_b"])),
    )
    for item in items
]

# The narration, cut at a sentence end under 1,000 characters.
narration = " ".join(item["narration"] for item in items)
if len(narration) > 1000:
    cut = narration[:1000]
    end = max(cut.rfind(". "), cut.rfind("! "), cut.rfind("? "))
    narration = cut[: end + 1] if end > 0 else cut
voice_ticket = submit("oneup/speech-standard", {"prompt": narration})
music_ticket = submit(
    "oneup/audio-song",
    {"prompt": "calm newsroom bed, no vocals", "lyrics_prompt": "[Instrumental]"},
)

slides = [
    (
        wait_for(a)["assets"][0]["asset_id"],
        wait_for(b)["assets"][0]["asset_id"],
    )
    for a, b in slide_tickets
]
voice = wait_for(voice_ticket)["assets"][0]
music = wait_for(music_ticket)["assets"][0]["asset_id"]

# 4. The word timings of the narration, and its length.
words = wait_for(submit("oneup/speech-transcribe", {"audio_url": voice["url"]}))
annotation_id = words["annotation"]["annotation_id"]
narration_ms = call("GET", f"/v1/assets/{voice['asset_id']}/url")["duration_ms"]
if not isinstance(narration_ms, int):
    raise SystemExit("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.
push_in = {
    "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",
}
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",
}
total = 3000 + narration_ms
weight = sum(len(item["narration"]) for item in items)
segments = [
    {
        "id": "hook",
        "source": {"$asset": slides[0][0]},
        "fit": "cover",
        "duration": 3000,
        "effects": [push_in],
        "transition_out": {"op": "cut", "duration": 0},
    }
]
overlays = [
    {
        "id": "hook_text",
        "kind": "text",
        "content": hook,
        "style": "headline",
        "position": "center",
        "range": {"from": 0, "to": 3000},
    }
]
at = 3000
for i, item in enumerate(items):
    if i == len(items) - 1:
        ms = total - at
    else:
        ms = round(narration_ms * len(item["narration"]) / weight)
    half = ms // 2
    a, b = slides[i]
    segments += [
        {"id": f"a{i + 1}s1", "source": {"$asset": a}, "fit": "cover", "duration": half, "effects": [dict(push_in)]},
        {"id": f"a{i + 1}s2", "source": {"$asset": b}, "fit": "cover", "duration": ms - half, "effects": [dict(pan)]},
    ]
    site = articles[min(i, len(articles) - 1)]["site"]
    overlays += [
        {"id": f"a{i + 1}_headline", "kind": "text", "content": item["headline"], "style": "headline", "position": "top", "range": {"from": at, "to": at + ms}},
        {"id": f"a{i + 1}_source", "kind": "text", "content": site, "style": "lower_third", "position": "bottom", "range": {"from": at, "to": at + ms}},
    ]
    at += ms
# The last segment fades out.
segments[-1]["effects"] = segments[-1]["effects"] + [
    {"op": "fade", "from": 1, "to": 0, "duration": 600}
]

timeline = {
    "v": "1.6",
    "output": {"aspect": "9:16", "resolution": 1080, "fps": 30, "container": "mp4"},
    "segments": segments,
    "overlays": 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": annotation_id},
            "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).
project = call("POST", "/v1/projects", {"agent_slug": "oneup/render-timeline"})
project_id = project["project_id"]
version = call("PUT", f"/v1/projects/{project_id}/timeline", {"timeline": timeline})
render(project_id, version["version_id"], "preview")
final = render(project_id, version["version_id"], "final")
call("GET", f"/v1/queue/result/{final['ticket']}")