Tools & Extensions

Build a YouTube Transcript-to-Summary Pipeline (Python + OpenAI, ~100 Lines)

··10 min read

Most tutorials on this topic stop at the happy path. The 50-line script works fine on a 20-minute video with English captions. Then you try a 2-hour video, hit a token error, and realize you need a chunking strategy. Or the transcript API throws RequestBlocked on a Tuesday and your pipeline is down until you figure out why.

Here's a complete, production-aware pipeline in ~100 lines: the transcript fetch, the chunking logic for long videos, a MapReduce summarization pass, and the four error types you need to handle explicitly. The conceptual overview of what this pipeline does under the hood — and why each stage exists — is in our explainer on how AI summarizes YouTube videos. This article is the implementation.

The Full Pipeline Before Any Code: What We're Building

The short answer: Four stages — (1) fetch transcript via youtube-transcript-api, (2) split text into token-sized chunks with tiktoken, (3) summarize each chunk independently (MapReduce map pass), (4) combine chunk summaries into a final output (reduce pass). About 100 lines of Python. No LangChain dependency required.

The pipeline handles two cases:

  • Short videos (transcript fits in one LLM call): single-pass summarization
  • Long videos (multi-hour content): MapReduce chunking — summarize each chunk, then reduce the chunk summaries into a final output

Understanding the branching logic upfront makes the code easier to follow. The chunking is the only non-obvious part.

Install and Setup (2 Minutes)

The short answer: Three packages — youtube-transcript-api for transcript fetching, openai for the LLM call, and tiktoken for accurate token counting. Set OPENAI_API_KEY in your environment. Use youtube-transcript-api v1.2.4 — the API changed in v1.0.0 and older tutorials showing .get_transcript() are using the deprecated pattern.

pip install youtube-transcript-api openai tiktoken
# Set your OpenAI key (bash/zsh)
export OPENAI_API_KEY="sk-..."

For a deeper walkthrough of youtube-transcript-api — including language selection, available languages, and the full API surface — see our YouTube transcript API guide. This article assumes you're past the basics and ready to build the full pipeline.

Stage 1: Fetching the Transcript (and Handling Failures)

The short answer: YouTubeTranscriptApi.fetch(video_id, languages=["en"]) is the current v1.2.4 method. It returns a FetchedTranscript iterable of dicts with text, start, and duration fields. Join the text fields for plain text. Handle TranscriptsDisabled, NoTranscriptFound, and RequestBlocked explicitly — they're all common and silent failure is worse than a clear error.

from youtube_transcript_api import (
    YouTubeTranscriptApi,
    TranscriptsDisabled,
    NoTranscriptFound,
    RequestBlocked,
    VideoUnavailable,
)

def fetch_transcript(video_id: str, languages: list = ["en"]) -> str:
    """Fetch transcript and return as plain text. Raises ValueError on known failures."""
    try:
        transcript = YouTubeTranscriptApi.fetch(video_id, languages=languages)
        return " ".join(seg["text"] for seg in transcript)
    except TranscriptsDisabled:
        raise ValueError(f"Transcripts are disabled for video {video_id}")
    except NoTranscriptFound:
        raise ValueError(f"No transcript in {languages} for video {video_id}")
    except RequestBlocked:
        raise ValueError("YouTube blocked this request — rate limit or bot detection")
    except VideoUnavailable:
        raise ValueError(f"Video {video_id} is unavailable (private, deleted, or age-restricted)")

Note the API change: in v1.0.0+, the method is .fetch(), not .get_transcript(). Most tutorials written before 2024 use the old pattern. If you're hitting AttributeError or unexpected return types, you're likely running against a stale tutorial. See youtube-transcript-api not working for the full failure-modes diagnostic if your fetch is failing in unexpected ways.

The four error types, and when you'll see them:

Exception Trigger Likelihood
TranscriptsDisabled Video owner opted out of captions Rare
NoTranscriptFound No track in requested language Common on non-English channels
RequestBlocked YouTube rate-limited or bot-detected Occasional at volume
VideoUnavailable Private, deleted, or age-restricted Occasional

Note: TranscriptsDisabled is rare overall, but rates vary by category — channels that rely heavily on visual content or music tend to have higher rates than talk-format channels. YouTube doesn't publish aggregate statistics.

If you need an alternative extraction path for VideoUnavailable content, yt-dlp subtitle extraction covers the CLI fallback that handles some cases the transcript API can't reach.

Stage 2: Chunking for Long Videos (The Token Limit Problem)

The short answer: Use tiktoken to count tokens accurately before splitting. A 1-hour video runs roughly 10,000–15,000 tokens of transcript text — within GPT-4o-mini's 128k context window, but quality degrades at high context fill. Chunking at 6,000 tokens adds robustness and keeps each summarization call well within a quality zone.

import tiktoken

