Skip to content

About

Turns a YouTube lecture into timestamped study notes with matching slide frames, using Gemini video understanding. Also has RAG Q&A, flashcards, quizzes and PDF/Markdown export in a Streamlit app.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

Β 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸŽ“ LectureLens

Multimodal Educational Video Understanding, Study Note Generation & Grounded Lecture Q&A

Python 3.11 | 3.12 License: MIT Streamlit FAISS

LectureLens transforms educational YouTube lectures into structured study guides with OpenCV-extracted slide images, active-recall revision tools, and an interactive, lecture-grounded Q&A assistant.


πŸ“Œ Table of Contents

  1. How the Pipeline Actually Works
  2. Key Features
  3. Architecture Overview
  4. Empirical Evaluation & Benchmarks
  5. System Requirements
  6. Installation & Setup
  7. Configuration (.env)
  8. How to Run
  9. Running Automated Tests
  10. Data Storage & Lecture Isolation
  11. Troubleshooting & Known Limitations

πŸ’‘ How the Pipeline Actually Works

It is important to understand the actual data flow of LectureLens:

  1. Direct Video Ingestion (No Caption/Transcript Dependencies):
    • Gemini watches and listens to the public YouTube video directly via its native multimodal API (google.genai.types.FileData(file_uri=url)).
    • There is no transcript scraping library (no youtube-transcript-api, no Whisper, no .srt parsing). Gemini directly analyzes spoken explanations, on-screen slides, diagrams, equations, and code demonstrations in a single end-to-end call, outputting a structured video_analysis.json.
  2. Timestamp Normalization & Boundary Clamping:
    • yt-dlp probes the verified video duration upfront, constraining Gemini's prompt and programmatically clamping any overrunning timestamps (0 <= start_time < end_time <= total_duration).
  3. Physical Slide & Keyframe Extraction:
    • yt-dlp temporarily streams lightweight video fragments into an isolated temporary directory. OpenCV (cv2.VideoCapture) seeks to each timestamp identified by Gemini, writes high-resolution JPEGs to disk, and saves visual_manifest.json. The temporary video is automatically deleted immediately afterward.
  4. Study Note Synthesis (From Analysis JSON, Not RAG):
    • Comprehensive study notes, key concepts, visual explanations, and revision flashcards are synthesized directly from video_analysis.json via Gemini text generationβ€”notes are not built from fragmented RAG chunks. Extracted slide JPEGs are programmatically attached to corresponding sections.
  5. Local Vector RAG (Used Strictly for Interactive Q&A):
    • Retrieval-Augmented Generation is used strictly for the interactive Q&A assistant tab. Chunks carrying section titles and timestamps are embedded locally using sentence-transformers/all-MiniLM-L6-v2 and indexed into an isolated FAISS IndexFlatIP store. When a student asks a question, the retriever extracts evidence passages, the Relevance Guard checks for topic boundaries, and Gemini generates a grounded answer with [MM:SS] timestamp citations.

πŸš€ Key Features

  • Direct Multimodal Video Understanding: Gemini analyzes the video directlyβ€”understanding spoken explanations, whiteboard drawings, slide text, and terminal code together.
  • Timestamp Integrity: Duration probing via yt-dlp and post-analysis clamping ensure timestamps never exceed the real video length.
  • Physical Keyframe Extraction: OpenCV extracts physical slide images at verified moments into permanent JPEG assets.
  • Grounded RAG Assistant (For Q&A):
    • Topic-aware sentence-preserving chunking with section metadata and timestamps.
    • Local dense vector embeddings via sentence-transformers/all-MiniLM-L6-v2 (384-d, normalized for cosine similarity).
    • Lecture-isolated FAISS (faiss-cpu) vector indexes with synchronized metadata.
    • Dual-phase Relevance Guard detecting in-scope, insufficient-evidence, and out-of-scope inquiries.
  • Revision & Self-Assessment Tools:
    • Active-recall concept flashcards with interactive reveal.
    • Grounded multiple-choice quizzes with automated grading, explanations, and timestamp references.
  • Publication-Quality Export: Export notes to Markdown or styled PDF (using ReportLab) with cover headers, callout boxes, and embedded diagrams.

πŸ—οΈ Architecture Overview

LectureLens/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.py                     # Streamlit web application & multi-tab UI
β”‚   β”œβ”€β”€ video_analyzer.py           # Gemini multimodal video analyzer & duration constraints
β”‚   β”œβ”€β”€ visual_extractor.py         # OpenCV frame extraction & manifest generator
β”‚   β”œβ”€β”€ note_generator.py           # Study note synthesizer & markdown converter
β”‚   β”œβ”€β”€ gemini_client.py            # Gemini client factory with automated model failover
β”‚   β”œβ”€β”€ rag/
β”‚   β”‚   β”œβ”€β”€ document_builder.py     # Section-to-document transformation
β”‚   β”‚   β”œβ”€β”€ chunker.py              # Sentence-preserving deterministic chunker
β”‚   β”‚   β”œβ”€β”€ embeddings.py           # Local SentenceTransformers (all-MiniLM-L6-v2) singleton
β”‚   β”‚   β”œβ”€β”€ vector_store.py         # FAISS IndexFlatIP inner-product store
β”‚   β”‚   β”œβ”€β”€ retriever.py            # Semantic retrieval & source citation
β”‚   β”‚   β”œβ”€β”€ relevance.py            # Dual-phase relevance guard & refusal handler
β”‚   β”‚   β”œβ”€β”€ answer_generator.py     # Grounded Gemini answer generator
β”‚   β”‚   └── pipeline.py             # End-to-end RAG coordinator (for Q&A)
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ lecture_service.py      # Multi-lecture lifecycle & legacy path sync
β”‚   β”‚   β”œβ”€β”€ quiz_service.py         # Flashcards and interactive quiz assessment
β”‚   β”‚   └── export_service.py       # Markdown and ReportLab PDF exporters
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   └── schemas.py              # Pydantic contracts & data models
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ config.py               # Centralized configuration & standard paths
β”‚   β”‚   β”œβ”€β”€ logging_config.py       # Secret-masked structured logging
β”‚   β”‚   └── validation.py           # URL parsing & timestamp normalization
β”‚   └── evaluations/
β”‚       └── evaluator.py            # Single-lecture benchmark test runner
β”œβ”€β”€ evals/                          # Empirical evaluation framework
β”‚   β”œβ”€β”€ measure_performance.py      # Multi-lecture timing & stage breakdown benchmark
β”‚   β”œβ”€β”€ faithfulness_check.py       # Auto-judged sampled evidence faithfulness suite
β”‚   └── results/
β”‚       β”œβ”€β”€ performance_metrics.json# Raw per-stage latency & call counts
β”‚       └── faithfulness_report.json# Raw statement-by-statement evidence verdicts
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ analysis/                   # Active lecture analysis JSON
β”‚   β”œβ”€β”€ notes/                      # Active study notes (JSON, MD, PDF)
β”‚   β”œβ”€β”€ visuals/                    # Extracted slide images & visual_manifest.json
β”‚   β”œβ”€β”€ indexes/                    # FAISS vector indexes (<lecture_id>/index.faiss)
β”‚   β”œβ”€β”€ lectures/                   # Isolated multi-lecture archives (<lecture_id>/...)
β”‚   └── evaluations/                # Evaluator metrics CSV and JSON
β”œβ”€β”€ tests/                          # Automated unit, integration, and regression tests
β”œβ”€β”€ requirements.txt                # Python dependencies
β”œβ”€β”€ .env.example                    # Environment template
β”œβ”€β”€ EVALS.md                        # Complete benchmark reproduction guide
└── AGENTS.md                       # Persistent engineering rules

