#!/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']}")