Try an interactive version of this dialog: Sign up at solve.it.com, click Upload, and pass this URL.
Create Notes from Youtube Transcript
Foreword This dialogue is a modification of the original dialogue here: https://share.solve.it.com/d/6307523ab98ea49b402f5924568fb2de
The two main changes made are:
- Anthropic library has been replaced with Lisette (therefore, it is no longer needed to specificaly set an ANTHROPIC_API_KEY)
- Each subheading in a chapter gets it's own message
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:
- Download the video (720p) and transcript.
- Uses claude to break the transcript into Chapters and Sections.
- Takes screenshots from the video that line up with each Section.
- Adds a title note and also a note message for each of the Chapters.
- 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.
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 lisette import *
from dialoghelper.core import *
chat = Chat(model='moonshot/kimi-k2-0711-preview')
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 = chat(prompt)
return {
'chunk_index': chunk_index,
'response': response.choices[0].message.content,
'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 section"""
# 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 section as a separate message
for chapter_num, chapter in enumerate(tqdm(chapters, desc="Chapters"), 1):
# Add chapter header as its own message
chapter_header = f"## Chapter {chapter_num}: {chapter['title']}\n"
add_msg(chapter_header, msg_type='note', placement='at_end', skipped=True)
# Add each section as its own message
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)
section_md = f"### {section_title}\n\n"
section_md += f"<a href=\"{yt_link}\" target=\"_blank\">{timestamp}</a> **{speaker}**: {text}\n\n"
if section_num in screenshots:
section_md += f"\n"
add_msg(section_md, msg_type='note', placement='at_end', skipped=True, i_collapsed=True, o_collapsed=True)
print(f"\n✓ Complete! Added messages to dialog")
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)}
Please can you run the &add_transcript_from_youtube tool and use it with: https://www.youtube.com/watch?v=m-GOZSi2R_Q&t
🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠
I'll run the add_transcript_from_youtube tool with that YouTube video for you.
{
"id": "toolu_014z9SsTRt3SePPU4ia8KLep",
"call": {
"function": "add_transcript_from_youtube",
"arguments": {
"video_url_or_id": "https://www.youtube.com/watch?v=m-GOZSi2R_Q&t"
}
},
"result": "{'video_id': 'm-GOZSi2R_Q', 'chapters': 1, 'sections': 5}"
}
Perfect! The tool has successfully processed the video. It created:
- 1 chapter with 5 sections
The transcript has been added to your dialog as a series of note messages. You should see:
- A header note with the video title and metadata
- A chapter note
- Five individual section notes, each with:
- Section title
- Timestamp link back to YouTube
- The transcript text for that section
- A screenshot from that moment in the video
You can now work through the video content step by step using these notes!
Introduction and Purpose
00:00 Jonno: Hello everyone, Jonno here. With the announcement of our new Solve It course, uh people asking what what is Solvent the app? What is this all about? I thought I should show a few of the cases where I've used it outside of work recently just to give you a feel for what Solit looks like. Um the kinds of things that it's ideally suited for um and what you can do.

What is Solvent
00:18 Jonno: So Solit is kind of like a dialogue between you, you can put notes to yourself. It's also a place to execute code, right? It's a a Jupiter style ripple environment. Um everything is live. So you can see if I've declared a variable um that now exists and I can modify that right and and and follow um what's going on. And it's also a dialogue between you and the computer. So for example, you can uh any Python tool that you can use, you can give that to solve it as a tool. Um and it can interact with the code that you've written, variables that you've defined. Um and yeah, it's all interacting in that same environment. So you can see here it just added to that same variable. um it's able to you know tell us how things work, explain things.

Use Cases Overview
01:03 Jonno: So some of the use cases um you know scraping data from a site um you can see here like I'm doing a lot of the work myself uh exploring around testing things out but then I'm also able to just hand it like hey here's the content of a page. Could you help me pull out the pieces of information that I'm interested in? Um exploring models so loading up um little models to do bits of ML research on. Again, really great to be able to just interact, explore, or poke at things. And then also, if you hit a roadblock, like at some point something's not working or or you're you're unsure what's going on, being able to ask the AI like, "Hey, you know, how might I uh check that everything's on the right device anytime you need that assistant." Um, yeah, exploring, in this case, um, some recreational maths, you know, is watching a YouTube video. Um, and then again like doing a lot of the stuff myself because it's just fun to have a a computational playground as it were to to test that ideas, but then also being able to ask it to, for example, use the search tool, tell me if I'm on the right track. Uh, it's able to give me um, you know, fancy names to put to to the concepts that's going on. Um, and also for things like, you know, in this case, um, yeah, exploring questions that I have and writing things like the uh, the plotting code. I don't I don't need to to do the um the plotting myself. if I'm more interested in the in the solving, but it's really cool to then have something that can say, "Oh, well, here you go. Here's your uh your fancy mapplot lib um output, right? That's not the uh the end goal for me, but it's nice to have this AI co-worker buddy."

Real-World Examples
02:28 Jonno: Um yeah, so I use this for all sorts of things. I use it when I'm curious whether or not AI can do something to pull together some data and send that as an eval. I use it for um hopping out like in this case I've got a friend who's a civil engineer um analyzing some data loading a file poking at it getting info from the AI how might I pull out the relevant bits you know could it write the regular expression for me thank you very much and then um importantly being able to validate at every step okay these are the lines I'm interested in can I do the convex hull yes it can tell me how to do the convex hull great I just at the bottom yes it can tell me how to get that um so it's very much a back and forth between you between the computer that's executing the code and between the AI.

Philosophy and Course Announcement
03:06 Jonno: Um, so yeah, those are just like some recent dialogues I had open. Um, I hope that elucidates a little bit about how we use solvent as a tool and some of the things it can do. Um, it does feel like a different way of coding to um, anyone who's used to the offload everything to the AI, but it also feels like a very familiar and obvious way of coding if you're at all uh, into the um, you know, the way we used to teach in fast AI, right? The sort of iterative exploratory programming with notebooks and MBDEV. Uh and for most people this it's like why are you describing this as anything new? This is just how good code is code is to do things in small incremental pieces that you understand. Um but yeah it's exciting to build a tool that tries to focus on that in an age where a lot of tools are focused on human replacement. Um so I hope you find that interesting. Uh if you want to come check out a course where we'll be covering how to use this tool and this approach for all sorts of things um check out the new solit course how to solve it with code. Uh but if you're just interested in the tool once that course is complete hopefully we'll be opening up just um kind of pay as you go subscriptions to to access it to use our you know instances in the cloud and our AI. Um but yeah uh otherwise you can take these ideas and you can apply them anywhere. So uh yeah I just hope you get some encouragement from this to keep on playing with code and working at your