def chunk_text(text: str, max_tokens: int = 6000, model: str = "gpt-4o-mini") -> list[str]:
    """Split text into token-bounded chunks."""
    enc = tiktoken.encoding_for_model(model)
    tokens = enc.encode(text)
    chunks = []
    for i in range(0, len(tokens), max_tokens):
        chunk_tokens = tokens[i:i + max_tokens]
        chunks.append(enc.decode(chunk_tokens))
    return chunks

Token math for typical videos:

  • 30-minute video: ~5,000–7,500 tokens (single-pass fine)
  • 1-hour video: ~10,000–15,000 tokens (1–2 chunks at 6k limit)
  • 3-hour video: ~30,000–45,000 tokens (5–8 chunks)

GPT-4o-mini's 128k context is large enough to handle most single videos in one pass — but even when the video fits, chunking is worth it. Quality can degrade when an LLM is asked to summarize near its context ceiling. Chunking keeps each summarization call manageable and makes errors easier to isolate.

Stage 3: MapReduce Summarization (Fast, Parallel-Friendly)

The short answer: Each chunk gets summarized independently in the map pass. The chunk summaries are then combined and passed to a final reduce call. This is the pattern LangChain's map_reduce chain implements under the hood — you can do it in pure Python without the framework overhead.

from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from environment

def summarize_chunk(chunk: str) -> str:
    """Summarize one chunk — called once per chunk in the map pass."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": "You are a concise summarizer. Extract the key points from this transcript excerpt. Be specific — include concrete examples, numbers, and claims from the text."
            },
            {"role": "user", "content": chunk}
        ],
        max_tokens=400
    )
    return response.choices[0].message.content

MapReduce vs Refine — when to use each:

  • MapReduce (this pipeline): Fast; parallelizable; each chunk summarized independently. Minor coherence loss at chunk boundaries. Best for most pipelines.
  • Refine: Pass chunk 1 summary + chunk 2 text to LLM → iteratively refine. Better narrative coherence, but sequential (can't parallelize), higher total token cost. Worth it for long-form content where argument continuity matters (lectures, debates, long interviews).

For the map pass, gpt-4o-mini keeps costs low — verify current pricing at openai.com/api/pricing before deploying. Use gpt-4o for the reduce pass if output quality matters more than cost.

Stage 4: The Reduce Pass and Output Formatting

The short answer: After the map pass, combine the chunk summaries and run one final LLM call that synthesizes them into a coherent output. The system prompt controls output structure — request JSON if you need a parseable response for storage or display.

def reduce_summaries(chunk_summaries: list[str]) -> str:
    """Combine chunk summaries into a final structured output."""
    combined = "\n\n---\n\n".join(chunk_summaries)
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": (
                    "You are synthesizing section summaries from a YouTube video into a final report. "
                    "Return valid JSON with this structure: "
                    '{"tldr": "2-3 sentence summary", "key_points": ["point 1", "point 2", ...], "chapters": [{"title": "...", "summary": "..."}]}'
                )
            },
            {"role": "user", "content": combined}
        ],
        max_tokens=800
    )
    return response.choices[0].message.content

Requesting JSON from the LLM is the right pattern when you need to store or display the output programmatically. Add response_format={"type": "json_object"} to the API call if you want guaranteed JSON parsing (available on GPT-4o and GPT-4o-mini models).

The Full Pipeline: Fetch → Chunk → Map → Reduce

Putting the stages together:

def summarize_video(video_id: str) -> str:
    """Full pipeline: fetch transcript → chunk → map-summarize → reduce."""
    # Stage 1: Fetch
    text = fetch_transcript(video_id)

    # Stage 2: Chunk
    chunks = chunk_text(text)

    if len(chunks) == 1:
        # Short video — single-pass summarization
        return summarize_chunk(chunks[0])

    # Stage 3: Map pass — summarize each chunk
    chunk_summaries = [summarize_chunk(chunk) for chunk in chunks]

    # Stage 4: Reduce — synthesize chunk summaries
    return reduce_summaries(chunk_summaries)


# Usage
if __name__ == "__main__":
    video_id = "dQw4w9WgXcQ"  # replace with your target
    summary = summarize_video(video_id)
    print(summary)

This is the working skeleton. Depending on your use case, you'll want to add: retry logic on RequestBlocked, caching by video ID (avoids re-fetching the same transcript), and parallel chunk processing (the map pass is trivially parallelizable with concurrent.futures). Production patterns for concurrency and caching are covered in our youtube-transcript-api Python guide.

Running at Scale: Rate Limits, Caching, and Cost Control

The short answer: youtube-transcript-api can be rate-limited by YouTube at an unpublished threshold — community reports suggest somewhere in the range of tens of requests per hour from a single IP, varying by IP reputation and YouTube's current policy. Cache transcripts by video ID to avoid re-fetching. At current gpt-4o-mini pricing, cost is negligible at hobby scale — significant at 10,000+ videos/month. Rate limit strategies for the transcript fetch layer are covered in the YouTube transcript rate limit guide.

Caching pattern:

import sqlite3
import hashlib

def get_or_fetch_transcript(video_id: str, db_path: str = "transcripts.db") -> str:
    """Check cache before fetching. Cache by video_id."""
    conn = sqlite3.connect(db_path)
    conn.execute("CREATE TABLE IF NOT EXISTS transcripts (video_id TEXT PRIMARY KEY, text TEXT)")
    
    row = conn.execute("SELECT text FROM transcripts WHERE video_id = ?", (video_id,)).fetchone()
    if row:
        return row[0]
    
    text = fetch_transcript(video_id)
    conn.execute("INSERT INTO transcripts (video_id, text) VALUES (?, ?)", (video_id, text))
    conn.commit()
    return text

Cost estimate at scale: the dominant variable cost is the LLM. Check OpenAI's current pricing and estimate based on average tokens-per-video for your content mix (typical 30–60 minute videos run a few thousand input tokens after chunking, plus the summary output). The transcript fetch is free (youtube-transcript-api has no per-call cost). If you're processing at volume, batching the map pass with parallel requests reduces wall-clock time significantly.

The Managed Alternative: When Building Isn't Worth It

The short answer: This pipeline works. If you're building a summarization product or integrating YouTube context into your own app, go build it — the code above is a solid foundation. If you just want the summaries, SkipTheWatch runs this pipeline for you and adds persistent chat on top, so you can ask follow-up questions about any video at any time.

The honest fork in the road:

Build it yourself if:

  • You're integrating YouTube summarization into your own product
  • You need custom output formats or downstream data pipelines
  • You want full control over the LLM, the prompt, and the storage layer
  • You're processing a specific channel or video set as a batch job

Use STW if:

  • You want YouTube summaries — not a summarization product
  • You summarize 5–50 videos per week and the copy-paste workflow is the friction
  • You want persistent chat: ask follow-up questions about any video you've summarized, even a week later
  • You don't want to manage API keys, rate limit handling, or pipeline updates

Persistent chat is the part most quick scripts skip. Once you have the summary, being able to ask "what did they say about X?" without re-reading the whole output — and having that conversation stay accessible later — changes how the tool fits into your workflow. 7-day free trial (card required, $0 charged during trial), then $9/month for 500 summaries.


FAQ

Q: Why does the code use .fetch() instead of .get_transcript()? A: .fetch() is the current method in youtube-transcript-api v1.0.0+. .get_transcript() may still work for compatibility but is not the maintained pattern. Use .fetch() for any new code.

Q: How do I handle a video where the transcript is in Spanish but I want English? A: Pass the translation option: YouTubeTranscriptApi.fetch(video_id, languages=["en"]) tries English first. To request a translation of a Spanish transcript, use the TranscriptList API to find available tracks and call .translate("en") on the Spanish transcript object. The transcript API guide covers this in detail.

Q: Can I run the map pass in parallel instead of sequentially? A: Yes — and you should if processing more than ~3 chunks. The map pass is embarrassingly parallel since each chunk is independent. Wrap the chunk summarization calls with concurrent.futures.ThreadPoolExecutor or asyncio for a straightforward speedup.

Q: What's the cost difference between GPT-4o and GPT-4o-mini for this pipeline? A: For a 1-hour video the difference is roughly an order of magnitude — verify against current OpenAI pricing. gpt-4o-mini is the right choice for the map pass. Using gpt-4o only for the reduce pass (where output quality matters most) is a reasonable cost-quality tradeoff.

Q: Why does my summary for a long video seem to miss things from the middle? A: Chunking boundary artifacts — content that spans two chunks can lose coherence because neither chunk has full context. The Refine strategy (sequential, each step includes the previous summary) handles this better. MapReduce is faster; Refine is more coherent. For podcast-style or lecture content where narrative continuity matters, Refine is worth the slower runtime.

Q: Does youtube-transcript-api work for non-English videos? A: Yes — fetch with languages=["fr"] (or whichever language) to get a non-English transcript. Some channels have multi-language tracks; others only have auto-generated captions in the original language. Translation via .translate("en") is available in the transcript list API but adds a network call per video.

Q: What happens when RequestBlocked is raised? A: YouTube is rate-limiting or bot-detecting the request. Short-term: wait a few minutes and retry. Long-term: implement exponential backoff, use a proxy, or reduce request frequency. The YouTube transcript rate limit guide covers the full strategy for high-volume use cases.

Q: Is this pipeline English-only? A: The pipeline as written requests English (languages=["en"]). Swap in any language code and it works for any language YouTube has captions for — but the OpenAI summarization prompt would also need to be in the target language for best results.

Skip the watch. Get the insight.

AI summaries of any YouTube video in seconds — key insights, timestamps, structured breakdowns. Start free — no credit card. Pro is $9/month for 500 summaries with a 7-day free trial, cancel anytime.

Get my free summaries

Free to start · No credit card · Upgrade anytime

Related Articles