Learn · Developers

Build a video clipping pipeline with the Shotstack API

Contents

If you have long recordings coming in, like talks, interviews, podcasts or stream recordings, sooner or later someone asks for short clips of the best parts. This guide is for developers building that into their own product or pipeline, whether it’s an AI clipping feature, a content workflow or a clipping API of your own. It isn’t a finished clipping tool. It shows how the pieces fit together, with code you can take apart and reuse.

By the end, you’ll have clips.py, a Python script that takes the URL of a long recording and produces five short, vertical clips with captions. Shotstack’s APIs handle the video work: they transcribe the recording, cut each clip, reframe it for a vertical screen and add the captions, so there are no FFmpeg jobs or GPU servers for you to run. The one part you supply is the moment picker, which decides what’s worth clipping. This guide uses an AI model through the OpenAI-compatible chat API, which OpenAI, Anthropic, Google Gemini and many other providers offer, so it works with whichever provider you have a key for. Your own model, a set of rules or a person could take its place.

TL;DR

  • To automatically clip long videos, import each recording with Shotstack’s Ingest API to get a transcript.
  • Let a picker you own choose the moments. Any AI model with an OpenAI-compatible API can do it.
  • Render each moment once: cut it out, fit it into a vertical frame, and add captions made from the transcript you already have.
  • This guide builds that pipeline as one Python script and runs it on a 51-minute conference talk.

We ran it on a talk from FOSDEM 2025. Here’s one of the five clips it made:

Source footage: “Beyond the README: Crafting a Better Developer Experience for Open Source Projects” by Lorna Mitchell, FOSDEM 2025. Licensed CC BY 2.0 BE.

For a wider look at what you can automate with video, see How to automate video editing.

How the pipeline fits together

Pipeline diagram: transcribe with the Ingest API, pick the moments, then upload a caption file and render each clip in one Edit API request.

The pipeline has three kinds of parts:

  • Shotstack API calls. The Ingest API imports the recording, transcribes it and hosts each clip’s caption file. The Edit API renders the clips. Webhooks tell your app when a render is done.
  • Your own logic. The moment picker reads the transcript and decides where the clips are.
  • Glue. A loop that submits renders and keeps track of them, and a manifest file that remembers what’s been done, so a run can stop and pick up again later.

The picker’s output is the contract between your logic and everything else: a list of moments, each with a start time, an end time and a title. Everything before that list is your component. After it, your code turns each moment into a render request and tracks the jobs, and Shotstack does the cutting, reframing and captioning. Because the handoff is just a list, you can start with a general-purpose model from any provider and later swap in one trained on your own data, editorial rules or a person reviewing the picks, and nothing downstream has to change.

For each recording, that adds up to one import request, which also produces the transcript, and a request to the model (two, if it has to fix its answer). Each clip then takes a small upload and one render request. The render cuts the moment out of the recording, fits it into a vertical frame, and adds a title and captions. The captions come from the transcript the import already made, so nothing is transcribed twice.

In a real product, the picker would be a function or a service you can replace, and the render step is stateless, so it can run anywhere. Webhooks are how your app learns that a clip is ready. The script in this guide polls instead, because it has no server to receive webhooks.

One limit to know up front: a picker that reads a transcript can only find moments where someone is talking. A great moment that happens in silence won’t be in the transcript.

Before you start

You’ll need:

  • Python 3.8 or later.
  • A Shotstack account and API key. The script uses the production API, and production renders use credits, so check Shotstack’s pricing. You can also run it against the sandbox, where renders are watermarked, by setting SHOTSTACK_ENV=stage and using your sandbox key.
  • An API key from an AI provider with an OpenAI-compatible chat API, for the picker. OpenAI, Anthropic and Google Gemini all have one.
  • A recording at a URL that returns the video file itself.

That last point matters because Shotstack fetches the file from its own servers. The URL has to be public, or a presigned URL that stays valid long enough for the download, and it has to return the video itself, not a web page or a list of download mirrors. The demo talk’s link on video.fosdem.org goes through a download redirector, and when Shotstack fetched it, it got back a 4.9 KB list of mirrors instead of the video. So the demo points straight at the file on one of FOSDEM’s mirrors.

