Skip to content

Instantly share code, notes, and snippets.

@hamelsmu
Created July 6, 2025 03:16
Show Gist options
  • Save hamelsmu/520b0bdc416a835674b3f8e830a8e521 to your computer and use it in GitHub Desktop.
Save hamelsmu/520b0bdc416a835674b3f8e830a8e521 to your computer and use it in GitHub Desktop.
YouTube Chapter Generator - Generate summaries and timestamps for YouTube videos using Gemini API
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "httpx",
# "typer",
# "rich",
# ]
# ///
"""
Generate chapter summaries with timestamps for YouTube videos using Google's Gemini API.
"""
import os, re, httpx, typer
from typing import Optional, Annotated
from rich.console import Console
console = Console()
def generate(
url: Annotated[str, typer.Argument(help="YouTube video URL")],
model: Annotated[str, typer.Option("--model", "-m")] = "gemini-2.5-flash",
prompt: Annotated[Optional[str], typer.Option("--prompt", "-p")] = None,
):
"""Generate chapter summaries for a YouTube video."""
if not (api_key := os.environ.get("GEMINI_API_KEY")):
return console.print("[red]Error: GEMINI_API_KEY environment variable is not set.[/red]")
if not re.match(r'(https?://)?(www\.)?(youtube\.com/(watch\?v=|embed/)|youtu\.be/)[\w-]+', url):
return console.print(f"[red]Error: '{url}' is not a valid YouTube URL[/red]")
try:
with console.status(f"[bold blue]Analyzing video with {model}...[/bold blue]", spinner="dots"):
response = httpx.post(
f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}",
json={
"contents": [{
"role": "user",
"parts": [
{"fileData": {"mimeType": "video/*", "fileUri": url}},
{"text": prompt or "Generate a succinct video summary (1-2 sentences) followed by YouTube chapter timestamps for this video. Format each line of the chapter summaries as 'MM:SS - Chapter Title' (e.g., '02:30 - Introduction'). Start with 00:00. Include all major topics and transitions and be thorough - do not miss any important topics. For the summary, do not say 'In this video, we will cover the following topics', 'This video discusses..' or anything like that. Instead, reference the main speaker's name if you know it."}
]
}],
"generationConfig": {
"mediaResolution": "MEDIA_RESOLUTION_LOW",
"responseMimeType": "text/plain",
"thinkingConfig": {"thinkingBudget": -1}
}
},
timeout=380.0
)
if response.status_code != 200:
return console.print(f"[red]API request failed: {response.json().get('error', {}).get('message', response.text)}[/red]")
if result := "".join(part.get("text", "") for candidate in response.json().get("candidates", []) for part in candidate.get("content", {}).get("parts", [])):
print(result)
else:
console.print("[yellow]No chapter summary generated.[/yellow]")
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
if __name__ == "__main__":
typer.run(generate)
@hamelsmu
Copy link
Author

hamelsmu commented Jul 6, 2025

YouTube Chapter Generator

Generate a brief summary and timestamped chapters for YouTube videos using Gemini's video understanding.

Setup

export GEMINI_API_KEY='your-api-key-here'
pip install httpx typer rich

Usage

python chapters.py "https://youtu.be/VIDEO_ID"

# Custom prompt
python chapters.py "https://youtu.be/VIDEO_ID" --prompt "Your custom instructions"

# Different model
python chapters.py "https://youtu.be/VIDEO_ID" --model gemini-2.0-flash

Output Format

Brief 1-2 sentence summary of the video content.

00:00 - Introduction
02:30 - Main Topic
05:45 - Examples
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment