Try an interactive version of this dialog: Sign up at solve.it.com, click Upload, and pass this URL.
Tools available from dialoghelper:
- &
curr_dialog: Get the current dialog info. - &
msg_idx: Get absolute index of message in dialog. - &
add_html: Send HTML to the browser to be swapped into the DOM using hx-swap-oob. - &
find_msg_id: Get the current message id. - &
find_msgs: Find messages in current specific dialog that contain the given information.- (solveit can often get this id directly from its context, and will not need to use this if the required information is already available to it.)
- &
read_msg: Get the message indexed in the current dialog.- To get the exact message use
n=0andrelative=Truetogether withmsgid. - To get a relative message use
n(relative position index). - To get the nth message use
nwithrelative=False, e.gn=0first message,n=-1last message.
- To get the exact message use
- &
del_msg: Delete a message from the dialog. - &
add_msg: Add/update a message to the queue to show after code execution completes. - &
update_msg: Update an existing message. - &
url2note: Read URL as markdown, and add a note below current message with the result - &
msg_insert_line: Insert text at a specific location in a message. - &
msg_str_replace: Find and replace text in a message. - &
msg_strs_replace: Find and replace multiple strings in a message. - &
msg_replace_lines: Replace a range of lines in a message with new content.- Always first use
read_msg( msgid=msgid, n=0, relative=True, nums=True)to view the content with line numbers.
- Always first use
def add_msg(
content:str, # Content of the message (i.e the message prompt, code, or note text)
placement:str='add_after', # Can be 'add_after', 'add_before', 'at_start', 'at_end'
msgid:str=None, # id of message that placement is relative to (if None, uses current message)
msg_type: str='note', # Message type, can be 'code', 'note', or 'prompt'
output:str='', # For prompts/code, initial output
time_run: str | None = '', # When was message executed
is_exported: int | None = 0, # Export message to a module?
skipped: int | None = 0, # Hide message from prompt?
i_collapsed: int | None = 0, # Collapse input?
o_collapsed: int | None = 0, # Collapse output?
heading_collapsed: int | None = 0, # Collapse heading section?
pinned: int | None = 0, # Pin to context?
dname:str='' # Running dialog to get info for; defaults to current dialog
):
"Add/update a message to the queue to show after code execution completes."
if placement not in ('at_start','at_end') and not msgid: msgid = find_msg_id()
res = call_endp(
'add_relative_', dname, content=content, placement=placement, msgid=msgid, msg_type=msg_type, output=output,
time_run=time_run, is_exported=is_exported, skipped=skipped, pinned=pinned,
i_collapsed=i_collapsed, o_collapsed=o_collapsed, heading_collapsed=heading_collapsed)
set_var('__msg_id', res)
return res
File: /usr/local/lib/python3.12/site-packages/dialoghelper/core.py
I want to create a tool that you can use to download a youtube transcript message. The tool should work like this: add_tscript_msg(scribe_dst, yt_video_id='zduSFxRajkE')
I think we can use yt-dlp for this purpose. Can you guide me how to create this tool that builds upon the dialoghelper tools that are already available. I want to use as much of dialoghelper as we can.
Great project! Let's build this step by step. First, let me understand what you want:
You want a function that downloads a YouTube transcript and adds it as a message to the dialog, similar to how the existing dialoghelper tools work.
Before we start coding, let's think about the design:
- Should the transcript be added as a 'note' message (like
url2notedoes)? - Where should it be placed - after the current message, or somewhere else?
- Do you want any formatting for the transcript (like timestamps)?
Also, have you used yt-dlp to download transcripts before? If not, the basic command is something like:
yt_dlp.YoutubeDL(params).extract_info(url)
What are your thoughts on these questions?
After that tool call the transcript is added to a Note message, also there are timestemps that are links to that timestamp in the video on youtube. Also there are screensots from the video at certain times. There are actually many screenshots. Each screenshot has a title or description underneath it.
Is this possible with yt-dlp alone?
To answer your question I'm not sure what scribe_dst is about, but perhaps it is destination?
Ah, interesting! So you want:
- Transcript text
- Timestamps as clickable YouTube links
- Multiple screenshots from the video
- Titles/descriptions under each screenshot
To answer your question: No, yt-dlp alone won't do all of this. Here's what each tool can do:
yt-dlp can:
- Download transcripts with timestamps
- Extract video thumbnails (but usually just one or a few key frames)
yt-dlp cannot:
- Generate multiple screenshots throughout the video (you'd need
ffmpegfor that) - Create the HTML formatting for clickable timestamp links
- Add descriptions under screenshots automatically
So you'd need a combination of tools. Does that make sense?
Regarding scribe_dst - yes, I'm also not sure what that parameter is! Do you know where you saw this function signature? Is it from existing code you're working with, or were you designing the API yourself?
Lets try to do it all with solveit dialoghelpers and yt-dlp. We only need to take images screenshots at every timestamp
🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠
Good! So the plan is:
- Use
yt-dlpto download the transcript with timestamps - Use
yt-dlpto download the video (or useffmpeg-pythonwhich is available) to extract screenshots at each timestamp - Use
add_msgfrom dialoghelper to create a note with the formatted content
Let's break this into steps. Which part would you like to tackle first?
Option A: Start by getting the transcript data from yt-dlp and see what it looks like?
Option B: First figure out how to extract a single screenshot at a specific timestamp, then we can loop through all timestamps?
Option C: Start by looking at how url2note works in dialoghelper to understand the pattern for creating notes?
What sounds most useful to start with?
Perfect! Let's start by exploring what yt-dlp gives us for transcripts.
Here's a small snippet to get the transcript data:
import yt_dlp
ydl_opts = {
'skip_download': True,
'writesubtitles': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info('https://www.youtube.com/watch?v=zduSFxRajkE', download=False)
Try running this and then let's inspect what's in info. You can look at info.keys() to see what data is available.
What do you find?
import yt_dlp
from pathlib import Path
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
info = download_video_and_transcript('zduSFxRajkE')
with open('zduSFxRajkE.en.srt', 'rb') as f:
srt_data = f.read().decode('utf-8')
print(srt_data[:100])
I need to break down this whole video into manageable sections. So for each new concept or idea or important piece of information I need a timestamp with a link to that time in the video and all of the text transcript associated with it and a screenshot from the video. I cannot miss any of the text, it must all flow from section to section.
🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠
Got it! This is a bigger project. Let's break it down into steps:
What you need to do:
- Get full transcript text - Parse the SRT to extract all text in order
- Segment by topic - Decide how to break the video into sections (by time intervals? manually? using chapter markers if available?)
- Extract screenshots - Use
ffmpegto grab frames at each segment's timestamp - Format the note - Create markdown with:
- YouTube timestamp links (format:
https://www.youtube.com/watch?v=VIDEO_ID&t=123s) - Screenshots embedded
- Full transcript text for each section
- YouTube timestamp links (format:
- Use
add_msgto create the note
Questions before we start coding:
-
How do you want to decide where sections begin/end?
- Fixed time intervals (e.g., every 2 minutes)?
- Based on the video's chapter markers (if it has them)?
- Manually specify timestamps?
-
How many screenshots do you want? One per section? Multiple?
What approach sounds best to you?
Yes! I can see the structure now. Looking at the HTML, I can see:
- Timestamps with YouTube links:
[00:00],[55:45], etc. that link to specific times in the video - Speaker labels: "Andrej Karpathy:", "Speaker A:", etc.
- Transcript text: Full sentences/paragraphs of what was said
- Images: Embedded as base64 data in
<img>tags withsrcsetattributes - Section headers: Like "Introduction to Tokenization"
The structure appears to be:
- Section Title (e.g., "Introduction to Tokenization")
- [Timestamp] with YouTube link
- Speaker: Transcript text
- Image (screenshot from that moment)
- Repeat...
So the methodology seems to be:
- Break video into logical sections by topic/concept
- For each section: timestamp → speaker → transcript → screenshot
- Use YouTube timestamp links like
[00:00]that link tohttps://www.youtube.com/watch?v=VIDEO_ID&t=SECONDS
Is this the structure you want to replicate?
It seems like the transcript is split very cleanly. Each new section starts with the start of a new sentence. This tells me that they did not just split on fixed intervals. They used a smarter approach. Can we use a smarter approach with tools like LLM's or Spacy or NLTK? Where we split in a sensible or smart way
Excellent observation! Yes, we can use a smart approach. Here are the best options:
Option 1: Use an LLM to segment intelligently (Best for topic-based splitting)
# Use Claude/GPT to analyze the full transcript and suggest logical breakpoints
# based on topic changes, new concepts, etc.
Option 2: Use sentence boundaries + semantic similarity (Good balance)
# 1. Split transcript into sentences (using spaCy or NLTK)
# 2. Group sentences into chunks based on:
# - Semantic similarity (using embeddings)
# - Length constraints (e.g., 2-5 minute segments)
# - Natural breaks (pauses, topic shifts)
Option 3: Use spaCy for linguistic analysis (Fast and good)
import spacy
# Detect:
# - Sentence boundaries
# - Topic shifts (using noun phrases, entities)
# - Discourse markers ("Now", "So", "Next", etc.)
My recommendation: Let's use Option 1 with an LLM since you have Claude available. We can:
- Feed the full SRT transcript to Claude
- Ask it to identify logical section breaks with timestamps
- It will understand context and topic changes naturally
Want me to show you how to do this? We'd send the transcript to Claude and ask it to return a structured list of sections with timestamps and titles.
# 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
segments = parse_srt_to_text(srt_data)
# Join all segments into full transcript with timestamps
full_transcript_with_times = '\n'.join([f"[{seg['time']}] {seg['text']}" for seg in segments])
full_transcript_with_times[:1000]
"[00:00:00,040] hi everyone so in this video I'd like us\n[00:00:02,040] to cover the process of tokenization in\n[00:00:04,080] large language models now you see here\n[00:00:06,440] that I have a set face and that's\n[00:00:08,280] because uh tokenization is my least\n[00:00:10,320] favorite part of working with large\n[00:00:11,679] language models but unfortunately it is\n[00:00:13,480] necessary to understand in some detail\n[00:00:15,519] because it it is fairly hairy gnarly and\n[00:00:17,600] there's a lot of hidden foot guns to be\n[00:00:19,480] aware of and a lot of oddness with large\n[00:00:21,840] language models typically traces back to\n[00:00:24,599] tokenization so what is\n[00:00:26,640] tokenization now in my previous video\n[00:00:28,920] Let's Build GPT from scratch uh we\n[00:00:31,560] actually already did tokenization but we\n[00:00:33,480] did a very naive simple version of\n[00:00:35,800] tokenization so when you go to the\n[00:00:37,480] Google colab for that video uh you see\n"import tiktoken
# Get the tokenizer for the model you'll use
# For Claude, use the cl100k_base encoding (similar to GPT-4)
encoding = tiktoken.get_encoding("cl100k_base")
# Count tokens
token_count = len(encoding.encode(full_transcript_with_times))
print(f"Token count: {token_count:,}")
# Also show character count for reference
print(f"Character count: {len(full_transcript_with_times):,}")
print(f"Approximate ratio: {len(full_transcript_with_times) / token_count:.2f} chars/token")
Given we are passing 60k tokens to the model, how long do we thing it will take to process this? We are using haihu 4-5 model
With Haiku (Claude 3.5 Haiku), processing 60k tokens should be quite fast:
Input processing (60k tokens):
- Haiku is optimized for speed
- Input tokens are processed in parallel
- Expect: 2-5 seconds to process the input
Output generation:
- This depends on how much output you request
- Haiku generates roughly 80-100 tokens/second
- If you ask for a structured list of sections (maybe 2-5k tokens output), expect: 20-60 seconds for generation
Total estimate: 30-90 seconds depending on output length.
Haiku is the fastest Claude model, so this is a good choice for this task. It's much faster than Sonnet or Opus would be.
Want to proceed with sending the transcript to Haiku to identify logical section breaks?
Lets remember the output format that we want:
Section 1: [00:00] Andrej Karpathy: Hi everyone. So in this video, I'd like us to cover the process of tokenization in large language models. Now, you see here that I have a sad face, and that's because, well, tokenization is my least favorite part of working with large language models. But unfortunately, it is necessary to understand in some detail because it is fairly hairy, gnarly, and there are a lot of hidden foot guns to be aware of. And a lot of oddness with large language models typically traces back to tokenization.
Section 2: [00:25] Andrej Karpathy: So what is tokenization? Now, in my previous video, "Let's build GPT from scratch," we actually already did tokenization, but we did a very naive, simple version of tokenization.
Section 3: [00:36] Andrej Karpathy: So when you go to the Google Colab for that video, you see here that we loaded our training set. And our training set was this Shakespeare dataset. Now in the beginning, the Shakespeare dataset is just a large string in Python. It's just text. And so the question is, how do we plug text into large language models?
Here there is a section title, a timestamp that links to the video. Also note that the person speaking has their name at the beginning of the section. Then there is a paragraph of text. So it looks like the parser is breaking down the video into sensible paragraphs. There is punctuation here with capital letters at the beginning of each sentence and full stops at the end of each also.
Ideally we craft a prompt that can do this for any generic video. Most of the videos we are dealing with will be technical tutorial type vids so we need to break them down into fairly small sections as they can be quite information dense. See here that there is three sections for only the frist 36 seconds of the video.
I think it is sensible to create a new seciton when there is a topic change or significant new information is being shared or fall back to roughly 1 minute chunks otherwise. The chunks should be full paragraph style with punctuation and also with there can be no overlapping. Editing of the original transcript is not allowed, we can only add punctuation and group sentences together.
Try to come up with a prompt that captures what we are trying to do here, but the prompt must be generic and not too focused on just this video. Send the full transcript to claude, but lets only check the first 10 sections that come back.
🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠
Perfect! Here's a prompt that should work generically:
from claudette import Client
import json
prompt = f"""You are analyzing a video transcript and need to break it into logical sections for documentation purposes.
**Your task:**
1. Identify logical section breaks based on:
- Topic changes or new concepts being introduced
- Significant new information being shared
- If no natural break, create sections roughly every 30-60 seconds
2. For each section, provide:
- Section number
- Start timestamp from the transcript (format: MM:SS or HH:MM:SS)
- Speaker name if identifiable (or "Speaker" if not)
- The complete text as a well-formed paragraph with proper punctuation
**Important rules:**
- Do NOT edit or change the original words - only add punctuation and capitalization
- Each section must contain complete sentences
- Sections cannot overlap - each word appears in exactly one section
- Technical tutorial videos are information-dense, so err on the side of more granular sections
- Each paragraph should be cohesive and cover one main idea or concept
**Transcript with timestamps:**
{full_transcript_with_times}
Return a JSON array of objects with this structure:
[
{{
"section": 1,
"timestamp": "00:00",
"speaker": "Speaker Name",
"text": "Full paragraph text with proper punctuation."
}},
...
]
Return ONLY valid JSON, no other text."""
# Call Claude with full transcript
client = Client(model="claude-sonnet-4-5")
response = client(prompt)
response_string = str(response)
response_string[:100]
# # Parse JSON response
# sections_data = json.loads(response_string)
# # Print first 10 sections to check
# for section in sections_data[:10]:
# print(f"Section {section['section']}:")
# print(f"[{section['timestamp']}] {section['speaker']}: {section['text']}\n")
Should we run this?
I have decided to use the Claude SDK directly as the response data shape is easier to work with.
I have noticed that this request times out. So there are a few things we can do:
- We can split the transcript into smaller chunks and send them one by one to claude and stitch together the resonses.
- We can ask claude to only provide the sction headers and timestamps and speaker, and possibly also chapter headers where we ask claude to also split this into sensible chapters. Then on our side we use the raw segments and stitch them together and also add the timestamps and speaker name and title to each section. The issue here is we have to make sure that we create our own paragraphs and add all punction ourselves on our end making sure not to overlap text between sections and also not to miss any text.
Additionally output tokens are much more expensive than input tokens, so option 2 may be better, but only if it is reasonably achievable with good results.
🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠
Good analysis! I recommend Option 1 with smart chunking because:
Why not Option 2:
- Handling punctuation and paragraph formation is tricky and error-prone
- Risk of missing or overlapping text between sections
- More complex code to maintain
- The token savings won't be huge (section metadata vs full text isn't that different)
Better approach - Option 1 with chunking:
def chunk_transcript(segments, chunk_size_minutes=10, overlap_seconds=30):
"""Split transcript into time-based chunks with overlap"""
chunks = []
current_chunk = []
for seg in segments:
# Convert time to seconds
time_parts = seg['time'].split(':')
seconds = int(time_parts[0])*60 + float(time_parts[1].replace(',','.'))
# Add to current chunk
current_chunk.append(seg)
# Check if chunk is full
if seconds >= (len(chunks) + 1) * chunk_size_minutes * 60:
chunks.append(current_chunk)
# Start new chunk with overlap
current_chunk = [s for s in current_chunk
if get_seconds(s['time']) > seconds - overlap_seconds]
if current_chunk:
chunks.append(current_chunk)
return chunks
Then process each chunk separately and stitch results together, removing duplicates at boundaries.
Want to try this approach? It's cleaner and more reliable than Option 2.
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=10, overlap_seconds=30):
"""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
# Test it
chunks = chunk_transcript(segments, chunk_size_minutes=10)
print(f"Number of chunks: {len(chunks)}")
for i, chunk in enumerate(chunks):
print(f"Chunk {i+1}: {len(chunk)} segments, {chunk[0]['time']} to {chunk[-1]['time']}")
Number of chunks: 14
Chunk 1: 256 segments, 00:00:00,040 to 00:10:01,680
Chunk 2: 264 segments, 00:09:32,800 to 00:20:03,840
Chunk 3: 260 segments, 00:19:34,320 to 00:30:05,200
Chunk 4: 261 segments, 00:29:37,279 to 00:40:06,520
Chunk 5: 269 segments, 00:39:37,000 to 00:50:06,559
Chunk 6: 266 segments, 00:49:39,200 to 01:00:08,640
Chunk 7: 258 segments, 00:59:39,359 to 01:10:09,360
Chunk 8: 266 segments, 01:09:42,719 to 01:20:10,400
Chunk 9: 270 segments, 01:19:40,520 to 01:30:11,199
Chunk 10: 270 segments, 01:29:42,880 to 01:40:12,480
Chunk 11: 299 segments, 01:39:44,920 to 01:50:14,280
Chunk 12: 280 segments, 01:49:45,440 to 02:00:16,760
Chunk 13: 283 segments, 01:59:48,679 to 02:10:16,880
Chunk 14: 93 segments, 02:09:48,119 to 02:13:26,119
Ok update my anthropic script to use these chunks and make the requests all at once using threading. Then we can see about stitching them back together
Here's the updated script with threading:
import threading
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
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}
Break this chunk into logical sections based on:
- Topic changes or new concepts
- Significant new information
- Roughly 30-60 second sections if no natural breaks
For each section provide:
- Section number (continue from previous chunks if not first)
- 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
**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,
"timestamp": "00:00",
"speaker": "Speaker Name",
"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
}
print(f"Using {len(chunks)} chunks")
# Process all chunks in parallel
results = []
with ThreadPoolExecutor(max_workers=5) as executor:
futures = {
executor.submit(process_chunk, chunk, i, len(chunks)): i
for i, chunk in enumerate(chunks)
}
for future in as_completed(futures):
try:
result = future.result()
results.append(result)
print(f"Completed chunk {result['chunk_index']+1}/{len(chunks)}")
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")
results[0]['response'][:500] if results else "No results"
This will process all chunks in parallel. Want to run it and then we'll work on stitching the results together?
Ok these sections look pretty good, but one thing we overlooked was grouping the segments into meaningful chapters with a suitable heading for each chapter.
🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠
Good catch! Let's add chapter groupings. We have two options:
Option 1: Post-process the sections we have Send the section metadata (timestamps and brief text previews) to Claude and ask it to group them into chapters with headings. This is cheaper and faster.
Option 2: Re-process with chapter detection Go back and modify the prompt to also identify chapter breaks. This is more work.
I recommend Option 1. Here's how:
# Create a summary of all sections for chapter grouping
sections_summary = []
for section in all_sections:
sections_summary.append({
'section': section['section'],
'timestamp': section['timestamp'],
'preview': section['text'][:150] # First 150 chars
})
summary_text = json.dumps(sections_summary, indent=2)
chapter_prompt = f"""You are organizing a video transcript into chapters.
Here are {len(all_sections)} sections from a technical tutorial video with timestamps and text previews:
{summary_text}
Group these sections into logical chapters. Each chapter should cover a major topic or theme.
Return JSON:
[
{{
"chapter": 1,
"title": "Introduction to Tokenization",
"sections": [1, 2, 3, 4]
}},
...
]"""
chapter_response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4000,
messages=[{"role": "user", "content": chapter_prompt}]
)
chapter_response.content[0].text
Want to try this?
You're right, let's do it properly from the start. Here's the updated prompt that includes chapter detection:
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 30-60 second sections if no natural breaks
For each section provide:
- Section number
- 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,
"timestamp": "00:00",
"speaker": "Speaker Name",
"chapter_title": "Introduction to Tokenization",
"text": "Full paragraph text."
}},
{{
"section": 2,
"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
}
Now re-run the processing with this updated prompt:
print(f"Using {len(chunks)} chunks")
# Process all chunks in parallel
results = []
with ThreadPoolExecutor(max_workers=16) as executor:
futures = {
executor.submit(process_chunk, chunk, i, len(chunks)): i
for i, chunk in enumerate(chunks)
}
for future in as_completed(futures):
try:
result = future.result()
results.append(result)
print(f"Completed chunk {result['chunk_index']+1}/{len(chunks)}")
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")
Want to run this?
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
}
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from anthropic import Anthropic
client = Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
print(f"Using {len(chunks)} chunks")
# Process all chunks in parallel
results = []
with ThreadPoolExecutor(max_workers=16) as executor:
futures = {
executor.submit(process_chunk, chunk, i, len(chunks)): i
for i, chunk in enumerate(chunks)
}
for future in as_completed(futures):
try:
result = future.result()
results.append(result)
print(f"Completed chunk {result['chunk_index']+1}/{len(chunks)}")
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")
Using 14 chunks
Completed chunk 14/14
Completed chunk 10/14
Completed chunk 7/14
Completed chunk 1/14
Completed chunk 9/14
Completed chunk 6/14
Completed chunk 2/14
Completed chunk 4/14
Completed chunk 13/14
Completed chunk 5/14
Completed chunk 12/14
Completed chunk 3/14
Completed chunk 8/14
Completed chunk 11/14
Processed 14 chunks successfully
import json
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)
# 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
print(f"Total sections after stitching: {len(all_sections)}")
print(f"\nFirst 3 sections:")
for section in all_sections[:10]:
print(f"\nSection {section['section']}:")
print(f"[{section['timestamp']}] {section['speaker']}: {section['text']}")
Total sections after stitching: 190
First 3 sections:
Section 1:
[00:00] Speaker: Hi everyone, so in this video I'd like us to cover the process of tokenization in large language models. Now you see here that I have a sad face and that's because tokenization is my least favorite part of working with large language models, but unfortunately it is necessary to understand in some detail because it is fairly hairy, gnarly and there's a lot of hidden foot guns to be aware of, and a lot of oddness with large language models typically traces back to tokenization.
Section 2:
[00:26] Speaker: So what is tokenization? Now in my previous video 'Let's Build GPT from scratch' we actually already did tokenization, but we did a very naive simple version of tokenization. So when you go to the Google colab for that video, you see here that we loaded our training set and our training set was this Shakespeare dataset. Now in the beginning the Shakespeare dataset is just a large string in Python, it's just text, and so the question is how do we plug text into large language models?
Section 3:
[00:54] Speaker: And in this case here we created a vocabulary of 65 possible characters that we saw occur in this string. These were the possible characters and we saw that there are 65 of them, and then we created a lookup table for converting from every possible character, a little string piece, into a token, an integer. So here for example we tokenized the string 'Hi there' and we received this sequence of tokens.
Section 4:
[01:24] Speaker: And here we took the first 1,000 characters of our dataset and we encoded it into tokens, and because this is character level we received 1,000 tokens in a sequence. So token 18 etc. Now later we saw that the way we plug these tokens into the language model is by using an embedding table. And so basically if we have 65 possible tokens then this embedding table is going to have 65 rows, and roughly speaking we're taking the integer associated with every single token, we're using that as a lookup into this table and we're plucking out the corresponding row.
Section 5:
[02:04] Speaker: And this row is trainable parameters that we're going to train using back propagation, and this is the vector that then feeds into the transformer, and that's how the transformer sort of perceives every single token. So here we had a very naive tokenization process that was a character level tokenizer, but in practice in state-of-the-art language models people use a lot more complicated schemes unfortunately for constructing these token vocabularies. So we're not dealing on the character level, we're dealing on chunk level, and the way these character chunks are constructed is using algorithms such as for example the byte pair encoding algorithm which we're going to go into in detail and cover in this video.
Section 6:
[02:51] Speaker: I'd like to briefly show you the paper that introduced a byte level encoding as a mechanism for tokenization in the context of large language models, and I would say that's probably the GPT-2 paper. And if you scroll down here to the section input representation, this is where they cover tokenization, the kinds of properties that you'd like the tokenization to have, and they conclude here that they're going to have a tokenizer where you have a vocabulary of 50,257 possible tokens and the context size is going to be 1,024 tokens.
Section 7:
[03:24] Speaker: So in the attention layer of the transformer neural network, every single token is attending to the previous tokens in the sequence and it's going to see up to 1,024 tokens. So tokens are this like fundamental unit, the atom of large language models if you will, and everything is in units of tokens, everything is about tokens, and tokenization is the process for translating strings or text into sequences of tokens and vice versa. When you go into the Llama 2 paper as well I can show you that when you search 'token' you're going to get 63 hits, and that's because tokens are again pervasive. So here they mentioned that they trained on two trillion tokens of data and so on.
Section 8:
[04:11] Speaker: So we're going to build our own tokenizer. Luckily the byte pair encoding algorithm is not that super complicated and we can build it from scratch ourselves and we'll see exactly how this works. Before we dive into code I'd like to give you a brief taste of some of the complexities that come from the tokenization because I just want to make sure that we motivate it sufficiently for why we are doing all this and why this is so gross.
Section 9:
[04:32] Speaker: So tokenization is at the heart of a lot of weirdness in large language models and I would advise that you do not brush it off. A lot of the issues that may look like just issues with the neural network architecture or the large language model itself are actually issues with the tokenization and fundamentally trace back to it. So if you've noticed any issues with large language models, can't, you know, not able to do spelling tasks very easily, that's usually due to tokenization. Simple string processing can be difficult for the large language model to perform natively. Non-English languages can work much worse and to a large extent this is due to tokenization.
Section 10:
[05:06] Speaker: Sometimes LLMs are bad at simple arithmetic, also can be traced to tokenization. GPT-2 specifically would have had quite a bit more issues with Python than future versions of it due to tokenization. There's a lot of other issues, maybe you've seen weird warnings about a trailing whitespace, this is a tokenization issue. If you had asked GPT earlier about solid gold Magikarp and what it is, you would see the LLM go totally crazy and it would start going off about a completely unrelated tangent topic. Maybe you've been told to use YAML over JSON in structured data, all of that has to do with tokenization.
Good point! Let's update the stitching code to handle chapters:
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)
# 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)}")
print(f"\nChapters:")
for i, chapter in enumerate(chapters, 1):
print(f"\nChapter {i}: {chapter['title']}")
print(f" Sections: {len(chapter['sections'])}")
print(f" First section: [{chapter['sections'][0]['timestamp']}]")
if len(chapter['sections']) > 0:
print(f" Last section: [{chapter['sections'][-1]['timestamp']}]")
Run this to see the chapter structure!
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)
# 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)}")
print(f"\nChapters:")
for i, chapter in enumerate(chapters, 1):
print(f"\nChapter {i}: {chapter['title']}")
print(f" Sections: {len(chapter['sections'])}")
print(f" First section: [{chapter['sections'][0]['timestamp']}]")
if len(chapter['sections']) > 0:
print(f" Last section: [{chapter['sections'][-1]['timestamp']}]")
Total sections: 190
Total chapters: 10
Chapters:
Chapter 1: Introduction to Tokenization in Large Language Models
Sections: 24
First section: [00:00]
Last section: [13:56]
Chapter 2: Building a Tokenizer
Sections: 14
First section: [14:56]
Last section: [23:32]
Chapter 3: Byte Pair Encoding Algorithm
Sections: 23
First section: [23:49]
Last section: [39:19]
Chapter 4: Encoding and Decoding with Tokenizers
Sections: 24
First section: [39:37]
Last section: [56:44]
Chapter 5: Modern Tokenizers and GPT-2 Implementation
Sections: 4
First section: [57:51]
Last section: [59:58]
Chapter 6: Understanding the GPT-2 Regex Pattern
Sections: 26
First section: [59:39]
Last section: [01:17:49]
Chapter 7: Special Tokens and Vocabulary Structure
Sections: 13
First section: [01:18:26]
Last section: [01:28:14]
Chapter 8: SentencePiece Tokenization
Sections: 19
First section: [01:28:41]
Last section: [01:42:34]
Chapter 9: Vocabulary Size Design and Considerations
Sections: 13
First section: [01:43:28]
Last section: [01:49:57]
Chapter 10: Advanced Tokenization Applications and Issues
Sections: 30
First section: [01:49:45]
Last section: [02:12:37]
Ok we have the video, lets extract the screenthots in one cell please, but lets do it in a way that we can use threading/multiprocessing to speed up the process. Use up to 16 workers.
import subprocess
from pathlib import Path
import base64
from concurrent.futures import ThreadPoolExecutor, as_completed
def extract_screenshot(video_path, timestamp, section_num):
"""Extract screenshot at given timestamp using ffmpeg"""
try:
# Convert timestamp to seconds
seconds = get_seconds(timestamp)
# Create temp file for screenshot
output_path = 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', output_path
]
# Run silently
subprocess.run(cmd, capture_output=True, check=True, stderr=subprocess.DEVNULL)
# Read image and convert to base64
with open(output_path, 'rb') as f:
img_data = f.read()
img_b64 = base64.b64encode(img_data).decode('utf-8')
# Clean up temp file
Path(output_path).unlink()
return img_b64
except Exception as e:
print(f"Error extracting screenshot for section {section_num}: {e}")
return None
# Extract all screenshots in parallel
print(f"Extracting {len(all_sections)} screenshots using 16 workers...")
screenshots = {}
completed = 0
with ThreadPoolExecutor(max_workers=16) as executor:
futures = {
executor.submit(extract_screenshot, video_path, section['timestamp'], section['section']): section['section']
for section in all_sections
}
for future in as_completed(futures):
section_num = futures[future]
try:
img_b64 = future.result()
if img_b64:
screenshots[section_num] = img_b64
completed += 1
if completed % 25 == 0 or completed == len(all_sections):
print(f" Progress: {completed}/{len(all_sections)}")
except Exception as e:
print(f"Error for section {section_num}: {e}")
print(f"\n✓ Extracted {len(screenshots)}/{len(all_sections)} screenshots")
This will extract all screenshots in parallel using 16 workers and show progress every 25 screenshots.
import subprocess
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
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):
"""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 16 workers...")
with ThreadPoolExecutor(max_workers=16) 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 as_completed(futures):
section_num = futures[future]
try:
img_path = future.result()
if img_path:
screenshot_paths[section_num] = img_path
completed += 1
if completed % 25 == 0 or completed == len(all_sections):
print(f" Progress: {completed}/{len(all_sections)}")
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
all_screenshots = extract_all_screenshots(all_sections=all_sections, video_path='zduSFxRajkE.mp4')
print(f"Example path: {all_screenshots[1]}")
Ok we have the screenshots. Are we at the final step can we put all of the pieces together into a note message and add it to the dialog?
Yes! Final step - let's generate the markdown and add it to the dialog:
# Build markdown content
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"
# Generate markdown
markdown_lines = [f"# Video Transcript: {info.get('title', 'Video')}\n"]
markdown_lines.append(f"**Video ID**: {video_id}\n")
markdown_lines.append(f"**Duration**: {info.get('duration_string', 'Unknown')}\n")
for chapter_num, chapter in enumerate(chapters, 1):
# Add chapter heading
markdown_lines.append(f"\n## Chapter {chapter_num}: {chapter['title']}\n")
for section in chapter['sections']:
section_num = section['section']
timestamp = section['timestamp']
speaker = section['speaker']
text = section['text']
# Add section with timestamp link
yt_link = format_timestamp_link(timestamp, video_id)
markdown_lines.append(f"\n### Section {section_num} [[{timestamp}]({yt_link})]\n")
# Add screenshot if available
if section_num in screenshots:
markdown_lines.append(f'<img src="data:image/jpeg;base64,{screenshots[section_num]}" width="800" />\n')
# Add speaker and text
markdown_lines.append(f"**{speaker}**: {text}\n")
markdown_content = '\n'.join(markdown_lines)
print(f"Generated markdown with {len(markdown_lines)} lines")
print(f"Total size: {len(markdown_content) / 1024 / 1024:.2f} MB")
# Add to dialog using add_msg
add_msg(markdown_content, msg_type='note', placement='add_after')
print("\n✓ Transcript note added to dialog!")
This will create a beautiful formatted note with:
- Video title and metadata
- Chapters with headings
- Sections with clickable YouTube timestamp links
- Screenshots embedded as base64 images
- Speaker names and formatted text
Ready to run?
# Build markdown content
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(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" \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"✓ Added Chapter {chapter_num}/{len(chapters)}")
print(f"\n✓ Complete! Added {len(chapters)+1} messages to dialog")
add_transcript_msg_by_chapters('zduSFxRajkE', chapters, all_screenshots, info)