Set up a project, install requests, the one package the script needs, and set your keys. The three AI_ variables tell the script where your AI provider’s API is, your key for it and which model to use:

Bash
mkdir clipping-pipeline && cd clipping-pipeline
python3 -m venv venv
source venv/bin/activate
python -m pip install requests
export SHOTSTACK_API_KEY=your-shotstack-key
export AI_BASE_URL=https://api.openai.com/v1
export AI_API_KEY=your-ai-provider-key
export AI_MODEL=gpt-5.4-mini

That example is for OpenAI. For another provider, change AI_BASE_URL and AI_MODEL:

ProviderAI_BASE_URLAI_MODEL, for example
OpenAIhttps://api.openai.com/v1gpt-5.4-mini
Anthropichttps://api.anthropic.com/v1claude-sonnet-5-5
Google Geminihttps://generativelanguage.googleapis.com/v1beta/openaigemini-3.5-flash

Create clips.py and start it with the imports and settings. The script talks to Shotstack and to the AI provider with plain HTTP requests, so every request body in this guide is exactly the JSON the API receives.

Python
import argparse
import json
import os
import re
import sys
import time
from collections import namedtuple
from pathlib import Path
from urllib.parse import urlparse

import requests

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",
}
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
UPLOAD_TIMEOUT = 2 * 60  # and for a caption file to be ready
AI_TIMEOUT = 5 * 60  # one request to the AI model

Next come a few small helpers, mostly for talking to Shotstack:

Python
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 ApiError(Exception):
    """Shotstack or the AI provider answered with an error."""


class Unresolved(Exception):
    """A submit request that may or may not have reached Shotstack."""


def error_detail(body):
    """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:
            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"{error_detail(body)}). SHOTSTACK_API_KEY must be your {kind} key."
        )
    if response.status_code >= 400:
        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):
    """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(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}")
    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):
    """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)

post_json sends a request once and never retries it. A submit request that times out may still have started a render, and sending it again could start a second one. A server error gets the same treatment, because it can come after the job was created. get_json only checks a status, which is safe to repeat, so it retries network errors, rate limits and server errors. download fetches finished files without the API key, because Shotstack serves them from plain file URLs. error_detail finds the reason in an error reply, which Shotstack’s Ingest API, its Edit API and the AI providers each put in a different place.

Step 1: Import the recording and get a transcript

The Ingest API fetches the recording, stores a copy and, if you ask, transcribes it. One request to POST https://api.shotstack.io/ingest/v1/sources does both, with a body like this:

JSON
{
  "url": "https://ftp.fau.de/fosdem/2025/k1105/fosdem-2025-5235-beyond-the-readme-crafting-a-better-developer-experience-for-open-source-projects.mp4",
  "outputs": { "transcription": { "format": "srt" } }
}

The response contains a source ID. Poll GET https://api.shotstack.io/ingest/v1/sources/{id} and watch two statuses: the file’s own status, and the transcript’s, at data.attributes.outputs.transcription.status. The file can be ready before the transcript is, so wait until both say ready, and stop if either says failed.

Once they’re ready, the response has three things to keep:

  • data.attributes.source is Shotstack’s hosted copy of the recording. The renders use it instead of your original URL, so Shotstack only downloads the file from your URL once.
  • data.attributes.duration is the length in seconds. Check that it’s there before you render, so the script stops early if the URL didn’t point to a video.
  • data.attributes.outputs.transcription.url is the SRT file.

Before the import itself, the script needs somewhere to save progress. The manifest is a dictionary that writes itself to manifest.json whenever you call save():

Python
class Manifest(dict):
    """What's been done for one recording, saved to manifest.json after every change."""

    def __init__(self, path, 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:
            # 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."
                )

    def save(self):
        # 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)

Saving the source ID as soon as the import request returns means that if the script stops while Shotstack is still transcribing, the next run waits for the same import instead of starting a new one. Each folder belongs to one URL. If you change the URL before anything was done for the old one, for example after a failed import, the script carries on with the new URL. Otherwise it stops, so two recordings never share a manifest. Here’s the import:

Python
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"}}}
        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"
        ]
        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]}, "
                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"
                )
            fail(f"the import failed ({reason}).")
        if status == ("ready", "ready"):
            break
        if time.time() - started > IMPORT_TIMEOUT:
            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."
        )
    srt = requests.get(transcript["url"], timeout=60)
    srt.raise_for_status()
    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()
    print(f"Imported {clock(source['duration'])} of video and saved {path}")

For the 51-minute, 1.2 GB demo recording, the file and its transcript were ready in about four minutes:

Text
Importing the recording (source zzz01m3r-6atjt-v152e-b92gb-01fym1)
  0:01  file: queued, transcript: queued
  0:12  file: importing, transcript: waiting
  4:10  file: ready, transcript: ready
Imported 51:36 of video and saved clips/fosdem-2025-5235-beyond-the-readme-craft/transcript.srt

The SRT file is plain text. This reads it into a list of cues, with times in seconds:

Python
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

The script keeps these cues for later too: each clip’s captions are the cues inside its moment.

For more on getting transcripts from Shotstack and working with SRT files, see the video summarizer guide.

Step 2: Pick the moments with an LLM

This step is your component. Its only job is to turn the transcript into the contract, a list like this one, which the script saves as moments.json:

JSON
[
  {
    "start": 955.55,
    "end": 990.92,
    "title": "The help output that gatekeeps users"
  }
]

This version sends the transcript to an AI model and asks it for the five best moments. Changing provider only means changing AI_BASE_URL, AI_API_KEY and AI_MODEL.

Give the model whole sentences

Shotstack’s SRT splits speech into short subtitle lines: 1,369 of them for this talk, most under two seconds long. Cutting clips at those boundaries would start and end them mid-sentence, so the script first joins the lines into whole sentences:

Python
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().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

Then it formats the transcript for the prompt, one sentence per line, each with its start time:

Python
def transcript_text(lines):
    """The transcript for the prompt: one sentence per line, with its start time."""
    return "\n".join(f"[{clock(line.start)}] {line.text}" for line in lines)

The talk becomes 523 lines like these, about 44,000 characters in all:

Text
[15:55] I recently tried to patch the help file for a, I'm not gonna name the tool because it isn't there, for a CLI project.
[16:03] So they're a dash dash help output.
[16:05] I didn't find it very helpful, and I sent them a patch.

Ask for quotes, not numbers

Here’s the prompt:

Python
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.

Reply with JSON only, in this form:
{{"moments": [{{"first_words": "...", "last_words": "...", "title": "..."}}]}}"""

It asks the model to point at each moment by copying its first and last words, rather than giving times or line numbers. An earlier version of this script numbered the lines and asked for line numbers, and the model seems to have mixed them up with the times printed next to them: four of its five moments pointed at the wrong part of the talk. Copying text is something language models do reliably, and finding copied text is easy in code.

Call any provider through one API

Most AI providers offer an OpenAI-compatible chat API. You send a list of messages to {AI_BASE_URL}/chat/completions with your key, and the text of the reply is at choices[0].message.content. The same request works for OpenAI, Anthropic and Google Gemini, so the script makes it with requests and needs no provider’s SDK:

Python
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. 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"
    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 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 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 ApiError(
            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):
        raise ApiError(f"{url} didn't send a chat reply. Check AI_BASE_URL.") from None
    if choice.get("finish_reason") == "length":
        raise ApiError("the AI model's reply was cut off. Try another AI_MODEL.")
    return text or ""

A few things to know about that request:

  • It sends only the model and the messages. Settings like temperature or a token limit differ between providers, and some models reject them, so the script leaves each provider’s defaults alone.
  • Network errors, rate limits and server errors are tried again, up to three times. A request to the model can’t start a render, so trying again is safe.
  • A refused key, an unknown model or an address that isn’t a chat API stops the script with one line that names the setting to check.
  • If the reply was cut off, with a finish_reason of length, its JSON is incomplete, so the script stops instead of guessing.

Support for structured outputs differs from provider to provider, so the prompt asks for JSON and the script checks what comes back. Some models put the JSON in a code block, so read_reply reads from the first { to the last }:

Python
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

A reply that isn’t that JSON, or a moment without all three fields, counts as a failed answer.

Check every moment in code

The prompt states the rules, but the code enforces them. find looks for a quote in the transcript, ignoring case and punctuation:

Python
def words(text):
    """Lowercase words without punctuation, so a quote matches however it's
    punctuated."""
    return re.findall(r"[^\W_]+", text.lower().replace("'", "").replace("’", ""))


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
        ):
            yield stream[k][1], stream[k + len(target) - 1][1]

check_picks turns each pair of quotes into start and end times, then checks the rest of the rules: each moment has to last 15 to 60 seconds, fit inside the recording and stay clear of the others. A phrase like “So the next thing is” can come up more than once in a talk, so it pairs every place the first words occur with the next place the last words occur, and keeps the shortest span.

Python
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"]}")'
        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
        # 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
        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, "
                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

If fewer than five moments pass, the script sends the problems back to the model once and asks for a corrected list. It keeps whichever answer had more moments pass, and if the second request fails, it keeps the first answer. If that still falls short, it keeps the moments that passed and says how many it found. It never makes up replacements.

Python
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 the AI model to fix these:"
            + "".join(f"\n  - {p}" for p in problems)
        )
        messages += [
            {"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, as JSON only.",
            },
        ]
        try:
            retried = check_reply(ask_ai(messages), lines, duration)
        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
            moments, problems = retried
    return moments, problems

In our run with claude-sonnet-5-5, all five moments passed the checks on the first try:

Text
Asking claude-sonnet-5-5 for 5 moments from 523 sentences
  1. Limit nitpicks: three max in a PR review (34:52 to 35:37)
  2. Opening the diff is the wrong way to review (32:43 to 33:32)
  3. Close issues you don't want, tag the ones you do (28:03 to 28:42)
  4. The CLI help patch that got rejected (15:55 to 16:30)
  5. Even patchy docs improve developer experience (11:50 to 12:20)

When a moment fails a check, the script prints the problem before it asks again, like this one from a test run: moment 5 ("Define 'done' in your contributing file"): lasts 81.5 seconds, not 15 to 60.

Save the moments, and let people edit them

Each pick costs a model call, so the script saves the moments to moments.json and reuses them on the next run:

Python
def read_moments(path, duration):
    """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)
    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 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


def get_moments(lines, manifest, folder, repick):
    """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"
    if path.exists() and not repick:
        print(f"Using the moments in {path}")
        return read_moments(path, 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."
        )
    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 again, "
            f"or write {path} by hand."
        )
    path.write_text(json.dumps(moments, indent=2))
    for n, moment in enumerate(moments, 1):
        span = f"{clock(moment['start'])} to {clock(moment['end'])}"
        print(f"  {n}. {moment['title']} ({span})")
    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

Once moments.json exists, the script uses it as it is, including a file you edited or wrote yourself, as long as the moments fit the recording and don’t overlap. To pick again, for example after you change the model or the prompt, add --repick. A new pick overwrites moments.json, hand edits included, so keep a copy of any edits you want to reuse.

That’s the contract doing its job. In an earlier run, a pick started just after the story it was about, so we moved it back to cover the story itself, 15:55 to 16:30, by editing moments.json. The renders used the edited file without asking the model again.

You don’t need a model to fill this file at all. A picker could apply rules to the transcript, like a list of keywords, or a person could choose the moments in a review screen. As long as it writes the same list, nothing after it changes.

Step 3: Caption, cut and reframe one clip

Each clip takes one render request to the Edit API, sent to POST https://api.shotstack.io/edit/v1/render, and a small upload before it.

Captions from the transcript you already have

The import already transcribed the whole talk, so the captions come from that transcript instead of transcribing each clip again. clip_srt takes the transcript lines inside a moment and moves their times back, so that the first line starts at zero, the start of the clip:

Python
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)
    )

The rich-caption asset can read its words from the URL of an SRT file. So the script uploads each clip’s file with the Ingest API and uses the URL Shotstack hosts it at:

Python
def upload_text(text):
    """Upload a small text file with the Ingest API and return its URL. An upload
    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:
        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"
    )

POST https://api.shotstack.io/ingest/v1/upload returns a signed URL, and a PUT to that URL sends the file. The signed URL has no file name, so the Content-Type header tells Shotstack what kind of file it is. Without it, the upload failed with “The file type could not be detected”. The file was ready a few seconds later. An upload can’t start a render, so unlike a render request, a failed one is safe to send again.

An SRT file only has a time for each line, not for each word, but the word being spoken is still highlighted as it’s said.

One render: cut, reframe, title and captions

Python
# 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"


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",
            "fonts": [{"src": ROBOTO_URL}],
            "tracks": [
                {
                    "clips": [
                        {
                            "asset": {
                                "type": "rich-text",
                                "text": moment["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": captions_url,
                                "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": [
                        {
                            "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}},
    }

Tracks are layered in order, with the first one on top.

The first track is the title. The rich-text clip sits in a 960x360 box at the top of the frame, lowered by 12% of the frame’s height, with the text centered in that box, just above the video. The title comes from the moment in moments.json, so a title you edit by hand shows up in the clip.

The second track is the captions. Their src is the clip’s uploaded SRT file, and "length": "end" keeps them going until the end of the timeline. They sit in a 960x400 box at the bottom of the frame, raised by 8% of the frame’s height (the offset) so that they land in the black band under the video. They’re set in bold Roboto at 64 pixels, and the word being spoken turns yellow. The fonts entry loads Roboto from Google Fonts, and both assets refer to it by the file’s name, ROBOTO. We checked the result on a phone, and the captions were readable at that size.

The last track is the video. Its src is Shotstack’s hosted copy from step 1, trim skips to the moment’s start, and length is how long to play. (The sports highlights guide covers trimming in more detail.) The output size is 1080x1920. When you set size, leave out resolution and aspectRatio.

"fit": "contain" fits the whole 16:9 frame inside the vertical one, with black bands above and below. Shotstack reframes by fitting, scaling, offsetting and cropping the frame. The default fit, crop, scales the video to fill the frame and cuts off the sides. For this recording, which shows the slides large with a small camera view of the speaker in the bottom-right corner, that would crop the speaker out. For a single-camera recording with the speaker in the middle of the frame, the default crop may be all you need. And unlike in CSS, "fit": "cover" stretches the image to fill the frame.

If you also want a clean vertical cut with no text, to reuse on other platforms or with another caption style, render the same timeline with only the video track.

Submit a render and wait for it

Python
def submit(edit, label):
    """Queue one render and return a record to track it by."""
    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()}


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"]:
            took = clock(time.time() - render["submitted"])
            print(f"  {label}: {info['status']} after {took}")
        render["status"] = info["status"]
        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"
    return render["status"] == "done"

A render reports several statuses on its way to done or failed. The script only acts on those two, and treats any other status as still in progress. A render that reports done without a URL counts as failed. In our final run, each render took about two minutes, from 1:39 to 2:11.

Step 4: Render all five clips

Five clips means five uploads and five render requests, each render tracked by its ID. advance takes one clip a step further each time it’s called: upload its captions and submit its render, wait for the render, then download the clip.

Python
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:
        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)
        # 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)
        return
    if not finished(job["render"], label):
        return
    try:
        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["render"]  # the file is gone, so the next run renders it again
            job["error"] = f"the rendered file is gone (HTTP {status})"
            return
        raise
    job["file"] = str(path)
    print(f"  {label}: saved {path}")

render_clips calls advance for every clip, over and over, until each one is done, has failed or is unresolved. All five renders go out on the first pass, and each clip is downloaded as soon as its own render finishes. The manifest is saved after every step. Each clip’s entry is named by its start, end and title, so a clip whose title you change in moments.json is made again, and a clip file you delete is downloaded again.

Python
def clip_state(job):
    if "file" in job:
        return "done"
    if "unresolved" in job:
        return "unresolved"
    if "error" in job or job.get("render", {}).get("status") == "failed":
        return "failed"
    return "working"


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 one render request, tracked by ID."""
    jobs = manifest.setdefault("renders", {})
    todo = []
    for n, moment in enumerate(moments, 1):
        # 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":
                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()

    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, cues, 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)
            job.pop("submitting", None)  # sent, refused or not reached
            manifest.save()
        if all(clip_state(job) != "working" for _, _, job, _ in todo):
            return todo
        if time.time() - started > RENDER_TIMEOUT:
            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)

Two kinds of failure need different handling:

  • A render that fails can safely be tried again, so the next run of the script resubmits it. So can a refused render request, an upload, or a download that failed.
  • A submit request that times out is different. The request may have reached Shotstack and started a render. Sending it again could create a duplicate, so the script marks the clip as unresolved and leaves it for you to check in the Shotstack dashboard. The same goes for a run that stops while a render request is being sent, which is why advance saves a note before it sends one: if nothing started, delete the clip’s entry under "renders" in manifest.json and run the script again. Checking a render’s status, on the other hand, is always safe to repeat.

In production, you’d replace the polling with webhooks: add a callback URL to each render request, and Shotstack calls it when the render finishes. Treat a callback as a signal, and fetch the render by its ID to confirm its status before acting on it. Shotstack also retries a callback that doesn’t get a success response within 10 seconds, so the same one can arrive more than once. Make acting on it twice harmless, for example by checking whether the clip is already saved.

Run it

The last piece reads the command line, sets up a folder for the recording, runs the steps in order and prints a summary. Any error it doesn’t expect ends the run with one line instead of a stack trace.

Python
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, "
                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("render", {}).get("error")]
            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 the AI model 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)
        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 "
            "may still have reached Shotstack, so look in your dashboard before you "
            "run this again."
        )
    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__":
    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}")

Run it with the recording’s URL:

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"

To check the layout before rendering everything, add --limit 1 to render only the first clip, then run the same command again without it. Thanks to the manifest, nothing that’s already done is repeated.

Here’s the output from our final run. It reused the transcript and the edited moments from earlier runs, so it went straight to rendering, and all five clips were ready less than three minutes after the first request:

Text
Using the moments in clips/fosdem-2025-5235-beyond-the-readme-craft/moments.json
Rendering 5 clips
  clip 1: queued (3085f186-82ba-4ac6-9333-526816ff401b)
  clip 2: queued (71d73531-2435-46d0-964b-a194faeb8ef2)
  clip 3: queued (25d1f77e-a671-4ed8-9595-e87f42962d88)
  clip 4: queued (25c64917-1938-4445-a6e4-b92ea078239b)
  clip 5: queued (97de71cb-9627-4e27-b10b-d5d6416ab909)
  clip 1: preprocessing after 0:39
  clip 2: preprocessing after 0:31
  clip 3: preprocessing after 0:26
  clip 4: fetching after 0:21
  clip 5: fetching after 0:17
  clip 1: queued after 0:56
  clip 2: queued after 0:48
  clip 3: queued after 0:44
  clip 4: preprocessing after 0:39
  clip 5: preprocessing after 0:34
  clip 1: rendering after 1:13
  clip 4: queued after 0:56
  clip 5: queued after 0:51
  clip 2: rendering after 1:23
  clip 3: rendering after 1:18
  clip 1: done after 1:48
  clip 1: saved clips/fosdem-2025-5235-beyond-the-readme-craft/clip-15m55s.mp4
  clip 3: done after 1:39
  clip 3: saved clips/fosdem-2025-5235-beyond-the-readme-craft/clip-11m48s.mp4
  clip 5: rendering after 1:34
  clip 2: done after 2:04
  clip 2: saved clips/fosdem-2025-5235-beyond-the-readme-craft/clip-34m52s.mp4
  clip 4: rendering after 1:58
  clip 5: saving after 1:53
  clip 4: done after 2:11
  clip 4: saved clips/fosdem-2025-5235-beyond-the-readme-craft/clip-29m55s.mp4
  clip 5: done after 2:09
  clip 5: saved clips/fosdem-2025-5235-beyond-the-readme-craft/clip-28m03s.mp4

Clips:
  1. The help output that gatekeeps users (15:55 to 16:30): clips/fosdem-2025-5235-beyond-the-readme-craft/clip-15m55s.mp4
  2. Maximum three nitpicks per pull request review (34:52 to 35:44): clips/fosdem-2025-5235-beyond-the-readme-craft/clip-34m52s.mp4
  3. Bad documentation beats no documentation (11:48 to 12:20): clips/fosdem-2025-5235-beyond-the-readme-craft/clip-11m48s.mp4
  4. Don't drip-feed requirements to new contributors (29:55 to 30:26): clips/fosdem-2025-5235-beyond-the-readme-craft/clip-29m55s.mp4
  5. Close issues you don't want, right away (28:03 to 28:56): clips/fosdem-2025-5235-beyond-the-readme-craft/clip-28m03s.mp4

Everything for the recording ends up in one folder:

Text
clips/fosdem-2025-5235-beyond-the-readme-craft/
  manifest.json
  moments.json
  transcript.srt
  clip-11m48s.mp4
  clip-15m55s.mp4
  clip-28m03s.mp4
  clip-29m55s.mp4
  clip-34m52s.mp4

And here are the five clips. The model’s picks vary from run to run and between providers, so yours may differ.

1. The help output that gatekeeps users (15:55 to 16:30)

2. Maximum three nitpicks per pull request review (34:52 to 35:44)

3. Bad documentation beats no documentation (11:48 to 12:20)

4. Don’t drip-feed requirements to new contributors (29:55 to 30:26)

5. Close issues you don’t want, right away (28:03 to 28:56)

Adapting it for stream recordings

The script starts from a recording at a URL, so the first job in a real system is getting each recording into storage you control. Most streaming and meeting platforms let you export or archive recordings, and once a file is in your own bucket, a presigned URL is all the import needs. Only clip recordings you have the rights to.

A commentated stream recording works the same way, as long as someone is talking through most of it. Two limits to plan for: Shotstack accepts source files up to 5 GB, so a long stream recording may need to be split or re-encoded first, and a transcript several hours long may need to go to the model in chunks, depending on the model. A quiet stretch of gameplay with a great moment in it won’t show up in a transcript at all, so a picker for that kind of footage needs other signals, like chat activity or the video itself.

Taking it to production

The script keeps its state in files and polls for results, which is fine for a demo. In a product, the same design stretches in a few directions:

  • Webhooks instead of polling. Give each render a callback URL and save each clip when its webhook arrives, confirming the render’s status by its ID.
  • A database instead of the manifest. What the script keeps in files (the source and each clip’s caption file and render ID in manifest.json, the moments in moments.json) becomes a row per recording and a row per clip.
  • Storage. Send finished clips to your own storage with destinations instead of downloading each one. To post a clip to YouTube, upload it with the YouTube Data API.
  • Many recordings at once. Each clip’s render is independent, so clips from many recordings can render at the same time. Every render request and every status check counts toward the Edit API’s rate limit of 300 requests a minute in production, so at volume, webhooks also save you the status checks.
  • A review step. Because the moments are a plain list, you can show them to a person to approve or adjust before any rendering starts.
  • More formats. The same moments can feed other renders, like a 16:9 highlight reel of the best moments, as in the sports highlights guide, or branded shorts built from a template, as in the YouTube Shorts guide.

Build clipping into your own product

You now have a pipeline that turns a long recording into short, captioned, vertical clips. The Ingest API gives you the transcript, your picker writes the moments list, and one Edit API render per moment turns it into a finished clip, captioned from the same transcript.

Because the moments list is the only handoff, you can swap the picker, change AI provider, add a review step or move to webhooks without touching the rest.

Sign up for a free Shotstack API key and point clips.py at one of your own recordings.

Frequently asked questions (FAQs)

Does each clip transcribe its audio again?

No. The import transcribes the whole recording once. Each clip’s captions are the transcript lines inside its moment, uploaded as a small SRT file, so each clip is a single render. The captions also match the words the picker read.

Can I use a different model, or my own rules, to pick the moments?

Yes. Any provider with an OpenAI-compatible chat API works: change AI_BASE_URL, AI_API_KEY and AI_MODEL. For a provider without one, replace ask_ai, which only has to return the text of the model’s reply. The renders only read moments.json, so you can also skip the model and write the moments with rules of your own, or let a person pick them.

How do I automatically clip long videos as soon as they arrive?

Start the pipeline from whatever tells you a recording has landed, like an upload event from your storage, a webhook from your video platform or a scheduled job that checks for new files. Run the import and the picker, submit the renders with callback URLs, and let each webhook save its clip. The manifest in this script becomes a row in your database, and the whole thing runs without anyone waiting on it.

Can I make square or horizontal clips too?

Yes, though we only tested the vertical layout. For square clips, change the output size in clip_edit to 1080x1080, then shrink the caption box and lower its offset to fit the bands above and below the video, which are only about 236 pixels tall. For horizontal clips, render at 1920x1080, leave out "fit": "contain", and put the captions over the bottom of the picture. The picker and the moments stay the same.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required