From ff4d0506fe254217e04ae5789a714a20eaae88cf Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 06:08:18 +0500 Subject: [PATCH 01/12] Add clips.py from the video clipping guide, as published --- examples/video-clipping-pipeline/clips.py | 610 ++++++++++++++++++++++ 1 file changed, 610 insertions(+) create mode 100644 examples/video-clipping-pipeline/clips.py diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py new file mode 100644 index 0000000..318d245 --- /dev/null +++ b/examples/video-clipping-pipeline/clips.py @@ -0,0 +1,610 @@ +#!/usr/bin/env python3 +"""Turn a long recording into short, vertical, captioned clips with the Shotstack API. + + python clips.py RECORDING_URL [--limit N] [--repick] + +Step 1 imports the recording with Shotstack's Ingest API and gets its transcript. +Step 2 asks Claude to pick the best moments and saves them to moments.json. +Step 3 renders each moment twice: once to cut it out and fit it into a vertical +frame, and once to add captions generated from the cut's own audio. +Step 4 does that for every moment and downloads the finished clips. + +Everything for one recording goes in clips//. Progress is saved to +manifest.json in that folder after every step, so running the same command again +picks up where the last run stopped instead of repeating work. + +Environment variables: + SHOTSTACK_API_KEY your Shotstack API key + ANTHROPIC_API_KEY your Anthropic API key (only needed to pick moments) + SHOTSTACK_ENV "v1" for production (the default) or "stage" for the sandbox +""" +import argparse +import hashlib +import json +import os +import re +import sys +import time +from collections import namedtuple +from pathlib import Path +from urllib.parse import urlparse + +import anthropic +import requests + +SHOTSTACK_ENV = os.environ.get("SHOTSTACK_ENV", "v1") +INGEST = f"https://api.shotstack.io/ingest/{SHOTSTACK_ENV}" +EDIT = f"https://api.shotstack.io/edit/{SHOTSTACK_ENV}" +HEADERS = {"x-api-key": os.environ.get("SHOTSTACK_API_KEY", ""), "Accept": "application/json"} + +CLIP_COUNT = 5 +MIN_SECONDS, MAX_SECONDS = 15, 60 + +POLL_SECONDS = 10 +IMPORT_TIMEOUT = 60 * 60 # stop waiting for the import and transcript after an hour +RENDER_TIMEOUT = 60 * 60 # and for the renders + + +def fail(message): + sys.exit(f"\nStopped: {message}") + + +def clock(seconds): + """1234.5 -> '20:34'""" + minutes, seconds = divmod(int(seconds), 60) + return f"{minutes}:{seconds:02d}" + + +class Manifest(dict): + """What's been done for one recording, saved to manifest.json after every change.""" + + def __init__(self, path, url): + super().__init__(json.loads(path.read_text()) if path.exists() else {"url": url}) + self.path = path + if self["url"] != url: + if set(self) == {"url"}: # nothing was done for the old URL, like after a failed import + self["url"] = url + else: + fail(f"{path.parent} belongs to a different recording: {self['url']}. " + "Delete or rename that folder to start over with this URL.") + + def save(self): + self.path.write_text(json.dumps(self, indent=2)) + + +# ---------------------------------------------------------------- Shotstack requests + +class ApiError(Exception): + """Shotstack answered with an error.""" + + +class Unresolved(Exception): + """A submit request that may or may not have reached Shotstack.""" + + +def check(response): + if response.status_code in (401, 403): + kind = "production" if SHOTSTACK_ENV == "v1" else "sandbox" + fail(f"Shotstack refused the API key ({response.status_code}). " + f"SHOTSTACK_API_KEY must be your {kind} key.") + if response.status_code >= 400: + raise ApiError(f"{response.status_code} from {response.url}: {response.text[:300]}") + return response.json() + + +def post_json(url, body): + """POST once. Sending the same submit twice could start a duplicate job.""" + try: + response = requests.post(url, headers=HEADERS, json=body, timeout=60) + except requests.RequestException as error: + raise Unresolved(str(error)) from error + return check(response) + + +def get_json(url): + """GET a status, retrying network errors, rate limits and server errors.""" + for attempt in range(1, 6): + try: + response = requests.get(url, headers=HEADERS, timeout=30) + if response.status_code != 429 and response.status_code < 500: + return check(response) + except requests.RequestException: + pass + time.sleep(5 * attempt) + fail(f"GET {url} kept failing. Run the same command again to carry on.") + + +def download(url, path): + """Save a file Shotstack hosts. No API key: these are plain file URLs.""" + with requests.get(url, stream=True, timeout=120) as response: + response.raise_for_status() + with open(path, "wb") as file: + for chunk in response.iter_content(chunk_size=1 << 20): + file.write(chunk) + + +# ---------------------------------------------------------------- step 1: import and transcribe + +def import_recording(url, manifest, folder): + """Import the recording with the Ingest API and wait for its SRT transcript.""" + if "source_id" not in manifest: + body = {"url": url, "outputs": {"transcription": {"format": "srt"}}} + manifest["source_id"] = post_json(f"{INGEST}/sources", body)["data"]["id"] + manifest.save() + print(f"Importing the recording (source {manifest['source_id']})") + + started, seen = time.time(), None + while True: + source = get_json(f"{INGEST}/sources/{manifest['source_id']}")["data"]["attributes"] + transcript = (source.get("outputs") or {}).get("transcription") or {} + status = (source.get("status"), transcript.get("status")) + if status != seen: + print(f" {clock(time.time() - started)} file: {status[0]}, transcript: {status[1] or 'waiting'}") + seen = status + if "failed" in status: + del manifest["source_id"] # so the next run starts a new import + manifest.save() + reason = source.get("error") or "no reason given" + if not source.get("duration"): + reason += ". Shotstack didn't get a video from that URL: it must return the file itself" + fail(f"the import failed ({reason}).") + if status == ("ready", "ready"): + break + if time.time() - started > IMPORT_TIMEOUT: + fail("the import is taking over an hour. Run the same command again to keep waiting.") + time.sleep(POLL_SECONDS) + + # Every render below needs the recording's length, so check it's there first. + if not source.get("duration"): + fail("the import has no duration, so the URL may not point to a video. " + "Check that the URL returns the file itself.") + srt = requests.get(transcript["url"], timeout=60) + srt.raise_for_status() + (folder / "transcript.srt").write_text(srt.content.decode("utf-8"), encoding="utf-8") + manifest.update(source_url=source["source"], duration=source["duration"]) + manifest.save() + print(f"Imported {clock(source['duration'])} of video and saved {folder / 'transcript.srt'}") + + +Cue = namedtuple("Cue", "start end text") + + +def parse_srt(text): + """Read an SRT file into a list of cues, with times in seconds.""" + def seconds(timestamp): + hours, minutes, secs = timestamp.strip().replace(",", ".").split(":") + return int(hours) * 3600 + int(minutes) * 60 + float(secs) + + cues = [] + for block in text.replace("\r\n", "\n").strip().split("\n\n"): + lines = block.strip().split("\n") + for i, line in enumerate(lines): + if "-->" in line: + start, end = line.split("-->") + cues.append(Cue(seconds(start), seconds(end.split()[0]), " ".join(lines[i + 1:]))) + break + return cues + + +# ---------------------------------------------------------------- step 2: pick the moments + +MODEL = "claude-sonnet-5-5" +MAX_TOKENS = 1000 +# Sonnet 5.5 can't turn thinking off. "between_tools" is its lowest setting: no +# thinking before it answers, and this request has no tools to think between. +THINKING = {"type": "between_tools"} + +PROMPT = f"""\ +You pick moments from a talk transcript to turn into short vertical video clips. + +The transcript has one sentence per line. Each line starts with the time the +sentence begins, in minutes and seconds. + +Pick the {CLIP_COUNT} best moments. A moment is a run of whole, consecutive sentences. +Every moment must: +- last {MIN_SECONDS} to {MAX_SECONDS} seconds (aim for 25 to 45) +- make sense on its own, without anything said earlier or anything shown on a slide +- not overlap any other moment + +Prefer moments with a clear point, a strong opinion or a practical tip, and skip +introductions and housekeeping. + +For each moment, copy the first six to ten words of its first sentence and the last +six to ten words of its last sentence exactly as they appear in the transcript, and +give it a short title of at most eight words. List the moments from best to worst.""" + +MOMENTS_SCHEMA = { + "type": "object", + "properties": { + "moments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "first_words": {"type": "string"}, + "last_words": {"type": "string"}, + "title": {"type": "string"}, + }, + "required": ["first_words", "last_words", "title"], + "additionalProperties": False, + }, + }, + }, + "required": ["moments"], + "additionalProperties": False, +} + + +def sentences(cues): + """Join the transcript's short subtitle lines into whole sentences, so every + moment starts and ends on a sentence boundary.""" + result, parts, start = [], [], None + for cue in cues: + if start is None: + start = cue.start + parts.append(cue.text.strip()) + if cue.text.rstrip().endswith((".", "?", "!")): + result.append(Cue(start, cue.end, " ".join(parts))) + parts, start = [], None + if parts: + result.append(Cue(start, cues[-1].end, " ".join(parts))) + return result + + +def transcript_text(lines): + """The transcript for the prompt: one sentence per line, with its start time.""" + return "\n".join(f"[{int(line.start // 60)}:{int(line.start % 60):02d}] {line.text}" + for line in lines) + + +def words(text): + """Lowercase words without punctuation, so a quote matches however it's punctuated.""" + return re.findall(r"[a-z0-9]+", text.lower().replace("'", "").replace("\u2019", "")) + + +def locate(quote, lines, after=0): + """Find a quote in the transcript, from line `after` on. Returns the indexes of + the lines where it starts and ends, or None if it isn't there.""" + target = words(quote) + stream = [(word, i) for i, line in enumerate(lines) for word in words(line.text)] + for k in range(len(stream) - len(target) + 1): + if target and stream[k][1] >= after and [w for w, _ in stream[k:k + len(target)]] == target: + return stream[k][1], stream[k + len(target) - 1][1] + return None + + +def ask_claude(client, messages): + """One request to Claude. Structured outputs make the reply JSON that matches the schema.""" + response = client.messages.create( + model=MODEL, + max_tokens=MAX_TOKENS, + thinking=THINKING, + system=PROMPT, + messages=messages, + output_config={"format": {"type": "json_schema", "schema": MOMENTS_SCHEMA}}, + ) + if response.stop_reason != "end_turn": + fail(f"Claude stopped early ({response.stop_reason}), so its reply isn't complete.") + text = next(block.text for block in response.content if block.type == "text") + return json.loads(text)["moments"] + + +def check_picks(picks, lines, duration): + """Find each moment's quotes in the transcript, turn them into start and end + times, and check the rules. Returns the moments that pass, best first, and a + list of problems.""" + moments, problems = [], [] + if len(picks) < CLIP_COUNT: + problems.append(f"there are {len(picks)} moments, not {CLIP_COUNT}") + for n, pick in enumerate(picks, 1): + where = f"moment {n} (\"{pick['title']}\")" + found = locate(pick["first_words"], lines) + if not found: + problems.append(f"{where}: the transcript doesn't contain \"{pick['first_words']}\"") + continue + first = found[0] + found = locate(pick["last_words"], lines, after=first) + if not found: + problems.append(f"{where}: the transcript doesn't contain \"{pick['last_words']}\" " + "after its first words") + continue + last = found[1] + start, end = lines[first].start, lines[last].end + if not MIN_SECONDS <= end - start <= MAX_SECONDS: + problems.append(f"{where}: lasts {end - start:.1f} seconds, " + f"not {MIN_SECONDS} to {MAX_SECONDS}") + continue + if not 0 <= start < end <= duration: + problems.append(f"{where}: runs past the end of the recording") + continue + overlap = next((m for m in moments if start < m["end"] and m["start"] < end), None) + if overlap: + problems.append(f"{where}: overlaps \"{overlap['title']}\"") + continue + moments.append({"start": start, "end": end, "title": pick["title"].strip()}) + return moments[:CLIP_COUNT], problems + + +def pick_moments(lines, duration): + """Ask Claude for moments, and ask once more if too few of them pass the checks.""" + client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY + messages = [{"role": "user", "content": transcript_text(lines)}] + picks = ask_claude(client, messages) + moments, problems = check_picks(picks, lines, duration) + if len(moments) < CLIP_COUNT: + print("Asking Claude to fix these:" + "".join(f"\n - {p}" for p in problems)) + messages += [ + {"role": "assistant", "content": json.dumps({"moments": picks})}, + {"role": "user", "content": "Some of those moments break the rules:\n" + + "\n".join(f"- {p}" for p in problems) + + f"\nSend the full list of {CLIP_COUNT} moments again, with these fixed."}, + ] + picks = ask_claude(client, messages) + moments, problems = check_picks(picks, lines, duration) + return moments, problems + + +def get_moments(lines, manifest, folder, repick): + """Reuse moments.json while nothing that shapes the pick has changed; otherwise pick again. + + moments.json is the contract between the picker and the renders: a list of + {"start", "end", "title"} with times in seconds. Edit it by hand, or write it + with a different picker, and the renders use it as it is.""" + path = folder / "moments.json" + picked_with = hashlib.sha256(json.dumps( + [transcript_text(lines), MODEL, MAX_TOKENS, THINKING, PROMPT, MOMENTS_SCHEMA] + ).encode()).hexdigest()[:16] + if path.exists() and not repick and manifest.get("picked_with") in (None, picked_with): + print(f"Using the moments in {path}") + moments = json.loads(path.read_text()) + for moment in moments: + if not 0 <= moment["start"] < moment["end"] <= manifest["duration"]: + fail(f"{path} has a moment that doesn't fit the recording: {moment}") + return moments + + if not os.environ.get("ANTHROPIC_API_KEY"): + fail("set ANTHROPIC_API_KEY so Claude can pick the moments.") + print(f"Asking {MODEL} for {CLIP_COUNT} moments from {len(lines)} sentences") + moments, problems = pick_moments(lines, manifest["duration"]) + for problem in problems: + print(f" left out: {problem}") + path.write_text(json.dumps(moments, indent=2)) + manifest["picked_with"] = picked_with + manifest.save() + for n, moment in enumerate(moments, 1): + print(f" {n}. {moment['title']} ({clock(moment['start'])} to {clock(moment['end'])})") + if not moments: + fail(f"none of the moments passed the checks. Change the prompt, or write {path} by hand.") + if len(moments) < CLIP_COUNT: + print(f"Only {len(moments)} moments passed the checks. Run with --repick to try " + f"again, or edit {path} by hand.") + return moments + + +# ---------------------------------------------------------------- step 3: render one clip + +def cut_edit(source_url, moment): + """Render 1: cut the moment out of the recording and fit it into a vertical frame.""" + return { + "timeline": { + "background": "#000000", + "tracks": [ + {"clips": [{ + "asset": {"type": "video", "src": source_url, "trim": moment["start"]}, + "start": 0, + "length": round(moment["end"] - moment["start"], 3), + "fit": "contain", + }]}, + ], + }, + "output": {"format": "mp4", "size": {"width": 1080, "height": 1920}}, + } + + +# Roboto, loaded so the bold weights below apply. A loaded font can be referred +# to by its name or by its file name, and this uses the file name. Copy font URLs +# verbatim from Google Fonts: the version and file name change over time. +ROBOTO_URL = "https://fonts.gstatic.com/s/roboto/v50/KFOmCnqEu92Fr1Me5WZLCzYlKw.ttf" +ROBOTO = "KFOmCnqEu92Fr1Me5WZLCzYlKw" + + +def caption_edit(cut_url, title): + """Render 2: add a title and captions generated from the cut's own audio. + + The title sits in the black band above the video. The captions come from the + clip named "clip" through an alias. They sit in the band under the video, with + the word being spoken in yellow.""" + return { + "timeline": { + "background": "#000000", + "fonts": [{"src": ROBOTO_URL}], + "tracks": [ + {"clips": [{ + "asset": { + "type": "rich-text", + "text": title, + "font": {"family": ROBOTO, "size": 76, "weight": 800, "color": "#ffffff"}, + "align": {"horizontal": "center", "vertical": "middle"}, + }, + "start": 0, + "length": "end", + "position": "top", + "offset": {"y": -0.12}, + "width": 960, + "height": 360, + }]}, + {"clips": [{ + "asset": { + "type": "rich-caption", + "src": "alias://clip", + "font": {"family": ROBOTO, "size": 64, "weight": 700, "color": "#ffffff"}, + "active": {"font": {"color": "#ffd84d"}}, + }, + "start": 0, + "length": "end", + "position": "bottom", + "offset": {"y": 0.08}, + "width": 960, + "height": 400, + }]}, + {"clips": [{ + "alias": "clip", + "asset": {"type": "video", "src": cut_url}, + "start": 0, + "length": "auto", + }]}, + ], + }, + "output": {"format": "mp4", "size": {"width": 1080, "height": 1920}}, + } + + +def submit(edit, label): + """Queue one render and return a record to track it by.""" + render_id = post_json(f"{EDIT}/render", edit)["response"]["id"] + print(f" {label}: queued ({render_id})") + return {"id": render_id, "status": "queued", "submitted": time.time()} + + +def finished(render, label): + """Check a render that isn't finished yet. True once it's done.""" + if render["status"] not in ("done", "failed"): + info = get_json(f"{EDIT}/render/{render['id']}")["response"] + if info["status"] != render["status"]: + print(f" {label}: {info['status']} after {clock(time.time() - render['submitted'])}") + render["status"] = info["status"] + if info["status"] == "done": + render["url"] = info["url"] + elif info["status"] == "failed": + render["error"] = info.get("error") or "no reason given" + return render["status"] == "done" + + +def advance(job, moment, source_url, path, label): + """Take one clip a step further: cut and reframe, then captions, then download.""" + if "cut" not in job: + job["cut"] = submit(cut_edit(source_url, moment), f"{label} cut") + return + if not finished(job["cut"], f"{label} cut"): + return + if "captions" not in job: + # Render URLs expire after 24 hours, so caption each cut as soon as it's ready. + job["captions"] = submit(caption_edit(job["cut"]["url"], moment["title"]), f"{label} captions") + return + if not finished(job["captions"], f"{label} captions"): + return + download(job["captions"]["url"], path) # this URL expires after 24 hours too + job["file"] = str(path) + print(f" {label}: saved {path}") + + +# ---------------------------------------------------------------- step 4: render all the clips + +def clip_state(job): + if "file" in job: + return "done" + if "unresolved" in job: + return "unresolved" + if "error" in job or "failed" in (job.get("cut", {}).get("status"), + job.get("captions", {}).get("status")): + return "failed" + return "working" + + +def render_clips(moments, manifest, folder): + """Submit every clip's renders and poll until each clip is done or has failed. + + Each clip is two render requests, tracked by ID.""" + jobs = manifest.setdefault("renders", {}) + todo = [] + for n, moment in enumerate(moments, 1): + job = jobs.setdefault(f"{moment['start']:.3f}-{moment['end']:.3f}", {}) + if clip_state(job) == "failed": # a new run tries failed clips again + job.pop("error", None) + if job.get("cut", {}).get("status") == "failed": + job.pop("cut") + job.pop("captions", None) + if job.get("captions", {}).get("status") == "failed": + job.pop("captions") + minutes, seconds = divmod(int(moment["start"]), 60) + todo.append((n, moment, job, folder / f"clip-{minutes:02d}m{seconds:02d}s.mp4")) + manifest.save() + + print(f"Rendering {len(todo)} clip{'' if len(todo) == 1 else 's'}") + started = time.time() + while True: + for n, moment, job, path in todo: + if clip_state(job) != "working": + continue + try: + advance(job, moment, manifest["source_url"], path, f"clip {n}") + except Unresolved as error: + # Don't resubmit: the render may have started, and a retry could duplicate it. + job["unresolved"] = f"the submit request didn't complete ({error})" + except (ApiError, requests.RequestException) as error: + job["error"] = str(error) + manifest.save() + if all(clip_state(job) != "working" for _, _, job, _ in todo): + return todo + if time.time() - started > RENDER_TIMEOUT: + fail("renders are still going after an hour. Run the same command again to keep " + "waiting; nothing that's already been submitted will be submitted again.") + time.sleep(POLL_SECONDS) + + +def report(todo): + print("\nClips:") + for n, moment, job, path in todo: + where = f"{clock(moment['start'])} to {clock(moment['end'])}" + if clip_state(job) == "done": + print(f" {n}. {moment['title']} ({where}): {path}") + elif clip_state(job) == "unresolved": + print(f" {n}. {moment['title']} ({where}): not sure a render started, because " + f"{job['unresolved']}. Check your Shotstack dashboard. If nothing started, " + f"delete this clip's entry under \"renders\" in manifest.json and run again.") + else: + reasons = [job.get("error")] + [job.get(stage, {}).get("error") for stage in ("cut", "captions")] + reason = "; ".join(r for r in reasons if r) + print(f" {n}. {moment['title']} ({where}): failed ({reason}). " + "Run the same command again to retry it.") + + +def main(): + parser = argparse.ArgumentParser(description="Turn a long recording into short, captioned, vertical clips.") + parser.add_argument("url", help="a URL that returns the recording file itself") + parser.add_argument("--limit", type=int, default=CLIP_COUNT, metavar="N", + help="render only the first N moments this run") + parser.add_argument("--repick", action="store_true", + help="ask Claude for new moments even if moments.json is up to date") + args = parser.parse_args() + + if args.limit < 1: + fail("--limit must be at least 1.") + if SHOTSTACK_ENV not in ("v1", "stage"): + fail('SHOTSTACK_ENV must be "v1" (production) or "stage" (sandbox).') + if not HEADERS["x-api-key"]: + fail("set SHOTSTACK_API_KEY first.") + + name = re.sub(r"[^A-Za-z0-9_-]+", "-", Path(urlparse(args.url).path).stem)[:40].strip("-") + folder = Path("clips") / f"{name or 'recording'}{'' if SHOTSTACK_ENV == 'v1' else '-sandbox'}" + folder.mkdir(parents=True, exist_ok=True) + manifest = Manifest(folder / "manifest.json", args.url) + + try: + if "source_url" not in manifest: + import_recording(args.url, manifest, folder) + lines = sentences(parse_srt((folder / "transcript.srt").read_text(encoding="utf-8"))) + moments = get_moments(lines, manifest, folder, args.repick) + todo = render_clips(moments[: args.limit], manifest, folder) + except Unresolved as error: + fail(f"a request didn't complete ({error}). It may still have reached Shotstack, " + "so check your dashboard before running this again.") + except ApiError as error: + fail(str(error)) + except anthropic.APIError as error: + fail(f"the Claude API returned an error: {error}") + report(todo) + + +if __name__ == "__main__": + main() From bf5829d648a0f8200f7b2be2ebf3f0c490058de9 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 06:11:36 +0500 Subject: [PATCH 02/12] Make the video clipping example follow the cookbook standards --- README.md | 1 + examples/video-clipping-pipeline/.env.example | 8 + examples/video-clipping-pipeline/.gitignore | 4 + examples/video-clipping-pipeline/README.md | 80 +++ examples/video-clipping-pipeline/clips.py | 500 +++++++++++++----- .../video-clipping-pipeline/requirements.txt | 2 + .../video-clipping-pipeline/test_clips.py | 166 ++++++ 7 files changed, 627 insertions(+), 134 deletions(-) create mode 100644 examples/video-clipping-pipeline/.env.example create mode 100644 examples/video-clipping-pipeline/.gitignore create mode 100644 examples/video-clipping-pipeline/README.md create mode 100644 examples/video-clipping-pipeline/requirements.txt create mode 100644 examples/video-clipping-pipeline/test_clips.py diff --git a/README.md b/README.md index 2680156..d33db05 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Clone this repository, or open the directory of the example you want. Each examp - [rime-multilingual-dub](examples/rime-multilingual-dub) dubs one video into several languages with Rime voice-overs, replacing the original audio and burning in captions, one render per language. - [scheduled-video-automation](examples/scheduled-video-automation) renders one product video per new feed item on a cron schedule. A history file makes repeated runs skip known items, and completion callbacks can replace polling. Companion code for [How to automate video creation on a schedule with the Shotstack API](https://shotstack.io/learn/automate-video-creation-on-a-schedule/). - [sports-highlight-videos](examples/sports-highlight-videos) trims a 10 second clip at each goal of a full match recording and joins them in one vertical render, cropped from the landscape footage. Extends [Automate sports video highlights using an API](https://shotstack.io/learn/automated-sports-highlight-video-api/). +- [video-clipping-pipeline](examples/video-clipping-pipeline) turns a long recording into short vertical clips with captions. Shotstack makes the transcript, Claude picks the moments, and each clip is cut and captioned in two renders. Companion code for [Build a video clipping pipeline with the Shotstack API](https://shotstack.io/learn/video-clipping-api-pipeline/). ## Contributing diff --git a/examples/video-clipping-pipeline/.env.example b/examples/video-clipping-pipeline/.env.example new file mode 100644 index 0000000..6e03112 --- /dev/null +++ b/examples/video-clipping-pipeline/.env.example @@ -0,0 +1,8 @@ +# Your Shotstack API key: https://dashboard.shotstack.io +SHOTSTACK_API_KEY= + +# Your Anthropic API key, for picking the moments: https://platform.claude.com/settings/keys +ANTHROPIC_API_KEY= + +# Optional. Set to stage for free watermarked test renders. Then use your sandbox key. +SHOTSTACK_ENV= diff --git a/examples/video-clipping-pipeline/.gitignore b/examples/video-clipping-pipeline/.gitignore new file mode 100644 index 0000000..19033fd --- /dev/null +++ b/examples/video-clipping-pipeline/.gitignore @@ -0,0 +1,4 @@ +.env +.venv/ +clips/ +__pycache__/ diff --git a/examples/video-clipping-pipeline/README.md b/examples/video-clipping-pipeline/README.md new file mode 100644 index 0000000..75d4067 --- /dev/null +++ b/examples/video-clipping-pipeline/README.md @@ -0,0 +1,80 @@ +# Video clipping pipeline + +Turn a long recording into five short vertical clips with captions. Shotstack +imports the recording and makes a transcript. Claude picks the best moments. +Shotstack cuts each moment and adds a title and captions. You get the MP4 +files in `clips//`. + +Related guide: [Build a video clipping pipeline with the Shotstack API](https://shotstack.io/learn/video-clipping-api-pipeline/). + +## Requirements + +- A [Shotstack account](https://dashboard.shotstack.io/register) and your + **production** API key +- An [Anthropic API key](https://platform.claude.com/settings/keys). Claude + picks the moments. +- Python 3.9 or later +- A public URL that gives the video file, not a web page + +Each clip uses two renders. Production renders use credits. Rates are on the +[pricing page](https://shotstack.io/pricing/). Set `SHOTSTACK_ENV=stage` in +`.env` and use your sandbox key for free watermarked test renders. + +## Setup + +```bash +git clone https://github.com/shotstack/shotstack-cookbook.git +cd shotstack-cookbook/examples/video-clipping-pipeline +python3 -m venv .venv +source .venv/bin/activate +python -m pip install -r requirements.txt +cp .env.example .env +``` + +Set `SHOTSTACK_API_KEY` and `ANTHROPIC_API_KEY` in `.env`. Then load the file. +Do this in each new terminal, and each time you change `.env`: + +```bash +set -a +source .env +set +a +``` + +## Run + +Render the first clip only, to examine the result: + +```bash +python clips.py "https://ftp.fau.de/fosdem/2025/k1105/fosdem-2025-5235-beyond-the-readme-crafting-a-better-developer-experience-for-open-source-projects.mp4" --limit 1 +``` + +Then run the same command without `--limit 1` to render all the clips. To use +your own recording, replace the URL. + +## What happens + +The script imports the recording with the Ingest API and waits for the +transcript. Then it sends the transcript to Claude, one sentence on each line. +Claude gives the first and last words of five moments. The script finds these +words in the transcript. It makes sure that each moment is 15 to 60 seconds +long and does not overlap another moment. It asks Claude one more time to fix +the moments that fail. It saves the moments in `moments.json`. + +Each clip uses two renders. The first render cuts the moment and puts it in a +1080x1920 frame. The second render adds the title and captions from the audio +of the cut. The script downloads each clip to `clip-MMmSSs.mp4`, named by its +start time in the recording. + +The script saves its progress in `manifest.json`. Run the same command again +to continue after a stop. It does not import the recording or pick the +moments again. To pick new moments, add `--repick`. To choose the moments +yourself, edit `moments.json`. + +If a render request does not complete, the render can start anyway. The +script does not send that request again. It tells you to look in your +Shotstack dashboard. If no render started, delete the entry for that clip +under `"renders"` in `manifest.json`. Then run the command again. + +The demo recording is "Beyond the README: Crafting a Better Developer +Experience for Open Source Projects" by Lorna Mitchell, FOSDEM 2025, licensed +CC BY 2.0 BE. diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py index 318d245..58a5d9b 100644 --- a/examples/video-clipping-pipeline/clips.py +++ b/examples/video-clipping-pipeline/clips.py @@ -18,6 +18,7 @@ ANTHROPIC_API_KEY your Anthropic API key (only needed to pick moments) SHOTSTACK_ENV "v1" for production (the default) or "stage" for the sandbox """ + import argparse import hashlib import json @@ -29,20 +30,22 @@ from pathlib import Path from urllib.parse import urlparse -import anthropic import requests -SHOTSTACK_ENV = os.environ.get("SHOTSTACK_ENV", "v1") +SHOTSTACK_ENV = os.environ.get("SHOTSTACK_ENV") or "v1" INGEST = f"https://api.shotstack.io/ingest/{SHOTSTACK_ENV}" EDIT = f"https://api.shotstack.io/edit/{SHOTSTACK_ENV}" -HEADERS = {"x-api-key": os.environ.get("SHOTSTACK_API_KEY", ""), "Accept": "application/json"} +HEADERS = { + "x-api-key": os.environ.get("SHOTSTACK_API_KEY", ""), + "Accept": "application/json", +} CLIP_COUNT = 5 MIN_SECONDS, MAX_SECONDS = 15, 60 POLL_SECONDS = 10 -IMPORT_TIMEOUT = 60 * 60 # stop waiting for the import and transcript after an hour -RENDER_TIMEOUT = 60 * 60 # and for the renders +IMPORT_TIMEOUT = 60 * 60 # stop waiting for the import and transcript after an hour +RENDER_TIMEOUT = 60 * 60 # and for the renders def fail(message): @@ -59,20 +62,30 @@ class Manifest(dict): """What's been done for one recording, saved to manifest.json after every change.""" def __init__(self, path, url): - super().__init__(json.loads(path.read_text()) if path.exists() else {"url": url}) + try: + saved = json.loads(path.read_text()) if path.exists() else {"url": url} + except ValueError: + saved = None + if not isinstance(saved, dict) or not isinstance(saved.get("url"), str): + fail(f"{path} is not a valid manifest. Fix it, or delete it to start over.") + super().__init__(saved) self.path = path if self["url"] != url: - if set(self) == {"url"}: # nothing was done for the old URL, like after a failed import + # nothing was done for the old URL, like after a failed import + if set(self) == {"url"}: self["url"] = url else: - fail(f"{path.parent} belongs to a different recording: {self['url']}. " - "Delete or rename that folder to start over with this URL.") + fail( + f"{path.parent} belongs to a different recording: {self['url']}. " + "Delete or rename that folder to start over with this URL." + ) def save(self): self.path.write_text(json.dumps(self, indent=2)) -# ---------------------------------------------------------------- Shotstack requests +# ---------------------------------------- Shotstack requests + class ApiError(Exception): """Shotstack answered with an error.""" @@ -82,14 +95,41 @@ class Unresolved(Exception): """A submit request that may or may not have reached Shotstack.""" +def error_detail(body): + """The reason in an error body: Ingest sends errors[0].detail, Edit sends + response.error or message.""" + if not isinstance(body, dict): + return "" + errors = body.get("errors") + first = errors[0] if isinstance(errors, list) and errors else None + response = body.get("response") + for value in ( + first.get("detail") if isinstance(first, dict) else None, + response.get("error") if isinstance(response, dict) else None, + body.get("message"), + ): + if isinstance(value, str) and value: + return value + return "" + + def check(response): + try: + body = response.json() + except ValueError: + body = None if response.status_code in (401, 403): kind = "production" if SHOTSTACK_ENV == "v1" else "sandbox" - fail(f"Shotstack refused the API key ({response.status_code}). " - f"SHOTSTACK_API_KEY must be your {kind} key.") + fail( + f"Shotstack refused the API key ({response.status_code} " + f"{error_detail(body)}). SHOTSTACK_API_KEY must be your {kind} key." + ) if response.status_code >= 400: - raise ApiError(f"{response.status_code} from {response.url}: {response.text[:300]}") - return response.json() + reason = error_detail(body) or response.reason + raise ApiError(f"{response.status_code} from {response.url}: {reason}") + if not isinstance(body, dict): + raise ApiError(f"{response.url} did not send a JSON object") + return body def post_json(url, body): @@ -97,7 +137,10 @@ def post_json(url, body): try: response = requests.post(url, headers=HEADERS, json=body, timeout=60) except requests.RequestException as error: - raise Unresolved(str(error)) from error + raise Unresolved(f"{type(error).__name__}") from error + # A server error can come after the job was created, so it isn't sent again either. + if response.status_code >= 500: + raise Unresolved(f"HTTP {response.status_code}") return check(response) @@ -123,47 +166,67 @@ def download(url, path): file.write(chunk) -# ---------------------------------------------------------------- step 1: import and transcribe +# ---------------------------------------- step 1: import and transcribe + def import_recording(url, manifest, folder): """Import the recording with the Ingest API and wait for its SRT transcript.""" if "source_id" not in manifest: body = {"url": url, "outputs": {"transcription": {"format": "srt"}}} - manifest["source_id"] = post_json(f"{INGEST}/sources", body)["data"]["id"] + data = post_json(f"{INGEST}/sources", body).get("data") + if not isinstance(data, dict) or not data.get("id"): + raise Unresolved("the reply had no source ID") + manifest["source_id"] = data["id"] manifest.save() print(f"Importing the recording (source {manifest['source_id']})") started, seen = time.time(), None while True: - source = get_json(f"{INGEST}/sources/{manifest['source_id']}")["data"]["attributes"] + source = get_json(f"{INGEST}/sources/{manifest['source_id']}")["data"][ + "attributes" + ] transcript = (source.get("outputs") or {}).get("transcription") or {} status = (source.get("status"), transcript.get("status")) if status != seen: - print(f" {clock(time.time() - started)} file: {status[0]}, transcript: {status[1] or 'waiting'}") + print( + f" {clock(time.time() - started)} file: {status[0]}, " + f"transcript: {status[1] or 'waiting'}" + ) seen = status if "failed" in status: del manifest["source_id"] # so the next run starts a new import manifest.save() reason = source.get("error") or "no reason given" if not source.get("duration"): - reason += ". Shotstack didn't get a video from that URL: it must return the file itself" + reason += ( + ". Shotstack didn't get a video from that URL: " + "it must return the file itself" + ) fail(f"the import failed ({reason}).") if status == ("ready", "ready"): break if time.time() - started > IMPORT_TIMEOUT: - fail("the import is taking over an hour. Run the same command again to keep waiting.") + fail( + f"the import is taking over {IMPORT_TIMEOUT // 60} minutes. " + "Run the same command again to keep waiting." + ) time.sleep(POLL_SECONDS) # Every render below needs the recording's length, so check it's there first. if not source.get("duration"): - fail("the import has no duration, so the URL may not point to a video. " - "Check that the URL returns the file itself.") + fail( + "the import has no duration, so the URL may not point to a video. " + "Check that the URL returns the file itself." + ) srt = requests.get(transcript["url"], timeout=60) srt.raise_for_status() - (folder / "transcript.srt").write_text(srt.content.decode("utf-8"), encoding="utf-8") + (folder / "transcript.srt").write_text( + srt.content.decode("utf-8"), encoding="utf-8" + ) manifest.update(source_url=source["source"], duration=source["duration"]) manifest.save() - print(f"Imported {clock(source['duration'])} of video and saved {folder / 'transcript.srt'}") + saved = folder / "transcript.srt" + print(f"Imported {clock(source['duration'])} of video and saved {saved}") Cue = namedtuple("Cue", "start end text") @@ -171,6 +234,7 @@ def import_recording(url, manifest, folder): def parse_srt(text): """Read an SRT file into a list of cues, with times in seconds.""" + def seconds(timestamp): hours, minutes, secs = timestamp.strip().replace(",", ".").split(":") return int(hours) * 3600 + int(minutes) * 60 + float(secs) @@ -181,12 +245,18 @@ def seconds(timestamp): for i, line in enumerate(lines): if "-->" in line: start, end = line.split("-->") - cues.append(Cue(seconds(start), seconds(end.split()[0]), " ".join(lines[i + 1:]))) + cues.append( + Cue( + seconds(start), + seconds(end.split()[0]), + " ".join(lines[i + 1 :]), + ) + ) break return cues -# ---------------------------------------------------------------- step 2: pick the moments +# ---------------------------------------- step 2: pick the moments MODEL = "claude-sonnet-5-5" MAX_TOKENS = 1000 @@ -253,13 +323,16 @@ def sentences(cues): def transcript_text(lines): """The transcript for the prompt: one sentence per line, with its start time.""" - return "\n".join(f"[{int(line.start // 60)}:{int(line.start % 60):02d}] {line.text}" - for line in lines) + return "\n".join( + f"[{int(line.start // 60)}:{int(line.start % 60):02d}] {line.text}" + for line in lines + ) def words(text): - """Lowercase words without punctuation, so a quote matches however it's punctuated.""" - return re.findall(r"[a-z0-9]+", text.lower().replace("'", "").replace("\u2019", "")) + """Lowercase words without punctuation, so a quote matches however it's + punctuated.""" + return re.findall(r"[a-z0-9]+", text.lower().replace("'", "").replace("’", "")) def locate(quote, lines, after=0): @@ -268,13 +341,18 @@ def locate(quote, lines, after=0): target = words(quote) stream = [(word, i) for i, line in enumerate(lines) for word in words(line.text)] for k in range(len(stream) - len(target) + 1): - if target and stream[k][1] >= after and [w for w, _ in stream[k:k + len(target)]] == target: + if ( + target + and stream[k][1] >= after + and [w for w, _ in stream[k : k + len(target)]] == target + ): return stream[k][1], stream[k + len(target) - 1][1] return None def ask_claude(client, messages): - """One request to Claude. Structured outputs make the reply JSON that matches the schema.""" + """One request to Claude. Structured outputs make the reply JSON that matches + the schema.""" response = client.messages.create( model=MODEL, max_tokens=MAX_TOKENS, @@ -284,7 +362,10 @@ def ask_claude(client, messages): output_config={"format": {"type": "json_schema", "schema": MOMENTS_SCHEMA}}, ) if response.stop_reason != "end_turn": - fail(f"Claude stopped early ({response.stop_reason}), so its reply isn't complete.") + fail( + f"Claude stopped early ({response.stop_reason}), " + "so its reply isn't complete." + ) text = next(block.text for block in response.content if block.type == "text") return json.loads(text)["moments"] @@ -297,37 +378,44 @@ def check_picks(picks, lines, duration): if len(picks) < CLIP_COUNT: problems.append(f"there are {len(picks)} moments, not {CLIP_COUNT}") for n, pick in enumerate(picks, 1): - where = f"moment {n} (\"{pick['title']}\")" + where = f'moment {n} ("{pick["title"]}")' found = locate(pick["first_words"], lines) if not found: - problems.append(f"{where}: the transcript doesn't contain \"{pick['first_words']}\"") + problems.append( + f'{where}: the transcript doesn\'t contain "{pick["first_words"]}"' + ) continue first = found[0] found = locate(pick["last_words"], lines, after=first) if not found: - problems.append(f"{where}: the transcript doesn't contain \"{pick['last_words']}\" " - "after its first words") + problems.append( + f'{where}: the transcript doesn\'t contain "{pick["last_words"]}" ' + "after its first words" + ) continue last = found[1] start, end = lines[first].start, lines[last].end if not MIN_SECONDS <= end - start <= MAX_SECONDS: - problems.append(f"{where}: lasts {end - start:.1f} seconds, " - f"not {MIN_SECONDS} to {MAX_SECONDS}") + problems.append( + f"{where}: lasts {end - start:.1f} seconds, " + f"not {MIN_SECONDS} to {MAX_SECONDS}" + ) continue if not 0 <= start < end <= duration: problems.append(f"{where}: runs past the end of the recording") continue - overlap = next((m for m in moments if start < m["end"] and m["start"] < end), None) + overlap = next( + (m for m in moments if start < m["end"] and m["start"] < end), None + ) if overlap: - problems.append(f"{where}: overlaps \"{overlap['title']}\"") + problems.append(f'{where}: overlaps "{overlap["title"]}"') continue moments.append({"start": start, "end": end, "title": pick["title"].strip()}) return moments[:CLIP_COUNT], problems -def pick_moments(lines, duration): +def pick_moments(client, lines, duration): """Ask Claude for moments, and ask once more if too few of them pass the checks.""" - client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY messages = [{"role": "user", "content": transcript_text(lines)}] picks = ask_claude(client, messages) moments, problems = check_picks(picks, lines, duration) @@ -335,66 +423,131 @@ def pick_moments(lines, duration): print("Asking Claude to fix these:" + "".join(f"\n - {p}" for p in problems)) messages += [ {"role": "assistant", "content": json.dumps({"moments": picks})}, - {"role": "user", "content": "Some of those moments break the rules:\n" + { + "role": "user", + "content": "Some of those moments break the rules:\n" + "\n".join(f"- {p}" for p in problems) - + f"\nSend the full list of {CLIP_COUNT} moments again, with these fixed."}, + + f"\nSend the full list of {CLIP_COUNT} moments again, " + "with these fixed.", + }, ] picks = ask_claude(client, messages) moments, problems = check_picks(picks, lines, duration) return moments, problems +def read_moments(path, duration): + """Read moments.json and check that every moment fits the recording.""" + try: + moments = json.loads(path.read_text()) + except ValueError: + moments = None + number = (int, float) + if not isinstance(moments, list) or not all( + isinstance(m, dict) + and isinstance(m.get("title"), str) + and isinstance(m.get("start"), number) + and isinstance(m.get("end"), number) + and 0 <= m["start"] < m["end"] <= duration + for m in moments + ): + fail( + f"{path} must be a list of moments, each with a title and a start and end " + "in seconds inside the recording. Fix it, or delete it to pick again." + ) + return moments + + def get_moments(lines, manifest, folder, repick): - """Reuse moments.json while nothing that shapes the pick has changed; otherwise pick again. + """Reuse moments.json while nothing that shapes the pick has changed; + otherwise pick again. moments.json is the contract between the picker and the renders: a list of {"start", "end", "title"} with times in seconds. Edit it by hand, or write it with a different picker, and the renders use it as it is.""" path = folder / "moments.json" - picked_with = hashlib.sha256(json.dumps( - [transcript_text(lines), MODEL, MAX_TOKENS, THINKING, PROMPT, MOMENTS_SCHEMA] - ).encode()).hexdigest()[:16] - if path.exists() and not repick and manifest.get("picked_with") in (None, picked_with): + picked_with = hashlib.sha256( + json.dumps( + [ + transcript_text(lines), + MODEL, + MAX_TOKENS, + THINKING, + PROMPT, + MOMENTS_SCHEMA, + ] + ).encode() + ).hexdigest()[:16] + if ( + path.exists() + and not repick + and manifest.get("picked_with") in (None, picked_with) + ): print(f"Using the moments in {path}") - moments = json.loads(path.read_text()) - for moment in moments: - if not 0 <= moment["start"] < moment["end"] <= manifest["duration"]: - fail(f"{path} has a moment that doesn't fit the recording: {moment}") - return moments + return read_moments(path, manifest["duration"]) if not os.environ.get("ANTHROPIC_API_KEY"): fail("set ANTHROPIC_API_KEY so Claude can pick the moments.") + try: + import anthropic # only this step needs it + except ImportError: + fail("install the anthropic package (pip install -r requirements.txt).") print(f"Asking {MODEL} for {CLIP_COUNT} moments from {len(lines)} sentences") - moments, problems = pick_moments(lines, manifest["duration"]) + try: + moments, problems = pick_moments( + anthropic.Anthropic(), lines, manifest["duration"] + ) + except anthropic.AuthenticationError: + fail("Anthropic refused the API key. Check ANTHROPIC_API_KEY.") + except anthropic.APIConnectionError: + fail("could not reach the Claude API. Check your network and run again.") + except anthropic.APIError as error: + fail(f"the Claude API returned an error: {error}") for problem in problems: print(f" left out: {problem}") path.write_text(json.dumps(moments, indent=2)) manifest["picked_with"] = picked_with manifest.save() for n, moment in enumerate(moments, 1): - print(f" {n}. {moment['title']} ({clock(moment['start'])} to {clock(moment['end'])})") + span = f"{clock(moment['start'])} to {clock(moment['end'])}" + print(f" {n}. {moment['title']} ({span})") if not moments: - fail(f"none of the moments passed the checks. Change the prompt, or write {path} by hand.") + fail( + "none of the moments passed the checks. " + f"Change the prompt, or write {path} by hand." + ) if len(moments) < CLIP_COUNT: - print(f"Only {len(moments)} moments passed the checks. Run with --repick to try " - f"again, or edit {path} by hand.") + print( + f"Only {len(moments)} moments passed the checks. Run with --repick to try " + f"again, or edit {path} by hand." + ) return moments -# ---------------------------------------------------------------- step 3: render one clip +# ---------------------------------------- step 3: render one clip + def cut_edit(source_url, moment): - """Render 1: cut the moment out of the recording and fit it into a vertical frame.""" + """Render 1: cut the moment out of the recording and fit it into a vertical + frame.""" return { "timeline": { "background": "#000000", "tracks": [ - {"clips": [{ - "asset": {"type": "video", "src": source_url, "trim": moment["start"]}, - "start": 0, - "length": round(moment["end"] - moment["start"], 3), - "fit": "contain", - }]}, + { + "clips": [ + { + "asset": { + "type": "video", + "src": source_url, + "trim": moment["start"], + }, + "start": 0, + "length": round(moment["end"] - moment["start"], 3), + "fit": "contain", + } + ] + }, ], }, "output": {"format": "mp4", "size": {"width": 1080, "height": 1920}}, @@ -419,40 +572,62 @@ def caption_edit(cut_url, title): "background": "#000000", "fonts": [{"src": ROBOTO_URL}], "tracks": [ - {"clips": [{ - "asset": { - "type": "rich-text", - "text": title, - "font": {"family": ROBOTO, "size": 76, "weight": 800, "color": "#ffffff"}, - "align": {"horizontal": "center", "vertical": "middle"}, - }, - "start": 0, - "length": "end", - "position": "top", - "offset": {"y": -0.12}, - "width": 960, - "height": 360, - }]}, - {"clips": [{ - "asset": { - "type": "rich-caption", - "src": "alias://clip", - "font": {"family": ROBOTO, "size": 64, "weight": 700, "color": "#ffffff"}, - "active": {"font": {"color": "#ffd84d"}}, - }, - "start": 0, - "length": "end", - "position": "bottom", - "offset": {"y": 0.08}, - "width": 960, - "height": 400, - }]}, - {"clips": [{ - "alias": "clip", - "asset": {"type": "video", "src": cut_url}, - "start": 0, - "length": "auto", - }]}, + { + "clips": [ + { + "asset": { + "type": "rich-text", + "text": title, + "font": { + "family": ROBOTO, + "size": 76, + "weight": 800, + "color": "#ffffff", + }, + "align": {"horizontal": "center", "vertical": "middle"}, + }, + "start": 0, + "length": "end", + "position": "top", + "offset": {"y": -0.12}, + "width": 960, + "height": 360, + } + ] + }, + { + "clips": [ + { + "asset": { + "type": "rich-caption", + "src": "alias://clip", + "font": { + "family": ROBOTO, + "size": 64, + "weight": 700, + "color": "#ffffff", + }, + "active": {"font": {"color": "#ffd84d"}}, + }, + "start": 0, + "length": "end", + "position": "bottom", + "offset": {"y": 0.08}, + "width": 960, + "height": 400, + } + ] + }, + { + "clips": [ + { + "alias": "clip", + "asset": {"type": "video", "src": cut_url}, + "start": 0, + "length": "auto", + } + ] + }, ], }, "output": {"format": "mp4", "size": {"width": 1080, "height": 1920}}, @@ -461,7 +636,10 @@ def caption_edit(cut_url, title): def submit(edit, label): """Queue one render and return a record to track it by.""" - render_id = post_json(f"{EDIT}/render", edit)["response"]["id"] + response = post_json(f"{EDIT}/render", edit).get("response") + render_id = response.get("id") if isinstance(response, dict) else None + if not render_id: + raise Unresolved("the reply had no render ID") print(f" {label}: queued ({render_id})") return {"id": render_id, "status": "queued", "submitted": time.time()} @@ -471,9 +649,13 @@ def finished(render, label): if render["status"] not in ("done", "failed"): info = get_json(f"{EDIT}/render/{render['id']}")["response"] if info["status"] != render["status"]: - print(f" {label}: {info['status']} after {clock(time.time() - render['submitted'])}") + took = clock(time.time() - render["submitted"]) + print(f" {label}: {info['status']} after {took}") render["status"] = info["status"] - if info["status"] == "done": + if info["status"] == "done" and not info.get("url"): + render["status"] = "failed" + render["error"] = "the render is done but has no URL" + elif info["status"] == "done": render["url"] = info["url"] elif info["status"] == "failed": render["error"] = info.get("error") or "no reason given" @@ -488,25 +670,43 @@ def advance(job, moment, source_url, path, label): if not finished(job["cut"], f"{label} cut"): return if "captions" not in job: - # Render URLs expire after 24 hours, so caption each cut as soon as it's ready. - job["captions"] = submit(caption_edit(job["cut"]["url"], moment["title"]), f"{label} captions") + # Render URLs can be deleted after 24 hours, so caption each cut as soon as + # it's ready. + job["captions"] = submit( + caption_edit(job["cut"]["url"], moment["title"]), f"{label} captions" + ) return if not finished(job["captions"], f"{label} captions"): return - download(job["captions"]["url"], path) # this URL expires after 24 hours too + try: + # This URL can be deleted after 24 hours too + download(job["captions"]["url"], path) + except requests.HTTPError as error: + status = getattr(error.response, "status_code", None) + if status in (403, 404, 410): + job["error"] = f"the rendered file is gone (HTTP {status})" + job["fix"] = ( + 'Delete this clip\'s entry under "renders" in manifest.json ' + "and run again to render it again." + ) + return + raise job["file"] = str(path) print(f" {label}: saved {path}") -# ---------------------------------------------------------------- step 4: render all the clips +# ---------------------------------------- step 4: render all the clips + def clip_state(job): if "file" in job: return "done" if "unresolved" in job: return "unresolved" - if "error" in job or "failed" in (job.get("cut", {}).get("status"), - job.get("captions", {}).get("status")): + if "error" in job or "failed" in ( + job.get("cut", {}).get("status"), + job.get("captions", {}).get("status"), + ): return "failed" return "working" @@ -521,6 +721,7 @@ def render_clips(moments, manifest, folder): job = jobs.setdefault(f"{moment['start']:.3f}-{moment['end']:.3f}", {}) if clip_state(job) == "failed": # a new run tries failed clips again job.pop("error", None) + job.pop("fix", None) if job.get("cut", {}).get("status") == "failed": job.pop("cut") job.pop("captions", None) @@ -539,7 +740,8 @@ def render_clips(moments, manifest, folder): try: advance(job, moment, manifest["source_url"], path, f"clip {n}") except Unresolved as error: - # Don't resubmit: the render may have started, and a retry could duplicate it. + # Don't resubmit: the render may have started, and a retry could + # duplicate it. job["unresolved"] = f"the submit request didn't complete ({error})" except (ApiError, requests.RequestException) as error: job["error"] = str(error) @@ -547,8 +749,11 @@ def render_clips(moments, manifest, folder): if all(clip_state(job) != "working" for _, _, job, _ in todo): return todo if time.time() - started > RENDER_TIMEOUT: - fail("renders are still going after an hour. Run the same command again to keep " - "waiting; nothing that's already been submitted will be submitted again.") + fail( + f"renders are still going after {RENDER_TIMEOUT // 60} minutes. " + "Run the same command again to keep waiting; nothing that's " + "already been submitted will be submitted again." + ) time.sleep(POLL_SECONDS) @@ -559,23 +764,38 @@ def report(todo): if clip_state(job) == "done": print(f" {n}. {moment['title']} ({where}): {path}") elif clip_state(job) == "unresolved": - print(f" {n}. {moment['title']} ({where}): not sure a render started, because " - f"{job['unresolved']}. Check your Shotstack dashboard. If nothing started, " - f"delete this clip's entry under \"renders\" in manifest.json and run again.") + print( + f" {n}. {moment['title']} ({where}): not sure a render started, " + f"because {job['unresolved']}. Check your Shotstack dashboard. " + "If nothing started, delete this clip's entry under " + '"renders" in manifest.json and run again.' + ) else: - reasons = [job.get("error")] + [job.get(stage, {}).get("error") for stage in ("cut", "captions")] + reasons = [job.get("error")] + [ + job.get(stage, {}).get("error") for stage in ("cut", "captions") + ] reason = "; ".join(r for r in reasons if r) - print(f" {n}. {moment['title']} ({where}): failed ({reason}). " - "Run the same command again to retry it.") + fix = job.get("fix", "Run the same command again to retry it.") + print(f" {n}. {moment['title']} ({where}): failed ({reason}). {fix}") def main(): - parser = argparse.ArgumentParser(description="Turn a long recording into short, captioned, vertical clips.") + parser = argparse.ArgumentParser( + description="Turn a long recording into short, captioned, vertical clips." + ) parser.add_argument("url", help="a URL that returns the recording file itself") - parser.add_argument("--limit", type=int, default=CLIP_COUNT, metavar="N", - help="render only the first N moments this run") - parser.add_argument("--repick", action="store_true", - help="ask Claude for new moments even if moments.json is up to date") + parser.add_argument( + "--limit", + type=int, + default=CLIP_COUNT, + metavar="N", + help="render only the first N moments this run", + ) + parser.add_argument( + "--repick", + action="store_true", + help="ask Claude for new moments even if moments.json is up to date", + ) args = parser.parse_args() if args.limit < 1: @@ -585,26 +805,38 @@ def main(): if not HEADERS["x-api-key"]: fail("set SHOTSTACK_API_KEY first.") - name = re.sub(r"[^A-Za-z0-9_-]+", "-", Path(urlparse(args.url).path).stem)[:40].strip("-") - folder = Path("clips") / f"{name or 'recording'}{'' if SHOTSTACK_ENV == 'v1' else '-sandbox'}" + name = re.sub(r"[^A-Za-z0-9_-]+", "-", Path(urlparse(args.url).path).stem)[ + :40 + ].strip("-") + folder = ( + Path("clips") + / f"{name or 'recording'}{'' if SHOTSTACK_ENV == 'v1' else '-sandbox'}" + ) folder.mkdir(parents=True, exist_ok=True) manifest = Manifest(folder / "manifest.json", args.url) try: if "source_url" not in manifest: import_recording(args.url, manifest, folder) - lines = sentences(parse_srt((folder / "transcript.srt").read_text(encoding="utf-8"))) + lines = sentences( + parse_srt((folder / "transcript.srt").read_text(encoding="utf-8")) + ) moments = get_moments(lines, manifest, folder, args.repick) todo = render_clips(moments[: args.limit], manifest, folder) except Unresolved as error: - fail(f"a request didn't complete ({error}). It may still have reached Shotstack, " - "so check your dashboard before running this again.") + fail( + f"a request didn't complete ({error}). It may still have reached " + "Shotstack, so check your dashboard before running this again." + ) except ApiError as error: fail(str(error)) - except anthropic.APIError as error: - fail(f"the Claude API returned an error: {error}") report(todo) if __name__ == "__main__": - main() + try: + main() + except KeyboardInterrupt: + fail("interrupted. Run the same command again to carry on.") + except Exception as error: # one line instead of a stack trace + fail(f"{type(error).__name__}: {error}") diff --git a/examples/video-clipping-pipeline/requirements.txt b/examples/video-clipping-pipeline/requirements.txt new file mode 100644 index 0000000..e7166f5 --- /dev/null +++ b/examples/video-clipping-pipeline/requirements.txt @@ -0,0 +1,2 @@ +anthropic>=0.77.0 +requests>=2.18 diff --git a/examples/video-clipping-pipeline/test_clips.py b/examples/video-clipping-pipeline/test_clips.py new file mode 100644 index 0000000..6da070f --- /dev/null +++ b/examples/video-clipping-pipeline/test_clips.py @@ -0,0 +1,166 @@ +"""Tests for the resume logic of clips.py. They do not call Shotstack or Claude. + +Run them from this directory: python3 -m unittest +""" + +import contextlib +import io +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import requests + +import clips + +RECORDING = "https://example.com/talk.mp4" +MOMENT = {"start": 61.0, "end": 91.0, "title": "A moment"} +URL = "https://cdn.shotstack.io/au/stage/owner/render.mp4" + + +def http_error(status_code): + response = requests.Response() + response.status_code = status_code + return requests.HTTPError(f"{status_code} for {URL}", response=response) + + +class FakeEdit: + """Stands in for the Edit API. Every render it accepts is done at once, + unless its ID is in `failed`.""" + + def __init__(self): + self.submits = [] + self.post_errors = [] + self.failed = set() + + def post_json(self, url, body): + if self.post_errors: + raise self.post_errors.pop(0) + self.submits.append(body) + return {"response": {"id": f"render-{len(self.submits)}"}} + + def get_json(self, url): + render_id = url.rsplit("/", 1)[-1] + if render_id in self.failed: + return {"response": {"status": "failed", "error": "test failure"}} + return {"response": {"status": "done", "url": URL}} + + +class Resume(unittest.TestCase): + """A run that stops part way must not pay for a render twice.""" + + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.folder = Path(temp.name) + manifest = clips.Manifest(self.folder / "manifest.json", RECORDING) + manifest.update(source_url=RECORDING, duration=3600) + manifest.save() + self.edit = FakeEdit() + self.downloads = [] + self.download_errors = [] + replacements = { + "post_json": self.edit.post_json, + "get_json": self.edit.get_json, + "download": self.download, + } + for name, value in replacements.items(): + patcher = mock.patch.object(clips, name, value) + patcher.start() + self.addCleanup(patcher.stop) + sleep = mock.patch.object(clips.time, "sleep") + sleep.start() + self.addCleanup(sleep.stop) + + def download(self, url, path): + if self.download_errors: + raise self.download_errors.pop(0) + self.downloads.append(url) + Path(path).write_bytes(b"video") + + def run_clips(self): + """One run of the render step, from the manifest on disk. Returns the job.""" + manifest = clips.Manifest(self.folder / "manifest.json", RECORDING) + with contextlib.redirect_stdout(io.StringIO()): + todo = clips.render_clips([MOMENT], manifest, self.folder) + return todo[0][2] + + def test_a_clip_takes_two_renders_and_one_download(self): + job = self.run_clips() + self.assertEqual(clips.clip_state(job), "done") + self.assertEqual(len(self.edit.submits), 2) + self.assertEqual(len(self.downloads), 1) + + def test_a_submit_that_did_not_complete_is_not_sent_again(self): + self.edit.post_errors = [clips.Unresolved("ReadTimeout")] + self.assertEqual(clips.clip_state(self.run_clips()), "unresolved") + self.assertEqual(clips.clip_state(self.run_clips()), "unresolved") + self.assertEqual(self.edit.submits, []) + + def test_a_refused_submit_is_sent_again_on_the_next_run(self): + self.edit.post_errors = [clips.ApiError("429 from the Edit API")] + self.assertEqual(clips.clip_state(self.run_clips()), "failed") + self.assertEqual(clips.clip_state(self.run_clips()), "done") + self.assertEqual(len(self.edit.submits), 2) + + def test_a_failed_download_does_not_render_again(self): + self.download_errors = [requests.ConnectionError("network down")] + self.assertEqual(clips.clip_state(self.run_clips()), "failed") + self.assertEqual(clips.clip_state(self.run_clips()), "done") + self.assertEqual(len(self.edit.submits), 2) + + def test_a_deleted_file_asks_for_the_entry_to_be_deleted(self): + self.download_errors = [http_error(404), http_error(404)] + job = self.run_clips() + self.assertEqual(clips.clip_state(job), "failed") + self.assertIn("manifest.json", job["fix"]) + job = self.run_clips() + self.assertIn("fix", job) + self.assertEqual(len(self.edit.submits), 2) + + def test_a_failed_captions_render_redoes_only_the_captions(self): + self.edit.failed = {"render-2"} + self.assertEqual(clips.clip_state(self.run_clips()), "failed") + self.edit.failed = set() + self.assertEqual(clips.clip_state(self.run_clips()), "done") + # The third render is the captions again (it loads the font), not a new cut + self.assertEqual(len(self.edit.submits), 3) + self.assertIn("fonts", self.edit.submits[2]["timeline"]) + + +class PostJson(unittest.TestCase): + """How a submit request is classified.""" + + def post(self, status_code, body=b"{}"): + response = requests.Response() + response.status_code = status_code + response._content = body + response.url = "https://api.shotstack.io/edit/stage/render" + with mock.patch.object(clips.requests, "post", return_value=response): + return clips.post_json(response.url, {}) + + def test_a_server_error_is_not_sent_again(self): + with self.assertRaises(clips.Unresolved): + self.post(502) + + def test_a_network_error_is_not_sent_again(self): + error = requests.ConnectionError("network down") + with mock.patch.object(clips.requests, "post", side_effect=error): + with self.assertRaises(clips.Unresolved): + clips.post_json("https://api.shotstack.io/edit/stage/render", {}) + + def test_a_refusal_names_the_reason(self): + body = b'{"message": "Bad Request", "response": {"error": "bad trim"}}' + with self.assertRaises(clips.ApiError) as raised: + self.post(400, body) + self.assertIn("bad trim", str(raised.exception)) + + def test_a_reply_with_no_render_id_is_not_sent_again(self): + with mock.patch.object(clips, "post_json", return_value={"response": {}}): + with self.assertRaises(clips.Unresolved): + clips.submit({}, "clip 1") + + +if __name__ == "__main__": + unittest.main() From 91c0a048eaff79c58c3bf784389422cdec2bdb68 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 06:18:56 +0500 Subject: [PATCH 03/12] Fix review findings in the video clipping example --- examples/video-clipping-pipeline/clips.py | 126 ++++++++++-------- .../video-clipping-pipeline/test_clips.py | 76 +++++++++-- 2 files changed, 140 insertions(+), 62 deletions(-) diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py index 58a5d9b..54404e5 100644 --- a/examples/video-clipping-pipeline/clips.py +++ b/examples/video-clipping-pipeline/clips.py @@ -46,6 +46,9 @@ POLL_SECONDS = 10 IMPORT_TIMEOUT = 60 * 60 # stop waiting for the import and transcript after an hour RENDER_TIMEOUT = 60 * 60 # and for the renders +# A render's URL can be deleted after 24 hours. A cut older than this is rendered +# again before its captions are. +CUT_MAX_AGE = 20 * 60 * 60 def fail(message): @@ -323,31 +326,25 @@ def sentences(cues): def transcript_text(lines): """The transcript for the prompt: one sentence per line, with its start time.""" - return "\n".join( - f"[{int(line.start // 60)}:{int(line.start % 60):02d}] {line.text}" - for line in lines - ) + return "\n".join(f"[{clock(line.start)}] {line.text}" for line in lines) def words(text): """Lowercase words without punctuation, so a quote matches however it's punctuated.""" - return re.findall(r"[a-z0-9]+", text.lower().replace("'", "").replace("’", "")) + return re.findall(r"[^\W_]+", text.lower().replace("'", "").replace("’", "")) -def locate(quote, lines, after=0): - """Find a quote in the transcript, from line `after` on. Returns the indexes of - the lines where it starts and ends, or None if it isn't there.""" - target = words(quote) - stream = [(word, i) for i, line in enumerate(lines) for word in words(line.text)] +def find(target, stream, after=0): + """Yield (first line, last line) for each place the words in `target` occur in + the transcript's (word, line) stream, from line `after` on.""" for k in range(len(stream) - len(target) + 1): if ( target and stream[k][1] >= after and [w for w, _ in stream[k : k + len(target)]] == target ): - return stream[k][1], stream[k + len(target) - 1][1] - return None + yield stream[k][1], stream[k + len(target) - 1][1] def ask_claude(client, messages): @@ -366,7 +363,9 @@ def ask_claude(client, messages): f"Claude stopped early ({response.stop_reason}), " "so its reply isn't complete." ) - text = next(block.text for block in response.content if block.type == "text") + text = next((b.text for b in response.content if b.type == "text"), None) + if text is None: + fail("Claude's reply has no text.") return json.loads(text)["moments"] @@ -374,27 +373,32 @@ def check_picks(picks, lines, duration): """Find each moment's quotes in the transcript, turn them into start and end times, and check the rules. Returns the moments that pass, best first, and a list of problems.""" + stream = [(word, i) for i, line in enumerate(lines) for word in words(line.text)] moments, problems = [], [] if len(picks) < CLIP_COUNT: problems.append(f"there are {len(picks)} moments, not {CLIP_COUNT}") for n, pick in enumerate(picks, 1): where = f'moment {n} ("{pick["title"]}")' - found = locate(pick["first_words"], lines) - if not found: + starts = [first for first, _ in find(words(pick["first_words"]), stream)] + if not starts: problems.append( f'{where}: the transcript doesn\'t contain "{pick["first_words"]}"' ) continue - first = found[0] - found = locate(pick["last_words"], lines, after=first) - if not found: + # The first words can occur more than once. Pair each place with the next + # place the last words occur, and keep the shortest span. + spans = [] + for first in starts: + found = next(find(words(pick["last_words"]), stream, after=first), None) + if found: + spans.append((lines[first].start, lines[found[1]].end)) + if not spans: problems.append( f'{where}: the transcript doesn\'t contain "{pick["last_words"]}" ' "after its first words" ) continue - last = found[1] - start, end = lines[first].start, lines[last].end + start, end = min(spans, key=lambda span: span[1] - span[0]) if not MIN_SECONDS <= end - start <= MAX_SECONDS: problems.append( f"{where}: lasts {end - start:.1f} seconds, " @@ -431,29 +435,40 @@ def pick_moments(client, lines, duration): "with these fixed.", }, ] - picks = ask_claude(client, messages) - moments, problems = check_picks(picks, lines, duration) + retried = check_picks(ask_claude(client, messages), lines, duration) + if len(retried[0]) > len(moments): # keep the first answer if it was better + moments, problems = retried return moments, problems def read_moments(path, duration): - """Read moments.json and check that every moment fits the recording.""" + """Read moments.json and check that the moments fit the recording and don't + overlap.""" try: moments = json.loads(path.read_text()) except ValueError: moments = None number = (int, float) - if not isinstance(moments, list) or not all( - isinstance(m, dict) - and isinstance(m.get("title"), str) - and isinstance(m.get("start"), number) - and isinstance(m.get("end"), number) - and 0 <= m["start"] < m["end"] <= duration - for m in moments - ): + valid = ( + isinstance(moments, list) + and len(moments) > 0 + and all( + isinstance(m, dict) + and isinstance(m.get("title"), str) + and isinstance(m.get("start"), number) + and isinstance(m.get("end"), number) + and 0 <= m["start"] < m["end"] <= duration + for m in moments + ) + ) + if valid: + spans = sorted((m["start"], m["end"]) for m in moments) + valid = all(a[1] <= b[0] for a, b in zip(spans, spans[1:])) + if not valid: fail( - f"{path} must be a list of moments, each with a title and a start and end " - "in seconds inside the recording. Fix it, or delete it to pick again." + f"{path} must be a list of moments that don't overlap, each with a title " + "and a start and end in seconds inside the recording. Fix it, or delete " + "it to pick again." ) return moments @@ -505,17 +520,17 @@ def get_moments(lines, manifest, folder, repick): fail(f"the Claude API returned an error: {error}") for problem in problems: print(f" left out: {problem}") + if not moments: + fail( + "none of the moments passed the checks. Run again to ask Claude again, " + f"or write {path} by hand." + ) path.write_text(json.dumps(moments, indent=2)) manifest["picked_with"] = picked_with manifest.save() for n, moment in enumerate(moments, 1): span = f"{clock(moment['start'])} to {clock(moment['end'])}" print(f" {n}. {moment['title']} ({span})") - if not moments: - fail( - "none of the moments passed the checks. " - f"Change the prompt, or write {path} by hand." - ) if len(moments) < CLIP_COUNT: print( f"Only {len(moments)} moments passed the checks. Run with --repick to try " @@ -554,9 +569,9 @@ def cut_edit(source_url, moment): } -# Roboto, loaded so the bold weights below apply. A loaded font can be referred -# to by its name or by its file name, and this uses the file name. Copy font URLs -# verbatim from Google Fonts: the version and file name change over time. +# Roboto, a variable font, loaded so the bold weights below apply. A loaded font +# can be referred to by its name or by its file name, and this uses the file name. +# Copy font URLs verbatim from Google Fonts: the version and file name change. ROBOTO_URL = "https://fonts.gstatic.com/s/roboto/v50/KFOmCnqEu92Fr1Me5WZLCzYlKw.ttf" ROBOTO = "KFOmCnqEu92Fr1Me5WZLCzYlKw" @@ -684,11 +699,8 @@ def advance(job, moment, source_url, path, label): except requests.HTTPError as error: status = getattr(error.response, "status_code", None) if status in (403, 404, 410): + del job["captions"] # so the next run renders the captions again job["error"] = f"the rendered file is gone (HTTP {status})" - job["fix"] = ( - 'Delete this clip\'s entry under "renders" in manifest.json ' - "and run again to render it again." - ) return raise job["file"] = str(path) @@ -721,12 +733,15 @@ def render_clips(moments, manifest, folder): job = jobs.setdefault(f"{moment['start']:.3f}-{moment['end']:.3f}", {}) if clip_state(job) == "failed": # a new run tries failed clips again job.pop("error", None) - job.pop("fix", None) - if job.get("cut", {}).get("status") == "failed": - job.pop("cut") + cut = job.get("cut", {}) + redo_captions = job.get("captions", {}).get("status") in (None, "failed") + # The captions render reads the cut's URL, so an old cut is made again + cut_is_old = time.time() - cut.get("submitted", 0) > CUT_MAX_AGE + if cut.get("status") == "failed" or (redo_captions and cut_is_old): + job.pop("cut", None) + job.pop("captions", None) + elif redo_captions: job.pop("captions", None) - if job.get("captions", {}).get("status") == "failed": - job.pop("captions") minutes, seconds = divmod(int(moment["start"]), 60) todo.append((n, moment, job, folder / f"clip-{minutes:02d}m{seconds:02d}s.mp4")) manifest.save() @@ -775,8 +790,10 @@ def report(todo): job.get(stage, {}).get("error") for stage in ("cut", "captions") ] reason = "; ".join(r for r in reasons if r) - fix = job.get("fix", "Run the same command again to retry it.") - print(f" {n}. {moment['title']} ({where}): failed ({reason}). {fix}") + print( + f" {n}. {moment['title']} ({where}): failed ({reason}). " + "Run the same command again to retry it." + ) def main(): @@ -825,8 +842,9 @@ def main(): todo = render_clips(moments[: args.limit], manifest, folder) except Unresolved as error: fail( - f"a request didn't complete ({error}). It may still have reached " - "Shotstack, so check your dashboard before running this again." + f"a request didn't complete ({error}). Check your network. The request " + "may still have reached Shotstack, so look in your dashboard before you " + "run this again." ) except ApiError as error: fail(str(error)) diff --git a/examples/video-clipping-pipeline/test_clips.py b/examples/video-clipping-pipeline/test_clips.py index 6da070f..065434b 100644 --- a/examples/video-clipping-pipeline/test_clips.py +++ b/examples/video-clipping-pipeline/test_clips.py @@ -5,6 +5,7 @@ import contextlib import io +import json import tempfile import unittest from pathlib import Path @@ -110,14 +111,24 @@ def test_a_failed_download_does_not_render_again(self): self.assertEqual(clips.clip_state(self.run_clips()), "done") self.assertEqual(len(self.edit.submits), 2) - def test_a_deleted_file_asks_for_the_entry_to_be_deleted(self): - self.download_errors = [http_error(404), http_error(404)] - job = self.run_clips() - self.assertEqual(clips.clip_state(job), "failed") - self.assertIn("manifest.json", job["fix"]) - job = self.run_clips() - self.assertIn("fix", job) - self.assertEqual(len(self.edit.submits), 2) + def test_a_deleted_file_renders_the_captions_again(self): + self.download_errors = [http_error(404)] + self.assertEqual(clips.clip_state(self.run_clips()), "failed") + self.assertEqual(clips.clip_state(self.run_clips()), "done") + # cut, captions, captions again: the cut is new enough to use again + self.assertEqual(len(self.edit.submits), 3) + self.assertIn("fonts", self.edit.submits[2]["timeline"]) + + def test_an_old_cut_is_rendered_again_before_its_captions(self): + self.download_errors = [http_error(404)] + self.run_clips() + manifest = clips.Manifest(self.folder / "manifest.json", RECORDING) + for job in manifest["renders"].values(): + job["cut"]["submitted"] -= clips.CUT_MAX_AGE + 1 + manifest.save() + self.assertEqual(clips.clip_state(self.run_clips()), "done") + self.assertEqual(len(self.edit.submits), 4) + self.assertNotIn("fonts", self.edit.submits[2]["timeline"]) def test_a_failed_captions_render_redoes_only_the_captions(self): self.edit.failed = {"render-2"} @@ -129,6 +140,55 @@ def test_a_failed_captions_render_redoes_only_the_captions(self): self.assertIn("fonts", self.edit.submits[2]["timeline"]) +class CheckPicks(unittest.TestCase): + """How Claude's quotes become start and end times.""" + + def test_a_repeated_phrase_uses_the_shortest_span(self): + lines = [ + clips.Cue(0, 10, "So the next thing is setup."), + clips.Cue(10, 300, "Then a long part."), + clips.Cue(300, 310, "So the next thing is testing."), + clips.Cue(310, 330, "And that is why tests matter."), + ] + pick = { + "first_words": "So the next thing is", + "last_words": "why tests matter", + "title": "Tests", + } + moments, _ = clips.check_picks([pick], lines, 400) + self.assertEqual(moments, [{"start": 300, "end": 330, "title": "Tests"}]) + + def test_accented_words_match(self): + lines = [clips.Cue(0, 20, "Über die Prüfung."), clips.Cue(20, 40, "Schön.")] + pick = {"first_words": "über die", "last_words": "schön", "title": "Prüfung"} + moments, _ = clips.check_picks([pick], lines, 100) + self.assertEqual(len(moments), 1) + + +class ReadMoments(unittest.TestCase): + """A moments.json written by hand.""" + + def read(self, moments): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "moments.json" + path.write_text(json.dumps(moments)) + with contextlib.redirect_stderr(io.StringIO()): + return clips.read_moments(path, 3600) + + def test_overlapping_moments_are_refused(self): + with self.assertRaises(SystemExit): + self.read( + [ + {"start": 10, "end": 40, "title": "a"}, + {"start": 30, "end": 60, "title": "b"}, + ] + ) + + def test_an_empty_list_is_refused(self): + with self.assertRaises(SystemExit): + self.read([]) + + class PostJson(unittest.TestCase): """How a submit request is classified.""" From cd1a8a96d8d8896cc5c85f69e3a151a71abf15f0 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 06:26:34 +0500 Subject: [PATCH 04/12] Add measured run times to the video clipping README --- examples/video-clipping-pipeline/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/video-clipping-pipeline/README.md b/examples/video-clipping-pipeline/README.md index 75d4067..3390849 100644 --- a/examples/video-clipping-pipeline/README.md +++ b/examples/video-clipping-pipeline/README.md @@ -65,6 +65,9 @@ Each clip uses two renders. The first render cuts the moment and puts it in a of the cut. The script downloads each clip to `clip-MMmSSs.mp4`, named by its start time in the recording. +With the demo recording, which is 52 minutes long, the import takes about 4 +minutes. Each clip takes 2 to 4 minutes, and the clips render at the same time. + The script saves its progress in `manifest.json`. Run the same command again to continue after a stop. It does not import the recording or pick the moments again. To pick new moments, add `--repick`. To choose the moments From d21711c5038533a100c62a393aa765d9cedc97a6 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 06:51:50 +0500 Subject: [PATCH 05/12] Caption clips from the transcript in one render, and pick moments with any AI provider --- README.md | 2 +- examples/video-clipping-pipeline/.env.example | 12 +- examples/video-clipping-pipeline/README.md | 46 ++- examples/video-clipping-pipeline/clips.py | 367 ++++++++++-------- .../video-clipping-pipeline/requirements.txt | 1 - .../video-clipping-pipeline/test_clips.py | 150 +++++-- 6 files changed, 353 insertions(+), 225 deletions(-) diff --git a/README.md b/README.md index d33db05..b2dd88e 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Clone this repository, or open the directory of the example you want. Each examp - [rime-multilingual-dub](examples/rime-multilingual-dub) dubs one video into several languages with Rime voice-overs, replacing the original audio and burning in captions, one render per language. - [scheduled-video-automation](examples/scheduled-video-automation) renders one product video per new feed item on a cron schedule. A history file makes repeated runs skip known items, and completion callbacks can replace polling. Companion code for [How to automate video creation on a schedule with the Shotstack API](https://shotstack.io/learn/automate-video-creation-on-a-schedule/). - [sports-highlight-videos](examples/sports-highlight-videos) trims a 10 second clip at each goal of a full match recording and joins them in one vertical render, cropped from the landscape footage. Extends [Automate sports video highlights using an API](https://shotstack.io/learn/automated-sports-highlight-video-api/). -- [video-clipping-pipeline](examples/video-clipping-pipeline) turns a long recording into short vertical clips with captions. Shotstack makes the transcript, Claude picks the moments, and each clip is cut and captioned in two renders. Companion code for [Build a video clipping pipeline with the Shotstack API](https://shotstack.io/learn/video-clipping-api-pipeline/). +- [video-clipping-pipeline](examples/video-clipping-pipeline) turns a long recording into short vertical clips with captions. Shotstack makes the transcript, an AI model from any OpenAI-compatible provider picks the moments, and one render per clip cuts it and adds captions from the transcript. Companion code for [Build a video clipping pipeline with the Shotstack API](https://shotstack.io/learn/video-clipping-api-pipeline/). ## Contributing diff --git a/examples/video-clipping-pipeline/.env.example b/examples/video-clipping-pipeline/.env.example index 6e03112..15cfa9b 100644 --- a/examples/video-clipping-pipeline/.env.example +++ b/examples/video-clipping-pipeline/.env.example @@ -1,8 +1,14 @@ # Your Shotstack API key: https://dashboard.shotstack.io SHOTSTACK_API_KEY= -# Your Anthropic API key, for picking the moments: https://platform.claude.com/settings/keys -ANTHROPIC_API_KEY= - # Optional. Set to stage for free watermarked test renders. Then use your sandbox key. SHOTSTACK_ENV= + +# The OpenAI-compatible API of your AI provider. The README gives the URL for each provider. +AI_BASE_URL= + +# Your API key for that provider. The README gives the page where you get it. +AI_API_KEY= + +# The model that picks the moments, for example gpt-5.4-mini +AI_MODEL= diff --git a/examples/video-clipping-pipeline/README.md b/examples/video-clipping-pipeline/README.md index 3390849..5ee6518 100644 --- a/examples/video-clipping-pipeline/README.md +++ b/examples/video-clipping-pipeline/README.md @@ -1,9 +1,9 @@ # Video clipping pipeline Turn a long recording into five short vertical clips with captions. Shotstack -imports the recording and makes a transcript. Claude picks the best moments. -Shotstack cuts each moment and adds a title and captions. You get the MP4 -files in `clips//`. +imports the recording and makes a transcript. An AI model picks the best +moments. Shotstack renders each moment with a title and captions. You get the +MP4 files in `clips//`. Related guide: [Build a video clipping pipeline with the Shotstack API](https://shotstack.io/learn/video-clipping-api-pipeline/). @@ -11,12 +11,12 @@ Related guide: [Build a video clipping pipeline with the Shotstack API](https:// - A [Shotstack account](https://dashboard.shotstack.io/register) and your **production** API key -- An [Anthropic API key](https://platform.claude.com/settings/keys). Claude - picks the moments. -- Python 3.9 or later +- An API key from an AI provider with an OpenAI-compatible chat API, for + example OpenAI, Anthropic or Google Gemini +- Python 3.8 or later, with `requests` 2.18 or later - A public URL that gives the video file, not a web page -Each clip uses two renders. Production renders use credits. Rates are on the +Each clip uses one render. Production renders use credits. Rates are on the [pricing page](https://shotstack.io/pricing/). Set `SHOTSTACK_ENV=stage` in `.env` and use your sandbox key for free watermarked test renders. @@ -31,8 +31,16 @@ python -m pip install -r requirements.txt cp .env.example .env ``` -Set `SHOTSTACK_API_KEY` and `ANTHROPIC_API_KEY` in `.env`. Then load the file. -Do this in each new terminal, and each time you change `.env`: +Set `SHOTSTACK_API_KEY` in `.env`. Then set `AI_BASE_URL`, `AI_API_KEY` and +`AI_MODEL` for your AI provider: + +| Provider | `AI_BASE_URL` | `AI_MODEL`, for example | API key | +| ------------- | --------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------- | +| OpenAI | `https://api.openai.com/v1` | `gpt-5.4-mini` | [platform.openai.com](https://platform.openai.com/api-keys) | +| Anthropic | `https://api.anthropic.com/v1` | `claude-sonnet-5-5` | [platform.claude.com](https://platform.claude.com/settings/keys) | +| Google Gemini | `https://generativelanguage.googleapis.com/v1beta/openai` | `gemini-3.5-flash` | [aistudio.google.com](https://aistudio.google.com/apikey) | + +Load the file. Do this in each new terminal, and each time you change `.env`: ```bash set -a @@ -54,19 +62,19 @@ your own recording, replace the URL. ## What happens The script imports the recording with the Ingest API and waits for the -transcript. Then it sends the transcript to Claude, one sentence on each line. -Claude gives the first and last words of five moments. The script finds these -words in the transcript. It makes sure that each moment is 15 to 60 seconds -long and does not overlap another moment. It asks Claude one more time to fix -the moments that fail. It saves the moments in `moments.json`. +transcript. Then it sends the transcript to the AI model, one sentence on each +line. The model gives the first and last words of five moments. The script +finds these words in the transcript. It makes sure that each moment is 15 to 60 +seconds long and does not overlap another moment. It asks the model one more +time to fix the moments that fail. It saves the moments in `moments.json`. -Each clip uses two renders. The first render cuts the moment and puts it in a -1080x1920 frame. The second render adds the title and captions from the audio -of the cut. The script downloads each clip to `clip-MMmSSs.mp4`, named by its -start time in the recording. +For each moment, the script cuts the transcript lines into a caption file and +uploads it. One render cuts the moment from the recording, puts it in a +1080x1920 frame, and adds the title and the captions. The script downloads each +clip to `clip-MMmSSs.mp4`, named by its start time in the recording. With the demo recording, which is 52 minutes long, the import takes about 4 -minutes. Each clip takes 2 to 4 minutes, and the clips render at the same time. +minutes. Each clip takes about 2 minutes, and the clips render at the same time. The script saves its progress in `manifest.json`. Run the same command again to continue after a stop. It does not import the recording or pick the diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py index 54404e5..c034bb4 100644 --- a/examples/video-clipping-pipeline/clips.py +++ b/examples/video-clipping-pipeline/clips.py @@ -4,9 +4,9 @@ python clips.py RECORDING_URL [--limit N] [--repick] Step 1 imports the recording with Shotstack's Ingest API and gets its transcript. -Step 2 asks Claude to pick the best moments and saves them to moments.json. -Step 3 renders each moment twice: once to cut it out and fit it into a vertical -frame, and once to add captions generated from the cut's own audio. +Step 2 asks an AI model to pick the best moments and saves them to moments.json. +Step 3 renders each moment once: it cuts the moment out of the recording, fits it +into a vertical frame, and adds a title and captions made from the transcript. Step 4 does that for every moment and downloads the finished clips. Everything for one recording goes in clips//. Progress is saved to @@ -15,8 +15,10 @@ Environment variables: SHOTSTACK_API_KEY your Shotstack API key - ANTHROPIC_API_KEY your Anthropic API key (only needed to pick moments) SHOTSTACK_ENV "v1" for production (the default) or "stage" for the sandbox + AI_BASE_URL the OpenAI-compatible API of your AI provider + AI_API_KEY your API key for that provider + AI_MODEL the model that picks the moments """ import argparse @@ -39,16 +41,19 @@ "x-api-key": os.environ.get("SHOTSTACK_API_KEY", ""), "Accept": "application/json", } +AI_BASE_URL = os.environ.get("AI_BASE_URL", "").rstrip("/") +AI_API_KEY = os.environ.get("AI_API_KEY", "") +AI_MODEL = os.environ.get("AI_MODEL", "") CLIP_COUNT = 5 MIN_SECONDS, MAX_SECONDS = 15, 60 POLL_SECONDS = 10 +UPLOAD_POLL_SECONDS = 2 IMPORT_TIMEOUT = 60 * 60 # stop waiting for the import and transcript after an hour RENDER_TIMEOUT = 60 * 60 # and for the renders -# A render's URL can be deleted after 24 hours. A cut older than this is rendered -# again before its captions are. -CUT_MAX_AGE = 20 * 60 * 60 +UPLOAD_TIMEOUT = 2 * 60 # and for a caption file to be ready +AI_TIMEOUT = 5 * 60 # one request to the AI model def fail(message): @@ -99,16 +104,21 @@ class Unresolved(Exception): def error_detail(body): - """The reason in an error body: Ingest sends errors[0].detail, Edit sends - response.error or message.""" + """The reason in an error body. Shotstack's Ingest API sends errors[0].detail, + its Edit API sends response.error or message, and OpenAI-compatible APIs send + error.message.""" + if isinstance(body, list) and body: + body = body[0] if not isinstance(body, dict): return "" errors = body.get("errors") first = errors[0] if isinstance(errors, list) and errors else None response = body.get("response") + error = body.get("error") for value in ( first.get("detail") if isinstance(first, dict) else None, response.get("error") if isinstance(response, dict) else None, + error.get("message") if isinstance(error, dict) else error, body.get("message"), ): if isinstance(value, str) and value: @@ -160,6 +170,37 @@ def get_json(url): fail(f"GET {url} kept failing. Run the same command again to carry on.") +def upload_text(text): + """Upload a small text file with the Ingest API and return its URL. An upload + doesn't cost anything, so a failed one is sent again on the next run.""" + try: + data = post_json(f"{INGEST}/upload", {}).get("data") + except Unresolved as error: + raise ApiError(f"the upload request didn't complete ({error})") from error + attributes = data.get("attributes") if isinstance(data, dict) else None + if not isinstance(attributes, dict) or not attributes.get("url"): + raise ApiError("the upload reply had no upload URL") + # The upload URL has no file name, so the content type tells Shotstack the type. + requests.put( + attributes["url"], + data=text.encode("utf-8"), + headers={"Content-Type": "text/plain"}, + timeout=60, + ).raise_for_status() + started = time.time() + while time.time() - started < UPLOAD_TIMEOUT: + source = get_json(f"{INGEST}/sources/{data['id']}")["data"]["attributes"] + if source.get("status") == "ready": + return source["source"] + if source.get("status") == "failed": + reason = source.get("error") or "no reason given" + raise ApiError(f"Shotstack couldn't read the caption file ({reason})") + time.sleep(UPLOAD_POLL_SECONDS) + raise ApiError( + f"the caption file wasn't ready after {UPLOAD_TIMEOUT // 60} minutes" + ) + + def download(url, path): """Save a file Shotstack hosts. No API key: these are plain file URLs.""" with requests.get(url, stream=True, timeout=120) as response: @@ -261,12 +302,6 @@ def seconds(timestamp): # ---------------------------------------- step 2: pick the moments -MODEL = "claude-sonnet-5-5" -MAX_TOKENS = 1000 -# Sonnet 5.5 can't turn thinking off. "between_tools" is its lowest setting: no -# thinking before it answers, and this request has no tools to think between. -THINKING = {"type": "between_tools"} - PROMPT = f"""\ You pick moments from a talk transcript to turn into short vertical video clips. @@ -284,28 +319,10 @@ def seconds(timestamp): For each moment, copy the first six to ten words of its first sentence and the last six to ten words of its last sentence exactly as they appear in the transcript, and -give it a short title of at most eight words. List the moments from best to worst.""" - -MOMENTS_SCHEMA = { - "type": "object", - "properties": { - "moments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "first_words": {"type": "string"}, - "last_words": {"type": "string"}, - "title": {"type": "string"}, - }, - "required": ["first_words", "last_words", "title"], - "additionalProperties": False, - }, - }, - }, - "required": ["moments"], - "additionalProperties": False, -} +give it a short title of at most eight words. List the moments from best to worst. + +Reply with JSON only, in this form: +{{"moments": [{{"first_words": "...", "last_words": "...", "title": "..."}}]}}""" def sentences(cues): @@ -347,26 +364,63 @@ def find(target, stream, after=0): yield stream[k][1], stream[k + len(target) - 1][1] -def ask_claude(client, messages): - """One request to Claude. Structured outputs make the reply JSON that matches - the schema.""" - response = client.messages.create( - model=MODEL, - max_tokens=MAX_TOKENS, - thinking=THINKING, - system=PROMPT, - messages=messages, - output_config={"format": {"type": "json_schema", "schema": MOMENTS_SCHEMA}}, - ) - if response.stop_reason != "end_turn": +def ask_ai(messages): + """One request to the AI model through the OpenAI-compatible chat API, which + OpenAI, Anthropic, Google Gemini and many other providers offer. Returns the + text of the reply.""" + url = f"{AI_BASE_URL}/chat/completions" + try: + response = requests.post( + url, + headers={"Authorization": f"Bearer {AI_API_KEY}"}, + json={"model": AI_MODEL, "messages": messages}, + timeout=AI_TIMEOUT, + ) + except requests.RequestException as error: fail( - f"Claude stopped early ({response.stop_reason}), " - "so its reply isn't complete." + f"could not reach {url} ({type(error).__name__}). " + "Check AI_BASE_URL and your network." ) - text = next((b.text for b in response.content if b.type == "text"), None) - if text is None: - fail("Claude's reply has no text.") - return json.loads(text)["moments"] + try: + body = response.json() + except ValueError: + body = None + if response.status_code in (401, 403): + fail( + f"the AI provider refused AI_API_KEY ({response.status_code} " + f"{error_detail(body)})." + ) + if response.status_code >= 400: + reason = error_detail(body) or response.reason + fail( + f"the AI provider answered {response.status_code} ({reason}). " + "Check AI_BASE_URL and AI_MODEL." + ) + try: + choice = body["choices"][0] + text = choice["message"]["content"] + except (TypeError, KeyError, IndexError): + fail(f"{url} didn't send a chat reply. Check AI_BASE_URL.") + if choice.get("finish_reason") == "length": + fail("the AI model's reply was cut off. Try another AI_MODEL.") + return text or "" + + +def read_reply(reply): + """The moments in the AI model's reply, or None if it isn't the JSON asked for. + Some models put the JSON in a code block, so this reads from the first { to the + last }.""" + try: + picks = json.loads(reply[reply.find("{") : reply.rfind("}") + 1])["moments"] + except (ValueError, KeyError, TypeError): + return None + fields = ("first_words", "last_words", "title") + if not isinstance(picks, list) or not all( + isinstance(p, dict) and all(isinstance(p.get(f), str) for f in fields) + for p in picks + ): + return None + return picks def check_picks(picks, lines, duration): @@ -418,24 +472,38 @@ def check_picks(picks, lines, duration): return moments[:CLIP_COUNT], problems -def pick_moments(client, lines, duration): - """Ask Claude for moments, and ask once more if too few of them pass the checks.""" - messages = [{"role": "user", "content": transcript_text(lines)}] - picks = ask_claude(client, messages) - moments, problems = check_picks(picks, lines, duration) +def check_reply(reply, lines, duration): + picks = read_reply(reply) + if picks is None: + return [], ["the reply isn't the JSON that was asked for"] + return check_picks(picks, lines, duration) + + +def pick_moments(lines, duration): + """Ask the AI model for moments, and ask once more if too few of them pass the + checks.""" + messages = [ + {"role": "system", "content": PROMPT}, + {"role": "user", "content": transcript_text(lines)}, + ] + reply = ask_ai(messages) + moments, problems = check_reply(reply, lines, duration) if len(moments) < CLIP_COUNT: - print("Asking Claude to fix these:" + "".join(f"\n - {p}" for p in problems)) + print( + "Asking the AI model to fix these:" + + "".join(f"\n - {p}" for p in problems) + ) messages += [ - {"role": "assistant", "content": json.dumps({"moments": picks})}, + {"role": "assistant", "content": reply}, { "role": "user", "content": "Some of those moments break the rules:\n" + "\n".join(f"- {p}" for p in problems) + f"\nSend the full list of {CLIP_COUNT} moments again, " - "with these fixed.", + "with these fixed, as JSON only.", }, ] - retried = check_picks(ask_claude(client, messages), lines, duration) + retried = check_reply(ask_ai(messages), lines, duration) if len(retried[0]) > len(moments): # keep the first answer if it was better moments, problems = retried return moments, problems @@ -482,16 +550,7 @@ def get_moments(lines, manifest, folder, repick): with a different picker, and the renders use it as it is.""" path = folder / "moments.json" picked_with = hashlib.sha256( - json.dumps( - [ - transcript_text(lines), - MODEL, - MAX_TOKENS, - THINKING, - PROMPT, - MOMENTS_SCHEMA, - ] - ).encode() + json.dumps([transcript_text(lines), AI_BASE_URL, AI_MODEL, PROMPT]).encode() ).hexdigest()[:16] if ( path.exists() @@ -501,28 +560,18 @@ def get_moments(lines, manifest, folder, repick): print(f"Using the moments in {path}") return read_moments(path, manifest["duration"]) - if not os.environ.get("ANTHROPIC_API_KEY"): - fail("set ANTHROPIC_API_KEY so Claude can pick the moments.") - try: - import anthropic # only this step needs it - except ImportError: - fail("install the anthropic package (pip install -r requirements.txt).") - print(f"Asking {MODEL} for {CLIP_COUNT} moments from {len(lines)} sentences") - try: - moments, problems = pick_moments( - anthropic.Anthropic(), lines, manifest["duration"] + if not (AI_BASE_URL and AI_API_KEY and AI_MODEL): + fail( + "set AI_BASE_URL, AI_API_KEY and AI_MODEL so an AI model can pick the " + "moments. The README gives the values for common providers." ) - except anthropic.AuthenticationError: - fail("Anthropic refused the API key. Check ANTHROPIC_API_KEY.") - except anthropic.APIConnectionError: - fail("could not reach the Claude API. Check your network and run again.") - except anthropic.APIError as error: - fail(f"the Claude API returned an error: {error}") + print(f"Asking {AI_MODEL} for {CLIP_COUNT} moments from {len(lines)} sentences") + moments, problems = pick_moments(lines, manifest["duration"]) for problem in problems: print(f" left out: {problem}") if not moments: fail( - "none of the moments passed the checks. Run again to ask Claude again, " + "none of the moments passed the checks. Run again to ask again, " f"or write {path} by hand." ) path.write_text(json.dumps(moments, indent=2)) @@ -542,31 +591,23 @@ def get_moments(lines, manifest, folder, repick): # ---------------------------------------- step 3: render one clip -def cut_edit(source_url, moment): - """Render 1: cut the moment out of the recording and fit it into a vertical - frame.""" - return { - "timeline": { - "background": "#000000", - "tracks": [ - { - "clips": [ - { - "asset": { - "type": "video", - "src": source_url, - "trim": moment["start"], - }, - "start": 0, - "length": round(moment["end"] - moment["start"], 3), - "fit": "contain", - } - ] - }, - ], - }, - "output": {"format": "mp4", "size": {"width": 1080, "height": 1920}}, - } +def clip_srt(cues, moment): + """The transcript's cues inside one moment, as an SRT file timed from the start + of the clip. The captions come from this file, so nothing is transcribed again.""" + + def stamp(seconds): + """62.5 -> '00:01:02,500'""" + minutes, ms = divmod(round(seconds * 1000), 60000) + return ( + f"{minutes // 60:02d}:{minutes % 60:02d}:{ms // 1000:02d},{ms % 1000:03d}" + ) + + inside = [c for c in cues if c.end > moment["start"] and c.start < moment["end"]] + return "\n".join( + f"{n}\n{stamp(max(c.start - moment['start'], 0))} --> " + f"{stamp(min(c.end, moment['end']) - moment['start'])}\n{c.text}\n" + for n, c in enumerate(inside, 1) + ) # Roboto, a variable font, loaded so the bold weights below apply. A loaded font @@ -576,12 +617,10 @@ def cut_edit(source_url, moment): ROBOTO = "KFOmCnqEu92Fr1Me5WZLCzYlKw" -def caption_edit(cut_url, title): - """Render 2: add a title and captions generated from the cut's own audio. - - The title sits in the black band above the video. The captions come from the - clip named "clip" through an alias. They sit in the band under the video, with - the word being spoken in yellow.""" +def clip_edit(source_url, moment, captions_url): + """The one render for one clip. It cuts the moment out of the recording and fits + it into a vertical frame. The title sits in the black band above the video, and + the captions sit in the band under it, with the word being spoken in yellow.""" return { "timeline": { "background": "#000000", @@ -592,7 +631,7 @@ def caption_edit(cut_url, title): { "asset": { "type": "rich-text", - "text": title, + "text": moment["title"], "font": { "family": ROBOTO, "size": 76, @@ -615,7 +654,7 @@ def caption_edit(cut_url, title): { "asset": { "type": "rich-caption", - "src": "alias://clip", + "src": captions_url, "font": { "family": ROBOTO, "size": 64, @@ -636,10 +675,14 @@ def caption_edit(cut_url, title): { "clips": [ { - "alias": "clip", - "asset": {"type": "video", "src": cut_url}, + "asset": { + "type": "video", + "src": source_url, + "trim": moment["start"], + }, "start": 0, - "length": "auto", + "length": round(moment["end"] - moment["start"], 3), + "fit": "contain", } ] }, @@ -677,29 +720,27 @@ def finished(render, label): return render["status"] == "done" -def advance(job, moment, source_url, path, label): - """Take one clip a step further: cut and reframe, then captions, then download.""" - if "cut" not in job: - job["cut"] = submit(cut_edit(source_url, moment), f"{label} cut") +def advance(job, moment, source_url, cues, path, label): + """Take one clip a step further: upload its captions and render it, then + download it.""" + if "render" not in job: + if "captions" not in job: + srt = clip_srt(cues, moment) + if not srt: + fail(f"{label} has no words in the transcript. Edit moments.json.") + job["captions"] = upload_text(srt) + job["render"] = submit(clip_edit(source_url, moment, job["captions"]), label) return - if not finished(job["cut"], f"{label} cut"): - return - if "captions" not in job: - # Render URLs can be deleted after 24 hours, so caption each cut as soon as - # it's ready. - job["captions"] = submit( - caption_edit(job["cut"]["url"], moment["title"]), f"{label} captions" - ) - return - if not finished(job["captions"], f"{label} captions"): + if not finished(job["render"], label): return try: - # This URL can be deleted after 24 hours too - download(job["captions"]["url"], path) + # Render URLs can be deleted after 24 hours, so each clip is downloaded as + # soon as it's done. + download(job["render"]["url"], path) except requests.HTTPError as error: status = getattr(error.response, "status_code", None) if status in (403, 404, 410): - del job["captions"] # so the next run renders the captions again + del job["render"] # the file is gone, so the next run renders it again job["error"] = f"the rendered file is gone (HTTP {status})" return raise @@ -715,33 +756,23 @@ def clip_state(job): return "done" if "unresolved" in job: return "unresolved" - if "error" in job or "failed" in ( - job.get("cut", {}).get("status"), - job.get("captions", {}).get("status"), - ): + if "error" in job or job.get("render", {}).get("status") == "failed": return "failed" return "working" -def render_clips(moments, manifest, folder): - """Submit every clip's renders and poll until each clip is done or has failed. +def render_clips(moments, cues, manifest, folder): + """Submit every clip's render and poll until each clip is done or has failed. - Each clip is two render requests, tracked by ID.""" + Each clip is one render request, tracked by ID.""" jobs = manifest.setdefault("renders", {}) todo = [] for n, moment in enumerate(moments, 1): job = jobs.setdefault(f"{moment['start']:.3f}-{moment['end']:.3f}", {}) if clip_state(job) == "failed": # a new run tries failed clips again job.pop("error", None) - cut = job.get("cut", {}) - redo_captions = job.get("captions", {}).get("status") in (None, "failed") - # The captions render reads the cut's URL, so an old cut is made again - cut_is_old = time.time() - cut.get("submitted", 0) > CUT_MAX_AGE - if cut.get("status") == "failed" or (redo_captions and cut_is_old): - job.pop("cut", None) - job.pop("captions", None) - elif redo_captions: - job.pop("captions", None) + if job.get("render", {}).get("status") == "failed": + del job["render"] minutes, seconds = divmod(int(moment["start"]), 60) todo.append((n, moment, job, folder / f"clip-{minutes:02d}m{seconds:02d}s.mp4")) manifest.save() @@ -753,7 +784,7 @@ def render_clips(moments, manifest, folder): if clip_state(job) != "working": continue try: - advance(job, moment, manifest["source_url"], path, f"clip {n}") + advance(job, moment, manifest["source_url"], cues, path, f"clip {n}") except Unresolved as error: # Don't resubmit: the render may have started, and a retry could # duplicate it. @@ -786,9 +817,7 @@ def report(todo): '"renders" in manifest.json and run again.' ) else: - reasons = [job.get("error")] + [ - job.get(stage, {}).get("error") for stage in ("cut", "captions") - ] + reasons = [job.get("error"), job.get("render", {}).get("error")] reason = "; ".join(r for r in reasons if r) print( f" {n}. {moment['title']} ({where}): failed ({reason}). " @@ -811,7 +840,7 @@ def main(): parser.add_argument( "--repick", action="store_true", - help="ask Claude for new moments even if moments.json is up to date", + help="ask the AI model for new moments even if moments.json is up to date", ) args = parser.parse_args() @@ -835,11 +864,9 @@ def main(): try: if "source_url" not in manifest: import_recording(args.url, manifest, folder) - lines = sentences( - parse_srt((folder / "transcript.srt").read_text(encoding="utf-8")) - ) - moments = get_moments(lines, manifest, folder, args.repick) - todo = render_clips(moments[: args.limit], manifest, folder) + cues = parse_srt((folder / "transcript.srt").read_text(encoding="utf-8")) + moments = get_moments(sentences(cues), manifest, folder, args.repick) + todo = render_clips(moments[: args.limit], cues, manifest, folder) except Unresolved as error: fail( f"a request didn't complete ({error}). Check your network. The request " diff --git a/examples/video-clipping-pipeline/requirements.txt b/examples/video-clipping-pipeline/requirements.txt index e7166f5..2a4ce5a 100644 --- a/examples/video-clipping-pipeline/requirements.txt +++ b/examples/video-clipping-pipeline/requirements.txt @@ -1,2 +1 @@ -anthropic>=0.77.0 requests>=2.18 diff --git a/examples/video-clipping-pipeline/test_clips.py b/examples/video-clipping-pipeline/test_clips.py index 065434b..5540dc0 100644 --- a/examples/video-clipping-pipeline/test_clips.py +++ b/examples/video-clipping-pipeline/test_clips.py @@ -1,4 +1,4 @@ -"""Tests for the resume logic of clips.py. They do not call Shotstack or Claude. +"""Tests for clips.py. They do not call Shotstack or an AI provider. Run them from this directory: python3 -m unittest """ @@ -17,6 +17,7 @@ RECORDING = "https://example.com/talk.mp4" MOMENT = {"start": 61.0, "end": 91.0, "title": "A moment"} +CUES = [clips.Cue(61.0, 70.0, "First words here."), clips.Cue(70.0, 91.0, "The end.")] URL = "https://cdn.shotstack.io/au/stage/owner/render.mp4" @@ -26,6 +27,12 @@ def http_error(status_code): return requests.HTTPError(f"{status_code} for {URL}", response=response) +def quietly(function, *args): + with contextlib.redirect_stdout(io.StringIO()): + with contextlib.redirect_stderr(io.StringIO()): + return function(*args) + + class FakeEdit: """Stands in for the Edit API. Every render it accepts is done at once, unless its ID is in `failed`.""" @@ -59,11 +66,13 @@ def setUp(self): manifest.update(source_url=RECORDING, duration=3600) manifest.save() self.edit = FakeEdit() + self.uploads = [] self.downloads = [] self.download_errors = [] replacements = { "post_json": self.edit.post_json, "get_json": self.edit.get_json, + "upload_text": self.upload_text, "download": self.download, } for name, value in replacements.items(): @@ -74,6 +83,10 @@ def setUp(self): sleep.start() self.addCleanup(sleep.stop) + def upload_text(self, text): + self.uploads.append(text) + return "https://example.com/captions.srt" + def download(self, url, path): if self.download_errors: raise self.download_errors.pop(0) @@ -83,16 +96,23 @@ def download(self, url, path): def run_clips(self): """One run of the render step, from the manifest on disk. Returns the job.""" manifest = clips.Manifest(self.folder / "manifest.json", RECORDING) - with contextlib.redirect_stdout(io.StringIO()): - todo = clips.render_clips([MOMENT], manifest, self.folder) + todo = quietly(clips.render_clips, [MOMENT], CUES, manifest, self.folder) return todo[0][2] - def test_a_clip_takes_two_renders_and_one_download(self): + def test_a_clip_takes_one_upload_one_render_and_one_download(self): job = self.run_clips() self.assertEqual(clips.clip_state(job), "done") - self.assertEqual(len(self.edit.submits), 2) + self.assertEqual(len(self.uploads), 1) + self.assertEqual(len(self.edit.submits), 1) self.assertEqual(len(self.downloads), 1) + def test_the_render_uses_the_uploaded_captions(self): + self.run_clips() + tracks = self.edit.submits[0]["timeline"]["tracks"] + captions = tracks[1]["clips"][0]["asset"] + self.assertEqual(captions["type"], "rich-caption") + self.assertEqual(captions["src"], "https://example.com/captions.srt") + def test_a_submit_that_did_not_complete_is_not_sent_again(self): self.edit.post_errors = [clips.Unresolved("ReadTimeout")] self.assertEqual(clips.clip_state(self.run_clips()), "unresolved") @@ -103,45 +123,114 @@ def test_a_refused_submit_is_sent_again_on_the_next_run(self): self.edit.post_errors = [clips.ApiError("429 from the Edit API")] self.assertEqual(clips.clip_state(self.run_clips()), "failed") self.assertEqual(clips.clip_state(self.run_clips()), "done") - self.assertEqual(len(self.edit.submits), 2) + self.assertEqual(len(self.edit.submits), 1) + self.assertEqual(len(self.uploads), 1) # the captions are kept def test_a_failed_download_does_not_render_again(self): self.download_errors = [requests.ConnectionError("network down")] self.assertEqual(clips.clip_state(self.run_clips()), "failed") self.assertEqual(clips.clip_state(self.run_clips()), "done") - self.assertEqual(len(self.edit.submits), 2) + self.assertEqual(len(self.edit.submits), 1) - def test_a_deleted_file_renders_the_captions_again(self): + def test_a_deleted_file_is_rendered_again(self): self.download_errors = [http_error(404)] self.assertEqual(clips.clip_state(self.run_clips()), "failed") self.assertEqual(clips.clip_state(self.run_clips()), "done") - # cut, captions, captions again: the cut is new enough to use again - self.assertEqual(len(self.edit.submits), 3) - self.assertIn("fonts", self.edit.submits[2]["timeline"]) - - def test_an_old_cut_is_rendered_again_before_its_captions(self): - self.download_errors = [http_error(404)] - self.run_clips() - manifest = clips.Manifest(self.folder / "manifest.json", RECORDING) - for job in manifest["renders"].values(): - job["cut"]["submitted"] -= clips.CUT_MAX_AGE + 1 - manifest.save() - self.assertEqual(clips.clip_state(self.run_clips()), "done") - self.assertEqual(len(self.edit.submits), 4) - self.assertNotIn("fonts", self.edit.submits[2]["timeline"]) + self.assertEqual(len(self.edit.submits), 2) + self.assertEqual(len(self.uploads), 1) - def test_a_failed_captions_render_redoes_only_the_captions(self): - self.edit.failed = {"render-2"} + def test_a_failed_render_is_rendered_again(self): + self.edit.failed = {"render-1"} self.assertEqual(clips.clip_state(self.run_clips()), "failed") self.edit.failed = set() self.assertEqual(clips.clip_state(self.run_clips()), "done") - # The third render is the captions again (it loads the font), not a new cut - self.assertEqual(len(self.edit.submits), 3) - self.assertIn("fonts", self.edit.submits[2]["timeline"]) + self.assertEqual(len(self.edit.submits), 2) + + +class ClipSrt(unittest.TestCase): + def test_the_captions_are_timed_from_the_start_of_the_clip(self): + cues = [ + clips.Cue(59.0, 62.0, "Before and in."), + clips.Cue(62.0, 70.5, "Inside."), + clips.Cue(95.0, 99.0, "After."), + ] + self.assertEqual( + clips.clip_srt(cues, MOMENT), + "1\n00:00:00,000 --> 00:00:01,000\nBefore and in.\n\n" + "2\n00:00:01,000 --> 00:00:09,500\nInside.\n", + ) + + +class UploadText(unittest.TestCase): + def test_the_file_is_sent_as_text(self): + signed = {"data": {"id": "src-1", "attributes": {"url": "https://s3/upload"}}} + ready = {"data": {"attributes": {"status": "ready", "source": "https://s3/f"}}} + put = mock.Mock() + with mock.patch.object( + clips, "post_json", return_value=signed + ), mock.patch.object(clips, "get_json", return_value=ready), mock.patch.object( + clips.requests, "put", put + ): + self.assertEqual( + clips.upload_text("1\n00:00:00,000 --> 00:00:01,000\nHi\n"), + "https://s3/f", + ) + self.assertEqual( + put.call_args.kwargs["headers"], {"Content-Type": "text/plain"} + ) + + def test_an_upload_that_did_not_complete_is_tried_again_later(self): + error = clips.Unresolved("ConnectionError") + with mock.patch.object(clips, "post_json", side_effect=error): + with self.assertRaises(clips.ApiError): + clips.upload_text("text") + + +class ReadReply(unittest.TestCase): + PICK = {"first_words": "a b", "last_words": "c d", "title": "T"} + + def test_json_in_a_code_block_is_read(self): + reply = "```json\n" + json.dumps({"moments": [self.PICK]}) + "\n```" + self.assertEqual(clips.read_reply(reply), [self.PICK]) + + def test_a_reply_that_is_not_json_is_refused(self): + self.assertIsNone(clips.read_reply("Here are the best moments: ...")) + + def test_a_moment_without_a_title_is_refused(self): + reply = json.dumps({"moments": [{"first_words": "a", "last_words": "b"}]}) + self.assertIsNone(clips.read_reply(reply)) + + +class AskAi(unittest.TestCase): + def ask(self, status_code, body): + response = requests.Response() + response.status_code = status_code + response._content = json.dumps(body).encode() + with mock.patch.object(clips.requests, "post", return_value=response) as post: + try: + return quietly(clips.ask_ai, [{"role": "user", "content": "hi"}]), post + except SystemExit as stop: + return str(stop), post + + def test_the_reply_text_is_returned(self): + body = {"choices": [{"message": {"content": "{}"}, "finish_reason": "stop"}]} + text, post = self.ask(200, body) + self.assertEqual(text, "{}") + self.assertTrue(post.call_args.args[0].endswith("/chat/completions")) + + def test_a_refused_key_stops_with_one_line(self): + message, _ = self.ask(401, {"error": {"message": "Incorrect API key"}}) + self.assertIn("refused AI_API_KEY", message) + self.assertIn("Incorrect API key", message) + + def test_a_reply_that_was_cut_off_stops(self): + body = {"choices": [{"message": {"content": "{"}, "finish_reason": "length"}]} + message, _ = self.ask(200, body) + self.assertIn("cut off", message) class CheckPicks(unittest.TestCase): - """How Claude's quotes become start and end times.""" + """How the AI model's quotes become start and end times.""" def test_a_repeated_phrase_uses_the_shortest_span(self): lines = [ @@ -172,8 +261,7 @@ def read(self, moments): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "moments.json" path.write_text(json.dumps(moments)) - with contextlib.redirect_stderr(io.StringIO()): - return clips.read_moments(path, 3600) + return quietly(clips.read_moments, path, 3600) def test_overlapping_moments_are_refused(self): with self.assertRaises(SystemExit): @@ -219,7 +307,7 @@ def test_a_refusal_names_the_reason(self): def test_a_reply_with_no_render_id_is_not_sent_again(self): with mock.patch.object(clips, "post_json", return_value={"response": {}}): with self.assertRaises(clips.Unresolved): - clips.submit({}, "clip 1") + quietly(clips.submit, {}, "clip 1") if __name__ == "__main__": From fa0dfc6ec11ebba8bf087ec26760ece1e68c31b7 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 06:56:23 +0500 Subject: [PATCH 06/12] Tidy AI error hints and comments in the video clipping example --- examples/video-clipping-pipeline/clips.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py index c034bb4..10360db 100644 --- a/examples/video-clipping-pipeline/clips.py +++ b/examples/video-clipping-pipeline/clips.py @@ -172,7 +172,7 @@ def get_json(url): def upload_text(text): """Upload a small text file with the Ingest API and return its URL. An upload - doesn't cost anything, so a failed one is sent again on the next run.""" + can't start a render, so a failed one is safe to send again on the next run.""" try: data = post_json(f"{INGEST}/upload", {}).get("data") except Unresolved as error: @@ -392,10 +392,12 @@ def ask_ai(messages): ) if response.status_code >= 400: reason = error_detail(body) or response.reason - fail( - f"the AI provider answered {response.status_code} ({reason}). " - "Check AI_BASE_URL and AI_MODEL." + check = ( + " Check AI_BASE_URL and AI_MODEL." + if response.status_code in (400, 404) + else "" ) + fail(f"the AI provider answered {response.status_code} ({reason}).{check}") try: choice = body["choices"][0] text = choice["message"]["content"] @@ -734,8 +736,6 @@ def advance(job, moment, source_url, cues, path, label): if not finished(job["render"], label): return try: - # Render URLs can be deleted after 24 hours, so each clip is downloaded as - # soon as it's done. download(job["render"]["url"], path) except requests.HTTPError as error: status = getattr(error.response, "status_code", None) From 65056f87638b1a094d9e4f4161e6131de785fb78 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 07:02:37 +0500 Subject: [PATCH 07/12] Use the measured clip times in the video clipping README --- examples/video-clipping-pipeline/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/video-clipping-pipeline/README.md b/examples/video-clipping-pipeline/README.md index 5ee6518..ab2be28 100644 --- a/examples/video-clipping-pipeline/README.md +++ b/examples/video-clipping-pipeline/README.md @@ -74,7 +74,7 @@ uploads it. One render cuts the moment from the recording, puts it in a clip to `clip-MMmSSs.mp4`, named by its start time in the recording. With the demo recording, which is 52 minutes long, the import takes about 4 -minutes. Each clip takes about 2 minutes, and the clips render at the same time. +minutes. Each clip takes 1 to 3 minutes, and the clips render at the same time. The script saves its progress in `manifest.json`. Run the same command again to continue after a stop. It does not import the recording or pick the From 08b2c65014f8260d22c6509258b512db75a23266 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 07:05:33 +0500 Subject: [PATCH 08/12] Fix second review findings in the video clipping example --- examples/video-clipping-pipeline/.env.example | 5 +- examples/video-clipping-pipeline/clips.py | 113 +++++++++++------- .../video-clipping-pipeline/test_clips.py | 90 +++++++++++--- 3 files changed, 147 insertions(+), 61 deletions(-) diff --git a/examples/video-clipping-pipeline/.env.example b/examples/video-clipping-pipeline/.env.example index 15cfa9b..7f92711 100644 --- a/examples/video-clipping-pipeline/.env.example +++ b/examples/video-clipping-pipeline/.env.example @@ -4,10 +4,11 @@ SHOTSTACK_API_KEY= # Optional. Set to stage for free watermarked test renders. Then use your sandbox key. SHOTSTACK_ENV= -# The OpenAI-compatible API of your AI provider. The README gives the URL for each provider. +# Your AI provider's OpenAI-compatible API, for example https://api.openai.com/v1 +# The README lists the values for OpenAI, Anthropic and Google Gemini. AI_BASE_URL= -# Your API key for that provider. The README gives the page where you get it. +# Your API key for that provider, for example from https://platform.openai.com/api-keys AI_API_KEY= # The model that picks the moments, for example gpt-5.4-mini diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py index 10360db..256616f 100644 --- a/examples/video-clipping-pipeline/clips.py +++ b/examples/video-clipping-pipeline/clips.py @@ -22,7 +22,6 @@ """ import argparse -import hashlib import json import os import re @@ -89,7 +88,10 @@ def __init__(self, path, url): ) def save(self): - self.path.write_text(json.dumps(self, indent=2)) + # Write a new file, then swap it in, so a crash can't leave half a manifest + temp = self.path.with_suffix(".tmp") + temp.write_text(json.dumps(self, indent=2)) + os.replace(temp, self.path) # ---------------------------------------- Shotstack requests @@ -154,7 +156,12 @@ def post_json(url, body): # A server error can come after the job was created, so it isn't sent again either. if response.status_code >= 500: raise Unresolved(f"HTTP {response.status_code}") - return check(response) + try: + return check(response) + except ApiError: + if response.ok: # accepted, but the reply can't be read + raise Unresolved("the reply wasn't a JSON object") from None + raise def get_json(url): @@ -333,7 +340,7 @@ def sentences(cues): if start is None: start = cue.start parts.append(cue.text.strip()) - if cue.text.rstrip().endswith((".", "?", "!")): + if cue.text.rstrip().rstrip("\"'”’)").endswith((".", "?", "!", "…")): result.append(Cue(start, cue.end, " ".join(parts))) parts, start = [], None if parts: @@ -364,47 +371,55 @@ def find(target, stream, after=0): yield stream[k][1], stream[k + len(target) - 1][1] +class AiError(Exception): + """The AI provider couldn't be reached, or answered with an error.""" + + def ask_ai(messages): """One request to the AI model through the OpenAI-compatible chat API, which OpenAI, Anthropic, Google Gemini and many other providers offer. Returns the - text of the reply.""" + text of the reply. Network errors, rate limits and server errors are tried + again, because a request to the model can't start a render.""" url = f"{AI_BASE_URL}/chat/completions" - try: - response = requests.post( - url, - headers={"Authorization": f"Bearer {AI_API_KEY}"}, - json={"model": AI_MODEL, "messages": messages}, - timeout=AI_TIMEOUT, - ) - except requests.RequestException as error: - fail( - f"could not reach {url} ({type(error).__name__}). " - "Check AI_BASE_URL and your network." - ) + for attempt in range(1, 4): + try: + response = requests.post( + url, + headers={"Authorization": f"Bearer {AI_API_KEY}"}, + json={"model": AI_MODEL, "messages": messages}, + timeout=AI_TIMEOUT, + ) + except requests.RequestException as error: + problem = f"could not reach {url} ({type(error).__name__})" + else: + if response.status_code != 429 and response.status_code < 500: + break + problem = f"the AI provider answered {response.status_code}" + time.sleep(10 * attempt) + else: + raise AiError(f"{problem}. Check AI_BASE_URL and your network, and try again.") try: body = response.json() except ValueError: body = None if response.status_code in (401, 403): - fail( + raise AiError( f"the AI provider refused AI_API_KEY ({response.status_code} " f"{error_detail(body)})." ) if response.status_code >= 400: reason = error_detail(body) or response.reason - check = ( - " Check AI_BASE_URL and AI_MODEL." - if response.status_code in (400, 404) - else "" + raise AiError( + f"the AI provider answered {response.status_code} ({reason}). " + "Check AI_BASE_URL and AI_MODEL." ) - fail(f"the AI provider answered {response.status_code} ({reason}).{check}") try: choice = body["choices"][0] text = choice["message"]["content"] except (TypeError, KeyError, IndexError): - fail(f"{url} didn't send a chat reply. Check AI_BASE_URL.") + raise AiError(f"{url} didn't send a chat reply. Check AI_BASE_URL.") from None if choice.get("finish_reason") == "length": - fail("the AI model's reply was cut off. Try another AI_MODEL.") + raise AiError("the AI model's reply was cut off. Try another AI_MODEL.") return text or "" @@ -505,7 +520,11 @@ def pick_moments(lines, duration): "with these fixed, as JSON only.", }, ] - retried = check_reply(ask_ai(messages), lines, duration) + try: + retried = check_reply(ask_ai(messages), lines, duration) + except AiError as error: + print(f"The second request failed, so the first answer is kept ({error})") + retried = [], problems if len(retried[0]) > len(moments): # keep the first answer if it was better moments, problems = retried return moments, problems @@ -544,21 +563,14 @@ def read_moments(path, duration): def get_moments(lines, manifest, folder, repick): - """Reuse moments.json while nothing that shapes the pick has changed; - otherwise pick again. + """Use moments.json if it exists, and ask the AI model for moments if it doesn't + or if `repick` is set. moments.json is the contract between the picker and the renders: a list of {"start", "end", "title"} with times in seconds. Edit it by hand, or write it with a different picker, and the renders use it as it is.""" path = folder / "moments.json" - picked_with = hashlib.sha256( - json.dumps([transcript_text(lines), AI_BASE_URL, AI_MODEL, PROMPT]).encode() - ).hexdigest()[:16] - if ( - path.exists() - and not repick - and manifest.get("picked_with") in (None, picked_with) - ): + if path.exists() and not repick: print(f"Using the moments in {path}") return read_moments(path, manifest["duration"]) @@ -568,7 +580,10 @@ def get_moments(lines, manifest, folder, repick): "moments. The README gives the values for common providers." ) print(f"Asking {AI_MODEL} for {CLIP_COUNT} moments from {len(lines)} sentences") - moments, problems = pick_moments(lines, manifest["duration"]) + try: + moments, problems = pick_moments(lines, manifest["duration"]) + except AiError as error: + fail(str(error)) for problem in problems: print(f" left out: {problem}") if not moments: @@ -577,8 +592,6 @@ def get_moments(lines, manifest, folder, repick): f"or write {path} by hand." ) path.write_text(json.dumps(moments, indent=2)) - manifest["picked_with"] = picked_with - manifest.save() for n, moment in enumerate(moments, 1): span = f"{clock(moment['start'])} to {clock(moment['end'])}" print(f" {n}. {moment['title']} ({span})") @@ -722,7 +735,7 @@ def finished(render, label): return render["status"] == "done" -def advance(job, moment, source_url, cues, path, label): +def advance(job, moment, manifest, cues, path, label): """Take one clip a step further: upload its captions and render it, then download it.""" if "render" not in job: @@ -731,7 +744,13 @@ def advance(job, moment, source_url, cues, path, label): if not srt: fail(f"{label} has no words in the transcript. Edit moments.json.") job["captions"] = upload_text(srt) - job["render"] = submit(clip_edit(source_url, moment, job["captions"]), label) + # Saved before the request is sent. If the run stops during the request, + # the next run can't tell whether the render started, so it won't resend it. + job["submitting"] = True + manifest.save() + edit = clip_edit(manifest["source_url"], moment, job["captions"]) + job["render"] = submit(edit, label) + del job["submitting"] return if not finished(job["render"], label): return @@ -768,7 +787,13 @@ def render_clips(moments, cues, manifest, folder): jobs = manifest.setdefault("renders", {}) todo = [] for n, moment in enumerate(moments, 1): - job = jobs.setdefault(f"{moment['start']:.3f}-{moment['end']:.3f}", {}) + # The title is part of the key, so a clip whose title changes is made again + key = f"{moment['start']:.3f}-{moment['end']:.3f} {moment['title']}" + job = jobs.setdefault(key, {}) + if job.pop("submitting", None): + job["unresolved"] = "the last run stopped while it was sending the request" + if "file" in job and not Path(job["file"]).exists(): + del job["file"] # deleted since, so it's downloaded again if clip_state(job) == "failed": # a new run tries failed clips again job.pop("error", None) if job.get("render", {}).get("status") == "failed": @@ -784,12 +809,14 @@ def render_clips(moments, cues, manifest, folder): if clip_state(job) != "working": continue try: - advance(job, moment, manifest["source_url"], cues, path, f"clip {n}") + advance(job, moment, manifest, cues, path, f"clip {n}") except Unresolved as error: # Don't resubmit: the render may have started, and a retry could # duplicate it. + job.pop("submitting", None) job["unresolved"] = f"the submit request didn't complete ({error})" except (ApiError, requests.RequestException) as error: + job.pop("submitting", None) # refused, so no render started job["error"] = str(error) manifest.save() if all(clip_state(job) != "working" for _, _, job, _ in todo): diff --git a/examples/video-clipping-pipeline/test_clips.py b/examples/video-clipping-pipeline/test_clips.py index 5540dc0..c0a26a3 100644 --- a/examples/video-clipping-pipeline/test_clips.py +++ b/examples/video-clipping-pipeline/test_clips.py @@ -93,12 +93,30 @@ def download(self, url, path): self.downloads.append(url) Path(path).write_bytes(b"video") - def run_clips(self): + def run_clips(self, moment=MOMENT): """One run of the render step, from the manifest on disk. Returns the job.""" manifest = clips.Manifest(self.folder / "manifest.json", RECORDING) - todo = quietly(clips.render_clips, [MOMENT], CUES, manifest, self.folder) + todo = quietly(clips.render_clips, [moment], CUES, manifest, self.folder) return todo[0][2] + def test_a_run_stopped_during_the_submit_does_not_send_it_again(self): + self.edit.post_errors = [KeyboardInterrupt()] + with self.assertRaises(KeyboardInterrupt): + self.run_clips() + self.assertEqual(clips.clip_state(self.run_clips()), "unresolved") + self.assertEqual(self.edit.submits, []) + + def test_a_new_title_makes_the_clip_again(self): + self.run_clips() + self.run_clips(dict(MOMENT, title="A better title")) + self.assertEqual(len(self.edit.submits), 2) + + def test_a_deleted_clip_file_is_downloaded_again(self): + Path(self.run_clips()["file"]).unlink() + self.assertEqual(clips.clip_state(self.run_clips()), "done") + self.assertEqual(len(self.edit.submits), 1) + self.assertEqual(len(self.downloads), 2) + def test_a_clip_takes_one_upload_one_render_and_one_download(self): job = self.run_clips() self.assertEqual(clips.clip_state(job), "done") @@ -201,34 +219,70 @@ def test_a_moment_without_a_title_is_refused(self): self.assertIsNone(clips.read_reply(reply)) +def chat_response(status_code, body): + response = requests.Response() + response.status_code = status_code + response._content = json.dumps(body).encode() + return response + + +def chat_reply(text): + return chat_response( + 200, {"choices": [{"message": {"content": text}, "finish_reason": "stop"}]} + ) + + class AskAi(unittest.TestCase): - def ask(self, status_code, body): - response = requests.Response() - response.status_code = status_code - response._content = json.dumps(body).encode() - with mock.patch.object(clips.requests, "post", return_value=response) as post: + def setUp(self): + sleep = mock.patch.object(clips.time, "sleep") + sleep.start() + self.addCleanup(sleep.stop) + + def ask(self, *responses): + """Ask once, with the AI provider sending these responses in turn. Returns + the reply text, or the AiError message, and the mocked post.""" + with mock.patch.object(clips.requests, "post", side_effect=responses) as post: try: - return quietly(clips.ask_ai, [{"role": "user", "content": "hi"}]), post - except SystemExit as stop: - return str(stop), post + return clips.ask_ai([{"role": "user", "content": "hi"}]), post + except clips.AiError as error: + return str(error), post def test_the_reply_text_is_returned(self): - body = {"choices": [{"message": {"content": "{}"}, "finish_reason": "stop"}]} - text, post = self.ask(200, body) + text, post = self.ask(chat_reply("{}")) self.assertEqual(text, "{}") self.assertTrue(post.call_args.args[0].endswith("/chat/completions")) - def test_a_refused_key_stops_with_one_line(self): - message, _ = self.ask(401, {"error": {"message": "Incorrect API key"}}) + def test_a_rate_limit_is_tried_again(self): + limited = chat_response(429, {"error": {"message": "Rate limit"}}) + text, post = self.ask(limited, chat_reply("{}")) + self.assertEqual(text, "{}") + self.assertEqual(post.call_count, 2) + + def test_a_refused_key_names_the_setting(self): + message, _ = self.ask( + chat_response(401, {"error": {"message": "Incorrect API key"}}) + ) self.assertIn("refused AI_API_KEY", message) self.assertIn("Incorrect API key", message) - def test_a_reply_that_was_cut_off_stops(self): + def test_a_reply_that_was_cut_off_is_an_error(self): body = {"choices": [{"message": {"content": "{"}, "finish_reason": "length"}]} - message, _ = self.ask(200, body) + message, _ = self.ask(chat_response(200, body)) self.assertIn("cut off", message) +class PickMoments(unittest.TestCase): + LINES = [clips.Cue(0, 10, "One two three four."), clips.Cue(10, 30, "Five six.")] + PICK = {"first_words": "one two", "last_words": "five six", "title": "T"} + + def test_a_failed_second_request_keeps_the_first_answer(self): + first = json.dumps({"moments": [self.PICK]}) + error = clips.AiError("the AI provider answered 503") + with mock.patch.object(clips, "ask_ai", side_effect=[first, error]): + moments, _ = quietly(clips.pick_moments, self.LINES, 100) + self.assertEqual(moments, [{"start": 0, "end": 30, "title": "T"}]) + + class CheckPicks(unittest.TestCase): """How the AI model's quotes become start and end times.""" @@ -309,6 +363,10 @@ def test_a_reply_with_no_render_id_is_not_sent_again(self): with self.assertRaises(clips.Unresolved): quietly(clips.submit, {}, "clip 1") + def test_an_accepted_request_with_an_unreadable_reply_is_not_sent_again(self): + with self.assertRaises(clips.Unresolved): + self.post(201, b"gateway") + if __name__ == "__main__": unittest.main() From 546d7cdcc7b01a3d6dee87b9dcb89f8c6a780843 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 07:12:53 +0500 Subject: [PATCH 09/12] Exit with code 1 when a clip is not done --- examples/video-clipping-pipeline/clips.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py index 256616f..9335c01 100644 --- a/examples/video-clipping-pipeline/clips.py +++ b/examples/video-clipping-pipeline/clips.py @@ -903,6 +903,8 @@ def main(): except ApiError as error: fail(str(error)) report(todo) + if any(clip_state(job) != "done" for _, _, job, _ in todo): + sys.exit(1) # so a script or a scheduler can tell that a clip is missing if __name__ == "__main__": From cb2a4638d124c58b9df8ea160c46904585c05f98 Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 07:14:48 +0500 Subject: [PATCH 10/12] Format the video clipping README with prettier --- examples/video-clipping-pipeline/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/video-clipping-pipeline/README.md b/examples/video-clipping-pipeline/README.md index ab2be28..c4a2c33 100644 --- a/examples/video-clipping-pipeline/README.md +++ b/examples/video-clipping-pipeline/README.md @@ -34,11 +34,11 @@ cp .env.example .env Set `SHOTSTACK_API_KEY` in `.env`. Then set `AI_BASE_URL`, `AI_API_KEY` and `AI_MODEL` for your AI provider: -| Provider | `AI_BASE_URL` | `AI_MODEL`, for example | API key | -| ------------- | --------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------- | -| OpenAI | `https://api.openai.com/v1` | `gpt-5.4-mini` | [platform.openai.com](https://platform.openai.com/api-keys) | -| Anthropic | `https://api.anthropic.com/v1` | `claude-sonnet-5-5` | [platform.claude.com](https://platform.claude.com/settings/keys) | -| Google Gemini | `https://generativelanguage.googleapis.com/v1beta/openai` | `gemini-3.5-flash` | [aistudio.google.com](https://aistudio.google.com/apikey) | +| Provider | `AI_BASE_URL` | `AI_MODEL`, for example | API key | +| ------------- | --------------------------------------------------------- | ----------------------- | ---------------------------------------------------------------- | +| OpenAI | `https://api.openai.com/v1` | `gpt-5.4-mini` | [platform.openai.com](https://platform.openai.com/api-keys) | +| Anthropic | `https://api.anthropic.com/v1` | `claude-sonnet-5-5` | [platform.claude.com](https://platform.claude.com/settings/keys) | +| Google Gemini | `https://generativelanguage.googleapis.com/v1beta/openai` | `gemini-3.5-flash` | [aistudio.google.com](https://aistudio.google.com/apikey) | Load the file. Do this in each new terminal, and each time you change `.env`: From 6017446efb23d0c94670945ac1c5f08a690ed7cf Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 07:49:29 +0500 Subject: [PATCH 11/12] Build the transcript path once in the video clipping example --- examples/video-clipping-pipeline/clips.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py index 9335c01..1fac402 100644 --- a/examples/video-clipping-pipeline/clips.py +++ b/examples/video-clipping-pipeline/clips.py @@ -271,13 +271,11 @@ def import_recording(url, manifest, folder): ) srt = requests.get(transcript["url"], timeout=60) srt.raise_for_status() - (folder / "transcript.srt").write_text( - srt.content.decode("utf-8"), encoding="utf-8" - ) + path = folder / "transcript.srt" + path.write_text(srt.content.decode("utf-8"), encoding="utf-8") manifest.update(source_url=source["source"], duration=source["duration"]) manifest.save() - saved = folder / "transcript.srt" - print(f"Imported {clock(source['duration'])} of video and saved {saved}") + print(f"Imported {clock(source['duration'])} of video and saved {path}") Cue = namedtuple("Cue", "start end text") From bc0ca5888cea1f962cf6a3dd91a1f7c923419b3e Mon Sep 17 00:00:00 2001 From: Musab Date: Tue, 17 Nov 2026 08:28:19 +0500 Subject: [PATCH 12/12] Apply ponytail review to the video clipping example --- examples/video-clipping-pipeline/clips.py | 27 +++++++------------ .../video-clipping-pipeline/test_clips.py | 9 +++---- 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/examples/video-clipping-pipeline/clips.py b/examples/video-clipping-pipeline/clips.py index 1fac402..df04208 100644 --- a/examples/video-clipping-pipeline/clips.py +++ b/examples/video-clipping-pipeline/clips.py @@ -98,7 +98,7 @@ def save(self): class ApiError(Exception): - """Shotstack answered with an error.""" + """Shotstack or the AI provider answered with an error.""" class Unresolved(Exception): @@ -369,10 +369,6 @@ def find(target, stream, after=0): yield stream[k][1], stream[k + len(target) - 1][1] -class AiError(Exception): - """The AI provider couldn't be reached, or answered with an error.""" - - def ask_ai(messages): """One request to the AI model through the OpenAI-compatible chat API, which OpenAI, Anthropic, Google Gemini and many other providers offer. Returns the @@ -395,19 +391,19 @@ def ask_ai(messages): problem = f"the AI provider answered {response.status_code}" time.sleep(10 * attempt) else: - raise AiError(f"{problem}. Check AI_BASE_URL and your network, and try again.") + raise ApiError(f"{problem}. Check AI_BASE_URL and your network, and try again.") try: body = response.json() except ValueError: body = None if response.status_code in (401, 403): - raise AiError( + raise ApiError( f"the AI provider refused AI_API_KEY ({response.status_code} " f"{error_detail(body)})." ) if response.status_code >= 400: reason = error_detail(body) or response.reason - raise AiError( + raise ApiError( f"the AI provider answered {response.status_code} ({reason}). " "Check AI_BASE_URL and AI_MODEL." ) @@ -415,9 +411,9 @@ def ask_ai(messages): choice = body["choices"][0] text = choice["message"]["content"] except (TypeError, KeyError, IndexError): - raise AiError(f"{url} didn't send a chat reply. Check AI_BASE_URL.") from None + raise ApiError(f"{url} didn't send a chat reply. Check AI_BASE_URL.") from None if choice.get("finish_reason") == "length": - raise AiError("the AI model's reply was cut off. Try another AI_MODEL.") + raise ApiError("the AI model's reply was cut off. Try another AI_MODEL.") return text or "" @@ -520,7 +516,7 @@ def pick_moments(lines, duration): ] try: retried = check_reply(ask_ai(messages), lines, duration) - except AiError as error: + except ApiError as error: print(f"The second request failed, so the first answer is kept ({error})") retried = [], problems if len(retried[0]) > len(moments): # keep the first answer if it was better @@ -578,10 +574,7 @@ def get_moments(lines, manifest, folder, repick): "moments. The README gives the values for common providers." ) print(f"Asking {AI_MODEL} for {CLIP_COUNT} moments from {len(lines)} sentences") - try: - moments, problems = pick_moments(lines, manifest["duration"]) - except AiError as error: - fail(str(error)) + moments, problems = pick_moments(lines, manifest["duration"]) for problem in problems: print(f" left out: {problem}") if not moments: @@ -748,7 +741,6 @@ def advance(job, moment, manifest, cues, path, label): manifest.save() edit = clip_edit(manifest["source_url"], moment, job["captions"]) job["render"] = submit(edit, label) - del job["submitting"] return if not finished(job["render"], label): return @@ -811,11 +803,10 @@ def render_clips(moments, cues, manifest, folder): except Unresolved as error: # Don't resubmit: the render may have started, and a retry could # duplicate it. - job.pop("submitting", None) job["unresolved"] = f"the submit request didn't complete ({error})" except (ApiError, requests.RequestException) as error: - job.pop("submitting", None) # refused, so no render started job["error"] = str(error) + job.pop("submitting", None) # sent, refused or not reached manifest.save() if all(clip_state(job) != "working" for _, _, job, _ in todo): return todo diff --git a/examples/video-clipping-pipeline/test_clips.py b/examples/video-clipping-pipeline/test_clips.py index c0a26a3..f8c6669 100644 --- a/examples/video-clipping-pipeline/test_clips.py +++ b/examples/video-clipping-pipeline/test_clips.py @@ -123,9 +123,6 @@ def test_a_clip_takes_one_upload_one_render_and_one_download(self): self.assertEqual(len(self.uploads), 1) self.assertEqual(len(self.edit.submits), 1) self.assertEqual(len(self.downloads), 1) - - def test_the_render_uses_the_uploaded_captions(self): - self.run_clips() tracks = self.edit.submits[0]["timeline"]["tracks"] captions = tracks[1]["clips"][0]["asset"] self.assertEqual(captions["type"], "rich-caption") @@ -240,11 +237,11 @@ def setUp(self): def ask(self, *responses): """Ask once, with the AI provider sending these responses in turn. Returns - the reply text, or the AiError message, and the mocked post.""" + the reply text, or the ApiError message, and the mocked post.""" with mock.patch.object(clips.requests, "post", side_effect=responses) as post: try: return clips.ask_ai([{"role": "user", "content": "hi"}]), post - except clips.AiError as error: + except clips.ApiError as error: return str(error), post def test_the_reply_text_is_returned(self): @@ -277,7 +274,7 @@ class PickMoments(unittest.TestCase): def test_a_failed_second_request_keeps_the_first_answer(self): first = json.dumps({"moments": [self.PICK]}) - error = clips.AiError("the AI provider answered 503") + error = clips.ApiError("the AI provider answered 503") with mock.patch.object(clips, "ask_ai", side_effect=[first, error]): moments, _ = quietly(clips.pick_moments, self.LINES, 100) self.assertEqual(moments, [{"start": 0, "end": 30, "title": "T"}])