Try an interactive version of this dialog: Sign up at solve.it.com, click Upload, and pass this URL.

Note: 592

Create Notes from Youtube Transcript

Here is a tool that can be used as a starting point to help you work through a techincal youtube video step by step.

You will need to set an ANTHROPIC_API_KEY env var to use this tool.

You can see my original dialog that got me to this point here: https://share.solve.it.com/d/7b6522c7a6aeca36fbcd5ca01be523dc

The tool can be pointed at any youtube video, and will do the following:

  1. Download the video (720p) and transcript.
  2. Uses claude to break the transcript into Chapters and Sections.
  3. Takes screenshots from the video that line up with each Section.
  4. Adds a title note and also a note message for each of the Chapters.
  5. Each note message contains links back to the original video and screenshots for each section as well as the concatenated and punctuated transcript for the section.

Usage

Run the code cells and tool definintion note below. This makes the functions runnable by the AI.

You can just ask the AI to use the add_transcript_from_youtube and it will do the rest. You just need a youtube url or video id.

You can also export the tool using the will be exported button, and then use it in other dialogs on the same instance. See Johno's example of this from Lesson 3.

Anything else?

I used a fair bit of parallelism here to make sure that the tool call runs in under 2 minutes.

I ended up chunking the transcript and sending to Claude API in chunks and then stitching them back together. I'm not sure if this is the best approach, but sending in one big blob was timing taking far too long and timing out.

Code: 4,333 (5:40:23a)

import os
import re
import json
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from tqdm import tqdm
import yt_dlp
import tiktoken
from anthropic import Anthropic
from dialoghelper.core import *

client = Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))