For more details, see docs/architecture.md.


πŸ“Š Empirical Evaluation & Benchmarks

All benchmark metrics are generated by automated scripts in evals/ running on real, public YouTube educational lectures. Complete details and raw JSON outputs are documented in EVALS.md.

1. Processing Latency & Stage Breakdown

Measured using evals/measure_performance.py across technical lectures ranging from 2 to 22 minutes (Raw data: evals/results/performance_metrics.json):

Lecture Topic Duration Total Time 1. Metadata Probe 2. Gemini Video Understanding 3. Frame Extraction (OpenCV) 4. Note Synthesis (Gemini Text) 5. Local FAISS RAG Indexing Frames Extracted Chunks Indexed
Neuroscience Intro 02:20 (140s) 89.94s 1.77s 47.78s 6.20s 10.83s 23.36s* 5 3
Agentic AI Architecture 13:49 (829s) 118.51s 1.91s 84.64s 13.63s 17.37s 0.94s 25 10
Model Context Protocol 21:57 (1,317s) 116.13s 1.76s 71.63s 21.20s 20.75s 0.78s 23 10
Aggregates (3 Lectures) Median: 13:49 Median: 116.13s Median: 1.77s Median: 71.63s Median: 13.63s Median: 17.37s Median: 0.94s Total: 53 Total: 23

*Note: Stage 5 for Lecture 1 included cold-start memory allocation and model weight caching for SentenceTransformers.

  • Completion Rate: 100.0% (3/3) successful end-to-end runs without errors.
  • API Call Budget: Exactly 2 Gemini API calls per lecture (1 video call + 1 text call). Zero external embedding API calls.

2. Evidence Faithfulness Spot-Check (Auto-Judged)

Measured using evals/faithfulness_check.py by randomly sampling 10 factual statements per lecture (seed=42) across 4 lectures ($N=40$ total statements) and auto-judging each statement against the ground-truth spoken content and slide descriptions (Raw data: evals/results/faithfulness_report.json):

Lecture ID Topic Sampled Statements Strictly Supported Partially Supported (Extrapolations) Unsupported (Hallucinations) Faithfulness Rate (Strict) Plausible Rate (Supported + Partial)
sample_node_lecture Node.js Fundamentals 10 10 0 0 100.0% 100.0%
yt_AUYtP6kVrQk Neuroscience Intro 10 8 2 0 80.0% 100.0%
yt_GeVCpohRU8Y Model Context Protocol 10 8 2 0 80.0% 100.0%
yt_15_pppse4fY Agentic AI Systems 10 3 3 4 30.0% 60.0%
Total / Macro Metric Diverse Technical Lectures 40 29 7 4 72.5% 90.0%

Audit Note on Weak Results: The Agentic AI lecture scored lower (30% strict / 60% plausible) because the note generator hallucinated an external 4-part agent taxonomy into Section 2 ("Tool-Augmented Chatbots"), where the instructor was actually explaining why tool-augmented chatbots are not agentic. The LLM blended external background knowledge about agents into early introductory sections.

3. Single-Lecture Retrieval Baseline

  • Dataset Scope: 13 hand-written questions on one 7-minute lecture (sample_node_lecture), not a general benchmark.
  • Results on this specific sample: HitRate@4: 1.0, MRR: 1.0, Retrieval Latency: ~12.7 ms. Run via python src/evaluations/evaluator.py.

πŸ’» System Requirements

  • Operating System: Windows 10/11, macOS, or Linux.
  • Python Version: Python 3.11 or 3.12 (Recommended). (Note: Python 3.13 on Windows has known OpenMP DLL initialization conflicts with faiss-cpu under test runners like pytest).
  • Memory (RAM): 4 GB minimum (8 GB recommended for local embedding model).
  • Disk Space: ~500 MB for Python packages and local embedding model cache.
  • Network: Internet access for YouTube metadata probing, Gemini API calls, and temporary frame extraction downloads.

πŸ“¦ Installation & Setup

1. Clone the Repository

git clone https://github.com/Bhakti-debug/LectureLens.git
cd LectureLens

2. Create and Activate a Virtual Environment

Windows (PowerShell):

python -m venv .venv
.\.venv\Scripts\Activate.ps1

macOS / Linux:

python3 -m venv .venv
source .venv/bin/activate

3. Install Dependencies

python -m pip install --upgrade pip
pip install -r requirements.txt

βš™οΈ Configuration (.env)

Copy .env.example to create your local .env:

cp .env.example .env

Configure your API key and preferences:

# Gemini API Configuration
GEMINI_API_KEY=your_actual_gemini_api_key_here
GEMINI_MODEL=gemini-3.7-flash

# RAG & Local Embedding Configuration (Used strictly for Q&A)
EMBEDDING_MODEL=all-MiniLM-L6-v2
CHUNK_SIZE=400
CHUNK_OVERLAP=60
RETRIEVAL_TOP_K=4
RELEVANCE_SIMILARITY_THRESHOLD=0.35

# Application & Logging
LOG_LEVEL=INFO

πŸš€ How to Run

Run the Streamlit Application

streamlit run src/main.py

Streamlit will launch locally at http://localhost:8501.

End-to-End Workflow in the UI:

  1. Analyze a New Lecture: Paste any public YouTube link in the top expander and click πŸš€ Analyze Lecture.
  2. πŸ“– Study Notes & Visuals: Read the lecture overview, chronological sections with timestamps, key concepts, and extracted slide images.
  3. πŸ’¬ Lecture Q&A Assistant: Ask conceptual questions grounded in the lecture. Inspect retrieved evidence passages and timestamp citations.
  4. πŸ—‚οΈ Revision Flashcards: Test memory recall with interactive concept flashcards.
  5. πŸ“ Self-Assessment Quiz: Answer multiple-choice questions with automated grading and explanations.
  6. πŸ“₯ Export Study Material: Download publication-ready .md or styled .pdf documents.
  7. Switch Lectures: Use the sidebar dropdown to switch between previously analyzed lectures without mixing indexes or chat history.

πŸ§ͺ Running Automated Tests

Run the unit, integration, and regression test suite:

pytest -v tests/test_validation.py tests/test_chunker.py tests/test_study_tools.py tests/test_export.py tests/test_regression.py

πŸ”’ Data Storage & Lecture Isolation

All artifacts are persisted in lecture-scoped directories:

  • Analysis: data/lectures/<lecture_id>/video_analysis.json
  • Visuals: data/lectures/<lecture_id>/visuals/ and visual_manifest.json
  • Notes: data/lectures/<lecture_id>/study_notes.json and study_notes.md
  • Vector Indexes: data/indexes/<lecture_id>/index.faiss and metadata.json

πŸ› οΈ Troubleshooting & Known Limitations

  1. Video Accessibility:
    • Gemini analyzes public YouTube videos directly via URL. Age-restricted, private, or regional-blocked videos will fail with 403 PERMISSION_DENIED.
  2. API Quota Management:
    • Free-tier Gemini accounts have a limit of 15 RPM. The client includes automatic retry and model failover (gemini_client.py) across candidate models to protect against 429 RESOURCE_EXHAUSTED.
  3. No Closed-Caption Dependency:
    • Because Gemini listens to the audio track directly, videos without spoken narration (pure background music or silent slides) will result in minimal spoken content.
  4. Local Vector Search Scope:
    • The vector store indexes structured text representations (spoken content, slide descriptions, on-screen text). Direct visual vector search (CLIP / SigLIP) is a planned future enhancement.

About

Turns a YouTube lecture into timestamped study notes with matching slide frames, using Gemini video understanding. Also has RAG Q&A, flashcards, quizzes and PDF/Markdown export in a Streamlit app.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages