<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Revolutionizing Video Consumption]]></title><description><![CDATA[Revolutionizing Video Consumption]]></description><link>https://youtubeassistant.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 20:37:55 GMT</lastBuildDate><atom:link href="https://youtubeassistant.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Revolutionizing Video Consumption: Building a YouTube Video Summarizer with RAG and Gemini AI]]></title><description><![CDATA[Discover how a YouTube Video Summarizer uses RAG and Gemini AI to enhance video engagement through concise summaries and interactive Q&A]]></description><link>https://youtubeassistant.hashnode.dev/revolutionizing-video-consumption-building-a-youtube-video-summarizer-with-rag-and-gemini-ai</link><guid isPermaLink="true">https://youtubeassistant.hashnode.dev/revolutionizing-video-consumption-building-a-youtube-video-summarizer-with-rag-and-gemini-ai</guid><category><![CDATA[gemini]]></category><category><![CDATA[RAG ]]></category><dc:creator><![CDATA[Sagar Mondal]]></dc:creator><pubDate>Thu, 17 Apr 2025 19:21:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744917636314/6a004da2-50c4-4dde-8c64-080f43aaf0d9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today’s fast-paced digital world, YouTube is a treasure trove of knowledge, entertainment, and inspiration. From tutorials to documentaries, the platform hosts millions of hours of content. But with this abundance comes a challenge: <strong>how do you extract the essence of a video without spending hours watching it?</strong> This is where our <strong>YouTube Video Summarizer with Retrieval-Augmented Generation (RAG) and Google’s Gemini AI</strong> comes in—a powerful tool designed to distill lengthy videos into concise, structured summaries and enable interactive question-answering, saving time and boosting productivity.</p>
<p>In this blog post, we’ll explore the problem of information overload in video content, how generative AI solves it, and how we built a Python-based summarizer using RAG, Pinecone, and Gemini AI. We’ll dive into code snippets to show the implementation, discuss the technology’s limitations, and envision future possibilities. Whether you’re a student, researcher, or content consumer, this project showcases the transformative potential of AI in making video content more accessible.</p>
<h2 id="heading-the-problem-information-overload-in-video-content">The Problem: Information Overload in Video Content</h2>
<p>YouTube videos are a rich source of information, but their length and unstructured nature can be overwhelming. Imagine you’re a student needing key insights from a 30-minute lecture, a professional seeking takeaways from a conference talk, or a hobbyist exploring a tutorial series. Watching every minute isn’t always feasible, especially when you’re juggling deadlines or need answers fast.</p>
<p><strong>The core problem is time inefficiency.</strong> Manually watching videos to extract key points is slow, and skimming risks missing critical information. While some videos offer transcripts, these are often long, unformatted, and hard to navigate. Existing summarization tools may provide generic overviews but often lack depth, context, or the ability to answer specific questions about the content.</p>
<p>This is where <strong>generative AI</strong>, combined with <strong>Retrieval-Augmented Generation (RAG)</strong>, offers a solution. By leveraging AI to process transcripts, retrieve relevant context, and generate structured summaries, we can transform how users interact with video content. Our project addresses this by:</p>
<ul>
<li><p><strong>Summarizing videos</strong> into concise, JSON-formatted outputs with titles, key points, and topics.</p>
</li>
<li><p><strong>Enabling question-answering</strong> to dive deeper into specific aspects of the video.</p>
</li>
<li><p><strong>Handling long transcripts</strong> to ensure scalability for extended content.</p>
</li>
</ul>
<h2 id="heading-how-generative-ai-solves-the-problem">How Generative AI Solves the Problem</h2>
<p>Generative AI, particularly large language models (LLMs) like Google’s <strong>Gemini 1.5 Pro</strong>, excels at understanding and synthesizing text. By combining Gemini with RAG—a technique that enhances LLMs with external knowledge retrieval—we can create a system that:</p>
<ol>
<li><p><strong>Extracts and processes</strong> YouTube video transcripts.</p>
</li>
<li><p><strong>Stores embeddings</strong> in a vector database (Pinecone) for efficient retrieval.</p>
</li>
<li><p><strong>Retrieves relevant context</strong> to augment summarization and question-answering.</p>
</li>
<li><p><strong>Generates structured outputs</strong> that are easy to read and query.</p>
</li>
<li><p><strong>Evaluates output quality</strong> to ensure accuracy and clarity.</p>
</li>
</ol>
<p>The use case is clear: <strong>save time and gain insights faster.</strong> Students can get lecture summaries in seconds, professionals can extract actionable insights from webinars, and hobbyists can focus on the most relevant parts of tutorials. The question-answering feature adds interactivity, allowing users to ask, “What are the key features of Gemini 2.0 Flash?” or “How does the video explain multimodal AI?” and receive precise answers based on the transcript.</p>
<h2 id="heading-building-the-youtube-video-summarizer">Building the YouTube Video Summarizer</h2>
<p>Our project, developed as a capstone for a 5-day Gen AI intensive course, is a Python-based Jupyter notebook that integrates several cutting-edge technologies:</p>
<ul>
<li><p><strong>YouTube Transcript API</strong> and <strong>Pytubefix</strong> for extracting video metadata and transcripts.</p>
</li>
<li><p><strong>Pinecone</strong> for storing transcript embeddings in a vector database.</p>
</li>
<li><p><strong>Google’s Gemini 1.5 Pro</strong> for summarization, question-answering, and evaluation.</p>
</li>
<li><p><strong>LangChain</strong> for managing RAG pipelines and embeddings.</p>
</li>
<li><p><strong>Matplotlib</strong> for visualizing evaluation results.</p>
</li>
</ul>
<p>Below, we’ll walk through the key components, share code snippets, and explain how they work together.</p>
<h3 id="heading-1-extracting-video-metadata-and-transcripts">1. Extracting Video Metadata and Transcripts</h3>
<p>The first step is to fetch the video’s metadata (title, channel, views, etc.) and transcript. We use <code>pytubefix</code> for metadata and <code>YouTubeTranscriptApi</code> for transcripts, with robust error handling for unavailable data.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">extract_video_details</span>(<span class="hljs-params">video_url</span>):</span>
    <span class="hljs-string">"""Extracts metadata from a YouTube video URL with robust error handling."""</span>
    <span class="hljs-keyword">try</span>:
        video_id = re.findall(<span class="hljs-string">r'(?:v=|\\/)([0-9A-Za-z_-]{11}).*'</span>, video_url)[<span class="hljs-number">0</span>]
        yt = YouTube(video_url)
        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">'title'</span>: yt.title,
            <span class="hljs-string">'channel'</span>: yt.author,
            <span class="hljs-string">'publish_date'</span>: yt.publish_date,
            <span class="hljs-string">'views'</span>: yt.views,
            <span class="hljs-string">'description'</span>: yt.description,
            <span class="hljs-string">'length'</span>: yt.length,
            <span class="hljs-string">'thumbnail'</span>: yt.thumbnail_url,
            <span class="hljs-string">'video_id'</span>: video_id
        }
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"Error extracting video details: <span class="hljs-subst">{e}</span>"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_transcript</span>(<span class="hljs-params">video_id</span>):</span>
    <span class="hljs-string">"""Fetches the transcript for a given YouTube video ID with fallback."""</span>
    <span class="hljs-keyword">try</span>:
        transcript_data = YouTubeTranscriptApi.get_transcript(video_id)
        <span class="hljs-keyword">return</span> <span class="hljs-string">" "</span>.join([entry[<span class="hljs-string">'text'</span>] <span class="hljs-keyword">for</span> entry <span class="hljs-keyword">in</span> transcript_data])
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"Transcript fetch error: <span class="hljs-subst">{e}</span>"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Transcript unavailable."</span>
</code></pre>
<p>This code ensures we have the raw data needed for summarization, displayed in a user-friendly HTML format with the video’s thumbnail.</p>
<h3 id="heading-2-building-the-rag-pipeline-with-pinecone">2. Building the RAG Pipeline with Pinecone</h3>
<p>To enable RAG, we split the transcript into chunks, convert them into embeddings using Google’s <code>text-embedding-004</code> model, and store them in a Pinecone vector database. The <code>create_vector_index</code> function handles this process, ensuring the index name is sanitized to meet Pinecone’s requirements.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sanitize_index_name</span>(<span class="hljs-params">name</span>):</span>
    <span class="hljs-string">"""Sanitizes a string to meet Pinecone's index name requirements."""</span>
    name = name.lower()
    name = re.sub(<span class="hljs-string">r'[^a-z0-9-]'</span>, <span class="hljs-string">'-'</span>, name)
    name = re.sub(<span class="hljs-string">r'-+'</span>, <span class="hljs-string">'-'</span>, name)
    name = name.strip(<span class="hljs-string">'-'</span>)
    <span class="hljs-keyword">return</span> name <span class="hljs-keyword">or</span> <span class="hljs-string">"default-index"</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_vector_index</span>(<span class="hljs-params">transcript, video_info</span>):</span>
    <span class="hljs-string">"""Creates and populates a Pinecone index with transcript embeddings."""</span>
    index_name = sanitize_index_name(<span class="hljs-string">f"youtube-rag-<span class="hljs-subst">{video_info[<span class="hljs-string">'video_id'</span>]}</span>"</span>)
    pc = Pinecone(api_key=os.environ[<span class="hljs-string">"PINECONE_API_KEY"</span>])
    spec = ServerlessSpec(cloud=<span class="hljs-string">"aws"</span>, region=<span class="hljs-string">"us-east-1"</span>)

    <span class="hljs-keyword">if</span> index_name <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> [index_info[<span class="hljs-string">"name"</span>] <span class="hljs-keyword">for</span> index_info <span class="hljs-keyword">in</span> pc.list_indexes()]:
        pc.create_index(index_name, dimension=<span class="hljs-number">768</span>, metric=<span class="hljs-string">'dotproduct'</span>, spec=spec)
        <span class="hljs-keyword">while</span> <span class="hljs-keyword">not</span> pc.describe_index(index_name).status[<span class="hljs-string">'ready'</span>]:
            time.sleep(<span class="hljs-number">1</span>)

    index = pc.Index(index_name)
    chunks = preprocess_transcript(transcript)
    data = pd.DataFrame({
        <span class="hljs-string">'chunk_id'</span>: [<span class="hljs-string">f"<span class="hljs-subst">{video_info[<span class="hljs-string">'video_id'</span>]}</span>-<span class="hljs-subst">{i}</span>"</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(chunks))],
        <span class="hljs-string">'text'</span>: chunks,
        <span class="hljs-string">'title'</span>: [video_info[<span class="hljs-string">'title'</span>]] * len(chunks),
        <span class="hljs-string">'source'</span>: [<span class="hljs-string">f"https://www.youtube.com/watch?v=<span class="hljs-subst">{video_info[<span class="hljs-string">'video_id'</span>]}</span>"</span>] * len(chunks)
    })

    embed_model = GoogleGenerativeAIEmbeddings(model=<span class="hljs-string">"models/text-embedding-004"</span>, google_api_key=GOOGLE_API_KEY)
    batch_size = <span class="hljs-number">100</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, len(data), batch_size):
        batch = data.iloc[i:i + batch_size]
        ids = batch[<span class="hljs-string">'chunk_id'</span>].tolist()
        texts = batch[<span class="hljs-string">'text'</span>].tolist()
        embeds = embed_model.embed_documents(texts)
        metadata = [{<span class="hljs-string">'text'</span>: row[<span class="hljs-string">'text'</span>], <span class="hljs-string">'source'</span>: row[<span class="hljs-string">'source'</span>], <span class="hljs-string">'title'</span>: row[<span class="hljs-string">'title'</span>]} <span class="hljs-keyword">for</span> _, row <span class="hljs-keyword">in</span> batch.iterrows()]
        index.upsert(vectors=list(zip(ids, embeds, metadata)))

    <span class="hljs-keyword">return</span> PineconeVectorStore(index_name=index_name, embedding=embed_model, namespace=<span class="hljs-literal">None</span>)
</code></pre>
<p>This sets up the vector store, enabling efficient retrieval of transcript chunks for summarization and question-answering.</p>
<h3 id="heading-3-generating-structured-summaries-with-rag">3. Generating Structured Summaries with RAG</h3>
<p>The <code>summarize_video_with_rag</code> function uses RAG to enhance summarization. It retrieves relevant transcript chunks, augments the prompt with context, and generates a JSON-formatted summary using Gemini AI with few-shot prompting.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_rag_summary</span>(<span class="hljs-params">query, transcript_chunk, vectorstore, model</span>):</span>
    <span class="hljs-string">"""Generates a summary using RAG to retrieve relevant context."""</span>
    results = vectorstore.similarity_search(query, k=<span class="hljs-number">3</span>)
    source_knowledge = <span class="hljs-string">"\n"</span>.join([x.page_content <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> results])
    prompt = <span class="hljs-string">f"""
Using the context below, generate a structured summary for the transcript chunk.

Context:
<span class="hljs-subst">{source_knowledge}</span>

<span class="hljs-subst">{create_summary_prompt(transcript_chunk)}</span>
"""</span>
    response = model.generate_content(prompt)
    summary_text = response.text
    json_match = re.search(<span class="hljs-string">r'\{.*\}'</span>, summary_text, re.DOTALL)
    <span class="hljs-keyword">return</span> json.loads(json_match.group(<span class="hljs-number">0</span>)) <span class="hljs-keyword">if</span> json_match <span class="hljs-keyword">else</span> {<span class="hljs-string">"error"</span>: <span class="hljs-string">"No JSON found"</span>}
</code></pre>
<p>For long transcripts, the function chunks the content and combines partial summaries into a cohesive output. The result is a structured summary like this (for a video on Gemini 2.0 Flash):</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Gemini 2.0 Flash Experimental Launch"</span>,
  <span class="hljs-attr">"key_points"</span>: [
    <span class="hljs-string">"Gemini 2.0 Flash is a multimodal model handling text, images, audio, and video."</span>,
    <span class="hljs-string">"Features enhanced reasoning, tool use, and Multimodal Live API for real-time interactions."</span>,
    <span class="hljs-string">"Twice as fast as Gemini 1.5 Pro with improved spatial understanding."</span>
  ],
  <span class="hljs-attr">"main_topics"</span>: [<span class="hljs-string">"Gemini"</span>, <span class="hljs-string">"Multimodal AI"</span>, <span class="hljs-string">"AI Development"</span>],
  <span class="hljs-attr">"summary"</span>: <span class="hljs-string">"Google launched Gemini 2.0 Flash Experimental, a multimodal LLM with advanced reasoning, tool integration, and real-time interaction capabilities."</span>
}
</code></pre>
<h3 id="heading-4-interactive-question-answering">4. Interactive Question-Answering</h3>
<p>To make the system interactive, we added a question-answering feature. The <code>ask_question_on_transcript</code> function retrieves relevant transcript chunks and generates answers using Gemini AI.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">ask_question_on_transcript</span>(<span class="hljs-params">question, vectorstore, video_info, model</span>):</span>
    <span class="hljs-string">"""Answers a user question about the YouTube video transcript using RAG."""</span>
    results = vectorstore.similarity_search(question, k=<span class="hljs-number">3</span>)
    context = <span class="hljs-string">"\n"</span>.join([doc.page_content <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> results])
    prompt = <span class="hljs-string">f"""
You are an expert assistant answering questions about a YouTube video titled "<span class="hljs-subst">{video_info[<span class="hljs-string">'title'</span>]}</span>" by <span class="hljs-subst">{video_info[<span class="hljs-string">'channel'</span>]}</span>.
Based on the following transcript excerpts, answer the question concisely and accurately.

Transcript Excerpts:
<span class="hljs-subst">{context}</span>

Question: <span class="hljs-subst">{question}</span>

Answer:
"""</span>
    response = model.generate_content(prompt)
    <span class="hljs-keyword">return</span> {
        <span class="hljs-string">"question"</span>: question,
        <span class="hljs-string">"answer"</span>: response.text.strip(),
        <span class="hljs-string">"context"</span>: context
    }
</code></pre>
<p>For example, asking “What are the key features of Gemini 2.0 Flash?” yields:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"question"</span>: <span class="hljs-string">"What are the key features of Gemini 2.0 Flash?"</span>,
  <span class="hljs-attr">"answer"</span>: <span class="hljs-string">"Gemini 2.0 Flash supports multimodal inputs (text, images, audio, video), offers enhanced reasoning, tool integration (Google Search, code execution), real-time interactions via the Multimodal Live API, image generation, and advanced text-to-speech."</span>,
  <span class="hljs-attr">"context"</span>: <span class="hljs-string">"Gemini 2.0 Flash Experimental, a multimodal LLM capable of processing and generating text, images, audio, and video..."</span>
}
</code></pre>
<h3 id="heading-5-evaluating-summary-quality">5. Evaluating Summary Quality</h3>
<p>To ensure high-quality summaries, we use Gemini AI to evaluate them on accuracy, completeness, conciseness, and clarity, visualized with a radar chart.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">evaluate_summary</span>(<span class="hljs-params">summary, transcript</span>):</span>
    <span class="hljs-string">"""Evaluates the quality of the generated summary."""</span>
    model = genai.GenerativeModel(<span class="hljs-string">'gemini-1.5-pro'</span>)
    evaluation_prompt = <span class="hljs-string">f"""
You are an expert in text summary evaluation. Evaluate the following summary based on the transcript excerpt.

Transcript (excerpt):
<span class="hljs-subst">{transcript[:<span class="hljs-number">2000</span>]}</span>... [truncated]

Generated Summary:
<span class="hljs-subst">{json.dumps(summary, indent=<span class="hljs-number">2</span>)}</span>

Evaluate on these criteria:
1. Accuracy: Does the summary accurately reflect the transcript's main points?
2. Completeness: Does it cover all key information?
3. Conciseness: Is it brief yet informative?
4. Clarity: Is it well-structured and easy to understand?

For each criterion, provide a score (1-10) and a brief explanation. Include an overall score and suggest 1-2 improvements. Return the evaluation in JSON format:

{{
  "accuracy": {{"score": 0, "explanation": ""}},
  "completeness": {{"score": 0, "explanation": ""}},
  "conciseness": {{"score": 0, "explanation": ""}},
  "clarity": {{"score": 0, "explanation": ""}},
  "overall": {{"score": 0, "explanation": ""}},
  "improvements": []
}}
"""</span>
    response = model.generate_content(evaluation_prompt)
    json_match = re.search(<span class="hljs-string">r'\{.*\}'</span>, response.text, re.DOTALL)
    <span class="hljs-keyword">return</span> json.loads(json_match.group(<span class="hljs-number">0</span>)) <span class="hljs-keyword">if</span> json_match <span class="hljs-keyword">else</span> {<span class="hljs-string">"error"</span>: <span class="hljs-string">"No JSON found"</span>}
</code></pre>
<p>This ensures users can trust the summaries, with scores visualized to highlight strengths and areas for improvement.</p>
<h2 id="heading-limitations-of-the-approach">Limitations of the Approach</h2>
<p>While powerful, the system has limitations:</p>
<ul>
<li><p><strong>Transcript Dependency</strong>: The tool relies on accurate, available transcripts. Videos without transcripts or with poor-quality captions (e.g., auto-generated) cannot be summarized effectively.</p>
</li>
<li><p><strong>Context Window Constraints</strong>: Long transcripts are chunked to fit Gemini’s context window, which may lead to loss of nuanced connections across chunks.</p>
</li>
<li><p><strong>Language Support</strong>: Currently, it processes English transcripts. Non-English videos require translation or multilingual model support.</p>
</li>
<li><p><strong>Visual Content</strong>: The system focuses on textual transcripts, ignoring visual elements (e.g., slides, demonstrations) that may carry critical information.</p>
</li>
<li><p><strong>API Costs and Limits</strong>: Pinecone and Gemini API usage incurs costs, and rate limits may restrict high-volume processing.</p>
</li>
<li><p><strong>Evaluation Subjectivity</strong>: The AI-based evaluation may vary in scoring consistency, depending on the model’s interpretation of criteria.</p>
</li>
</ul>
<h2 id="heading-future-art-of-the-possible">Future Art-of-the-Possible</h2>
<p>The future of AI-driven video summarization is exciting, with several possibilities:</p>
<ul>
<li><p><strong>Multimodal Analysis</strong>: Integrate computer vision to analyze video frames, capturing information from slides, charts, or on-screen text. Models like Gemini could process both audio and visual inputs for richer summaries.</p>
</li>
<li><p><strong>Multilingual Support</strong>: Extend the system to handle non-English transcripts using multilingual embeddings and translation APIs.</p>
</li>
<li><p><strong>Personalized Summaries</strong>: Allow users to customize summary length, focus (e.g., technical details vs. high-level overview), or output format (e.g., bullet points, paragraphs).</p>
</li>
<li><p><strong>Real-Time Summarization</strong>: Develop a streaming version that summarizes live YouTube streams or webinars in real-time.</p>
</li>
<li><p><strong>Cross-Video Insights</strong>: Use topic modeling to analyze multiple videos on a subject, identifying trends or synthesizing knowledge across sources.</p>
</li>
<li><p><strong>User Feedback Loop</strong>: Incorporate user ratings or corrections to fine-tune summaries and improve model performance over time.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Our YouTube Video Summarizer with RAG and Gemini AI tackles the problem of information overload by transforming lengthy videos into concise, actionable insights. By combining transcript extraction, vector database retrieval, and generative AI, it saves time and empowers users to engage with content efficiently. The question-answering feature adds interactivity, making it a versatile tool for students, professionals, and curious minds.</p>
<p>While limitations like transcript dependency and language support exist, the foundation is set for exciting advancements. From multimodal analysis to real-time summarization, the art-of-the-possible is vast. This project, built as a capstone for a Gen AI course, demonstrates the power of AI to make knowledge more accessible—and it’s just the beginning.</p>
<p>Try it yourself by creating a copy of my kaggle nptebook and or running it. Share your thoughts and let’s explore how AI can reshape how we consume video content!</p>
<hr />
<p><em>Built with Python, Google Gemini 1.5 Pro, Pinecone, LangChain, and a passion for making knowledge accessible. Published on April 18, 2025.</em></p>
]]></content:encoded></item></channel></rss>