def download_video_and_transcript(video_id, lang_code='en'):
    video_path = f'{video_id}.mp4'
    ydl_opts = {
        'format': 'best[height<=720]',  # Lower quality for faster download
        'quiet': True,
        'noprogress': True,  # Suppresses progress bar
        'no_warnings': True, # Suppresses warnings
        'outtmpl': video_path,
        'writesubtitles': True,
        'subtitlesformat': 'srt',  # Use SRT format for subtitles
        'subtitleslangs': [lang_code],
        'writeautomaticsub': True,  # Download automatic subtitles
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(f'https://www.youtube.com/watch?v={video_id}', download=False)
        if not Path(video_path).exists():
            print("Downloading video & transcript")
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.download([f'https://www.youtube.com/watch?v={video_id}'])
            print(f"Downloaded: {video_path} & transcript: {video_path}.{lang_code}.srt")
        else:
            print(f"Video already exists: {video_path}")
    return info

# Parse the SRT
def parse_srt_to_text(srt_data):
    """Extract just the text from SRT, preserving timing"""
    lines = srt_data.strip().split('\n')
    segments = []
    current_time = None
    current_text = []
    
    for line in lines:
        if '-->' in line:
            current_time = line.split(' --> ')[0]
        elif line.strip() and not line.strip().isdigit():
            current_text.append(line.strip())
        elif line.strip() == '' and current_text:
            segments.append({
                'time': current_time,
                'text': ' '.join(current_text)
            })
            current_text = []
    
    return segments

def count_tokens(text):
    """Count tokens in text using tiktoken"""
    encoding = tiktoken.get_encoding("cl100k_base")
    # Get the tokenizer for the model you'll use
    # Count tokens
    token_count = len(encoding.encode(text))
    print(f"Transcript Token Count: {token_count:,}")


def get_seconds(time_str):
    """Convert HH:MM:SS,mmm or MM:SS,mmm to seconds"""
    parts = time_str.replace(',', '.').split(':')
    if len(parts) == 3:  # HH:MM:SS
        return int(parts[0])*3600 + int(parts[1])*60 + float(parts[2])
    else:  # MM:SS
        return int(parts[0])*60 + float(parts[1])

def chunk_transcript(segments, chunk_size_minutes=5, overlap_seconds=15):
    """Split transcript into time-based chunks with overlap"""
    chunks = []
    current_chunk = []
    chunk_start_time = 0
    
    for seg in segments:
        seconds = get_seconds(seg['time'])
        
        # Add to current chunk
        current_chunk.append(seg)
        
        # Check if chunk is full (reached chunk_size_minutes)
        if seconds >= chunk_start_time + (chunk_size_minutes * 60):
            chunks.append(current_chunk.copy())
            # Start new chunk with overlap
            overlap_start = seconds - overlap_seconds
            current_chunk = [s for s in current_chunk 
                           if get_seconds(s['time']) >= overlap_start]
            chunk_start_time = seconds
    
    # Add remaining chunk
    if current_chunk:
        chunks.append(current_chunk)
    
    return chunks

def process_chunk(chunk_segments, chunk_index, total_chunks):
    """Process a single chunk with Claude"""
    chunk_text = '\n'.join([f"[{seg['time']}] {seg['text']}" for seg in chunk_segments])
    
    # Get time range for this chunk
    start_time = chunk_segments[0]['time']
    end_time = chunk_segments[-1]['time']
    
    prompt = f"""You are analyzing a video transcript chunk (part {chunk_index+1} of {total_chunks}).
Time range: {start_time} to {end_time}

**Task 1: Identify chapter breaks**
If this chunk contains a major topic change that warrants a new chapter, identify it.

**Task 2: Break into sections**
Break this chunk into logical sections based on:
- Topic changes or new concepts
- Significant new information
- Roughly 90 to 120 second sections if no natural breaks

For each section provide:
- Section number
- Section title
- Start timestamp (format: MM:SS or HH:MM:SS)
- Speaker name if identifiable (or "Speaker" if not)
- Complete text as a well-formed paragraph with proper punctuation
- Chapter title (if this section starts a new chapter, otherwise null)

**Important rules:**
- Do NOT edit words - only add punctuation and capitalization
- Complete sentences only
- No overlapping sections
- Technical videos are information-dense, create granular sections

**Transcript:**
{chunk_text}

Return ONLY valid JSON array:
[
  {{
    "section": 1,
    "section_title": "Section Title",
    "timestamp": "00:00",
    "speaker": "Speaker Name",
    "chapter_title": "Introduction to Tokenization",
    "text": "Full paragraph text."
  }},
  {{
    "section": 2,
    "section_title": "Section Title",
    "timestamp": "00:30",
    "speaker": "Speaker Name",
    "chapter_title": null,
    "text": "Full paragraph text."
  }}
]"""

    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=8000,
        messages=[{"role": "user", "content": prompt}]
    )
    
    return {
        'chunk_index': chunk_index,
        'response': response.content[0].text,
        'start_time': start_time,
        'end_time': end_time
    }

def process_all_chunks(chunks, max_workers=32):
    """Process all chunks in parallel"""
    print(f"Using {len(chunks)} chunks")

    # Process all chunks in parallel
    results = []
    with ThreadPoolExecutor(max_workers=32) as executor:
        futures = {
            executor.submit(process_chunk, chunk, i, len(chunks)): i 
            for i, chunk in enumerate(chunks)
        }
        
        for future in tqdm(as_completed(futures), total=len(chunks), desc="Processing chunks"):
            try:
                result = future.result()
                results.append(result)
            except Exception as e:
                print(f"Error processing chunk {futures[future]}: {e}")

    # Sort results by chunk index
    results.sort(key=lambda x: x['chunk_index'])
    print(f"\nProcessed {len(results)} chunks successfully")
    return results

def parse_and_clean_json(response_text):
    """Extract JSON from response, handling markdown code blocks"""
    if '```json' in response_text:
        response_text = response_text.split('```json')[1].split('```')[0].strip()
    elif '```' in response_text:
        response_text = response_text.split('```')[1].split('```')[0].strip()
    
    return json.loads(response_text)

