DEV Community

Yusuf Yildiz
Yusuf Yildiz

Posted on Originally published at importly.io

Chunking YouTube transcripts for RAG, with timestamps that link back

If you're building search or Q&A over videos, the fiddly part isn't the embeddings - it's turning caption lines into chunks that still know where in the video they came from. This is a chunker for that. It's standard library Python, and every chunk keeps a timestamp and a deep link so an answer can cite "0:05" and open the video right there.

Originally published at importly.io.

Why not embed the caption lines directly

Transcripts arrive as short segments. Caption tracks give you one segment per on-screen line, often five to ten words; speech-to-text gives roughly one per sentence. Embedding each one separately makes retrieval worse: a five-word line carries too little meaning to match a question, and you end up storing thousands of vectors per hour of video.

Merging consecutive segments into chunks of about 150 to 300 words works better. Each chunk keeps the start of its first segment and the end of its last, so you lose no timing information.

Step 1: get the segments from a link

You need the transcript as timed segments. On a laptop, pulling captions for a YouTube video usually just works. On a server it often doesn't, because YouTube blocks a lot of datacenter IPs, and plenty of videos have no captions at all. Disclosure: I built Importly for that case - you send it a link and get the segments back, from captions or speech-to-text when there are none. The get_transcript() used below is from this Python guide, but any source that gives you start, end and text per segment works the same.

The shape the chunker expects (times in seconds):

{
  "text": "All right, so here we are, in front of the elephants\n...",
  "source": "platform_captions",
  "language": "en",
  "duration": 19,
  "data": {
    "segments": [
      { "start": 1.2, "end": 3.36, "text": "All right, so here we are, in front of the elephants" },
      { "start": 5.318, "end": 7.974, "text": "the cool thing about these guys is that they have really..." },
      { "start": 7.974, "end": 12.616, "text": "really really long trunks" }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: merge segments into chunks

Standard library only. It counts words rather than model tokens, which is close enough for sizing chunks and keeps the code independent of any one model:

# chunks.py
from urllib.parse import parse_qs, urlparse


def chunk_segments(segments, max_words=200, overlap=1):
    """Merge transcript segments into chunks of about max_words words.

    Each chunk keeps the start of its first segment and the end of its last,
    and repeats the last `overlap` segments of the previous chunk so a
    sentence cut at the boundary still appears whole in one of them.
    """
    chunks, current, words = [], [], 0
    for seg in segments:
        n = len(seg["text"].split())
        if current and words + n > max_words:
            chunks.append(_merge(current))
            carry = current[-overlap:] if overlap else []
            words = sum(len(s["text"].split()) for s in carry)
            # Skip the overlap when it wouldn't leave room for new text
            current, words = (carry, words) if words + n <= max_words else ([], 0)
        current.append(seg)
        words += n
    if current:
        chunks.append(_merge(current))
    return chunks


def _merge(segs):
    return {
        "text": " ".join(s["text"].strip() for s in segs),
        "start": segs[0]["start"],
        "end": segs[-1]["end"],
    }


def youtube_id(url):
    u = urlparse(url)
    if u.hostname == "youtu.be":
        return u.path.lstrip("/")
    if u.path.startswith("/shorts/"):
        return u.path.split("/")[2]
    return parse_qs(u.query).get("v", [None])[0]


def link_at(url, seconds):
    """A link that opens the video at `seconds` (YouTube), else the plain URL."""
    video_id = youtube_id(url)
    if not video_id:
        return url
    return f"https://www.youtube.com/watch?v={video_id}&t={int(seconds)}s"


def clock(seconds):
    m, s = divmod(int(seconds), 60)
    h, m = divmod(m, 60)
    return f"{h}:{m:02}:{s:02}" if h else f"{m}:{s:02}"
Enter fullscreen mode Exit fullscreen mode

Run on the segments above with max_words=15, it returns:

[
  { "text": "All right, so here we are, in front of the elephants", "start": 1.2, "end": 3.36 },
  { "text": "the cool thing about these guys is that they have really... really really long trunks", "start": 5.318, "end": 12.616 }
]
Enter fullscreen mode Exit fullscreen mode

A few choices worth knowing:

  • Overlap is in segments, not words. Repeating the last caption line of the previous chunk keeps a sentence that straddles the boundary findable, without cutting a line in half. Set overlap=0 if you'd rather not store the repeat.
  • One long segment is never split. Caption lines and speech-to-text sentences are usually far shorter than a chunk. If you do see oversized chunks, split long segments on sentence punctuation before chunking.
  • The timestamps stay honest. start is when the first line of the chunk begins, so a deep link lands just before the matching passage rather than after it.

Step 3: build records with a deep link

# records.py
from chunks import chunk_segments, clock, link_at
from transcript import get_transcript  # from the Python transcript guide


def video_chunks(url, title=None, max_words=200):
    result = get_transcript(url)
    records = []
    for i, chunk in enumerate(chunk_segments(result["data"]["segments"], max_words)):
        records.append({
            "id": f"{url}#{i}",
            "text": chunk["text"],
            "metadata": {
                "url": url,
                "title": title,
                "start": chunk["start"],
                "end": chunk["end"],
                "label": f"{clock(chunk['start'])}-{clock(chunk['end'])}",
                "link": link_at(url, chunk["start"]),
                "language": result["language"],
                "source": result["source"],
            },
        })
    return records
Enter fullscreen mode Exit fullscreen mode

Each record looks like this:

{
  "id": "https://www.youtube.com/watch?v=jNQXAC9IVRw#1",
  "text": "the cool thing about these guys is that they have really... really really long trunks and that's cool",
  "metadata": {
    "url": "https://www.youtube.com/watch?v=jNQXAC9IVRw",
    "title": "Me at the zoo",
    "start": 5.318,
    "end": 17.0,
    "label": "0:05-0:17",
    "link": "https://www.youtube.com/watch?v=jNQXAC9IVRw&t=5s",
    "language": "en",
    "source": "platform_captions"
  }
}
Enter fullscreen mode Exit fullscreen mode

Embed text with whatever model you already use and store the record with its metadata in your vector store. At answer time, put the label next to each retrieved passage in the prompt and ask the model to cite it, then render link so the user can jump straight to the moment. For sites without a time parameter, link_at returns the plain URL and you can show the label on its own.

Doing this for many videos

Don't hold a web request open per video. Fetch transcripts in a background job or a webhook handler and run the chunk-and-embed step there. Store the record id so re-ingesting a video replaces its chunks instead of duplicating them.

What chunk size should I use?

About 200 words with one segment of overlap is a reasonable starting point. Then adjust from your own retrieval results: if answers miss context, go larger; if retrieved passages are mostly off-topic, go smaller. Time windows (say, every 60 seconds) are simpler, but speaking speed varies a lot between videos, so counting words gives steadier chunks while the segment times still give you the timestamps.

Top comments (0)