def stitch_results(results):
    """Stitch results into Chapters & Sections"""
    # Parse all chunks
    all_sections = []
    seen_texts = set()  # Track duplicates

    for result in results:
        try:
            sections = parse_and_clean_json(result['response'])
            
            for section in sections:
                # Check for duplicates (from overlap)
                text_key = section['text'][:100]  # First 100 chars as key
                
                if text_key not in seen_texts:
                    seen_texts.add(text_key)
                    all_sections.append(section)
        except Exception as e:
            print(f"Error parsing chunk {result['chunk_index']}: {e}")
            print(f"Response preview: {result['response'][:200]}")

    # Renumber sections sequentially
    for i, section in enumerate(all_sections, 1):
        section['section'] = i

    # Extract chapters
    chapters = []
    current_chapter = None

    for section in all_sections:
        if section.get('chapter_title'):
            # Start a new chapter
            if current_chapter:
                chapters.append(current_chapter)
            current_chapter = {
                'title': section['chapter_title'],
                'sections': [section]
            }
        else:
            # Add to current chapter
            if current_chapter:
                current_chapter['sections'].append(section)
            else:
                # No chapter yet, create a default one
                current_chapter = {
                    'title': 'Introduction',
                    'sections': [section]
                }

    # Add the last chapter
    if current_chapter:
        chapters.append(current_chapter)

    print(f"Total sections: {len(all_sections)}")
    print(f"Total chapters: {len(chapters)}")
    return chapters

def extract_screenshot(video_path, timestamp, section_num, output_dir):
    """Extract screenshot at given timestamp using ffmpeg"""
    try:
        # Convert timestamp to seconds
        seconds = get_seconds(timestamp)
        
        # Create output file path
        output_path = output_dir / f"screenshot_{section_num}.jpg"
        
        # Use ffmpeg to extract frame
        cmd = [
            'ffmpeg', '-ss', str(seconds), '-i', video_path,
            '-vframes', '1', '-q:v', '2',  # Quality 2 (high)
            '-y', str(output_path)
        ]
        
        # Run silently
        subprocess.run(cmd, capture_output=True, check=True)
        
        return str(output_path)
    except Exception as e:
        print(f"Error extracting screenshot for section {section_num}: {e}")
        return None

def extract_all_screenshots(all_sections, video_path, max_workers=16):
    """Extract all screenshots in parallel"""
    screenshot_paths = {}
    completed = 0
    
    # Create output directory for screenshots
    output_dir = Path(f"video_screenshots/{Path(video_path).stem}")
    output_dir.mkdir(exist_ok=True, parents=True)

    # Extract all screenshots in parallel
    print(f"Extracting {len(all_sections)} screenshots using {max_workers} workers...")
    
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {
            executor.submit(extract_screenshot, video_path, section['timestamp'], section['section'], output_dir): section['section']
            for section in all_sections
        }
        for future in tqdm(as_completed(futures), total=len(all_sections), desc="Extracting screenshots", leave=False):
            section_num = futures[future]
            try:
                img_path = future.result()
                if img_path:
                    screenshot_paths[section_num] = img_path
                completed += 1
            except Exception as e:
                print(f"Error for section {section_num}: {e}")
    
    print(f"\n✓ Extracted {len(screenshot_paths)}/{len(all_sections)} screenshots")
    return screenshot_paths

def format_timestamp_link(timestamp, video_id):
    """Convert timestamp to YouTube link"""
    seconds = int(get_seconds(timestamp))
    return f"https://www.youtube.com/watch?v={video_id}&t={seconds}s"

def add_transcript_msg_by_chapters(video_id, chapters, screenshots, info):
    """Add transcript as separate messages per chapter"""
    
    # Add header message
    header_md = f"# Video Transcript: {info.get('title', 'Video')}\n"
    header_md += f"**Video ID**: {video_id}\n"
    header_md += f"**Duration**: {info.get('duration_string', 'Unknown')}\n"
    header_md += f"**Total Chapters**: {len(chapters)}\n"
    
    add_msg(header_md, msg_type='note', placement='add_after')
    
    # Add each chapter as a separate message
    for chapter_num, chapter in enumerate(tqdm(chapters, desc="Chapters"), 1):
        chapter_lines = [f"## Chapter {chapter_num}: {chapter['title']}\n"]
        
        for section in chapter['sections']:
            section_num = section['section']
            section_title = section['section_title']
            timestamp = section['timestamp']
            speaker = section['speaker']
            text = section['text']
            
            yt_link = format_timestamp_link(timestamp, video_id)
            chapter_lines.append(f"\n### {section_title} \n")
            chapter_lines.append(f"<a href=\"{yt_link}\" target=\"_blank\">{timestamp}</a> **{speaker}**: {text}\n")
            
            if section_num in screenshots:
                chapter_lines.append(f"![{section_title}]({screenshots[section_num]}#ai) \n")
        
        chapter_md = '\n'.join(chapter_lines)
        add_msg(chapter_md, msg_type='note', placement='at_end', skipped=True, i_collapsed=True, o_collapsed=True)
    
    print(f"\n✓ Complete! Added {len(chapters)+1} messages to dialog")

Code: 693 (5:40:23a)

def add_transcript_from_youtube(video_url_or_id: str, lang_code: str = 'en', chunk_minutes: int = 5):
    """Download YouTube video, extract transcript with LLM analysis, and add to dialog"""
    
    # Extract video ID from URL if needed
    if 'youtube.com' in video_url_or_id or 'youtu.be' in video_url_or_id:
        match = re.search(r'(?:v=|/)([a-zA-Z0-9_-]{11})', video_url_or_id)
        video_id = match.group(1) if match else video_url_or_id
    else:
        video_id = video_url_or_id
    
    print(f"Processing video: {video_id}\n")
    
    # 1. Download video and transcript
    info = download_video_and_transcript(video_id, lang_code)
    
    # 2. Parse SRT
    with open(f'{video_id}.{lang_code}.srt', 'rb') as f:
        srt_data = f.read().decode('utf-8')
    segments = parse_srt_to_text(srt_data)
    full_transcript = '\n'.join([f"[{seg['time']}] {seg['text']}" for seg in segments])
    
    # 3. Count tokens
    count_tokens(full_transcript)
    
    # 4. Chunk transcript
    chunks = chunk_transcript(segments, chunk_size_minutes=chunk_minutes)
    print(f"Created {len(chunks)} chunks\n")
    
    # 5. Process chunks with LLM
    results = process_all_chunks(chunks)
    
    # 6. Stitch results into chapters
    chapters = stitch_results(results)
    
    # 7. Extract all sections for screenshots
    all_sections = []
    for chapter in chapters:
        all_sections.extend(chapter['sections'])
    
    screenshots = extract_all_screenshots(all_sections, f'{video_id}.mp4')
    
    # 8. Add to dialog
    add_transcript_msg_by_chapters(video_id, chapters, screenshots, info)
    
    return {'video_id': video_id, 'chapters': len(chapters), 'sections': len(all_sections)}

Note: 40

  • &add_transcript_from_youtube: Get a youtube video transcript and create a series of chaptered note messages from the transcript

Prompt: 34

Please can you run the &add_transcript_from_youtube tool and use it with a random youtube video

Assistant: 402

🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠

I'll run the add_transcript_from_youtube tool with a random YouTube video. Let me pick an interesting technical video for demonstration:

Copied!
{
  "id": "toolu_01EKQVSapLzovLSoNZh7fjZ6",
  "call": {
    "function": "add_transcript_from_youtube",
    "arguments": {
      "video_url_or_id": "https://www.youtube.com/watch?v=kCc8FmEb1nY"
    }
  },
  "result": "{'video_id': 'kCc8FmEb1nY', 'chapters': 21, 'sections': 163}"
}

Perfect! The tool successfully processed the video and created:

  • 21 chapters
  • 163 sections with timestamps and screenshots

The transcript has been added to your dialog as a series of collapsed note messages - one for each chapter. Each section includes:

  • A link back to the specific timestamp in the YouTube video
  • The transcribed text formatted as a paragraph
  • A screenshot from that moment in the video

You can now expand any chapter to explore the content step-by-step. This makes it easy to work through technical videos methodically!