Spaces:
Runtime error
Runtime error
Download app.py from DeftDaedalus/RAGVid: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/spaces/DeftDaedalus/RAGVid/resolve/main/app.py
- Command line
-
hf download hf://spaces/DeftDaedalus/RAGVid/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DeftDaedalus/RAGVid/resolve/main/app.py
10.4 kB
| import streamlit as st | |
| import yt_dlp | |
| import os | |
| import re | |
| import tempfile | |
| import numpy as np | |
| from groq import Groq | |
| try: | |
| from faster_whisper import WhisperModel | |
| WHISPER_AVAILABLE = True | |
| except ImportError: | |
| WHISPER_AVAILABLE = False | |
| try: | |
| import faiss | |
| from sentence_transformers import SentenceTransformer | |
| FAISS_AVAILABLE = True | |
| except ImportError: | |
| FAISS_AVAILABLE = False | |
| st.set_page_config(page_title="VidRAG", page_icon="π¬", layout="wide") | |
| st.title("π¬ VidRAG") | |
| st.caption("Paste a YouTube URL β get a summary β chat with the transcript") | |
| with st.sidebar: | |
| st.header("βοΈ Settings") | |
| groq_key = st.text_input("Groq API Key", type="password", | |
| placeholder="gsk_...", | |
| help="See README for how to get your free key") | |
| st.divider() | |
| use_whisper = st.toggle("ποΈ Force Whisper transcription", value=False, | |
| disabled=not WHISPER_AVAILABLE) | |
| whisper_model_size = "tiny" | |
| if WHISPER_AVAILABLE: | |
| whisper_model_size = st.selectbox("Whisper model size", | |
| ["tiny", "base", "small"], index=0, | |
| disabled=not use_whisper) | |
| groq_model = st.selectbox("Groq model", | |
| ["llama-3.3-70b-versatile", | |
| "llama3-8b-8192", | |
| "mixtral-8x7b-32768"], index=0) | |
| chunk_size = st.slider("Chunk size (words)", 100, 500, 200) | |
| top_k = st.slider("RAG top-k chunks", 1, 8, 3) | |
| if not FAISS_AVAILABLE: | |
| st.warning("faiss not installed β using keyword search fallback") | |
| if not WHISPER_AVAILABLE: | |
| st.info("faster-whisper not installed β Whisper fallback disabled") | |
| # ββ helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def clean_vtt(vtt: str) -> str: | |
| lines = vtt.splitlines() | |
| seen, out = set(), [] | |
| for line in lines: | |
| line = line.strip() | |
| if not line or line.startswith("WEBVTT") or "-->" in line: | |
| continue | |
| line = re.sub(r"<[^>]+>", "", line) | |
| line = re.sub(r"\d+:\d+:\d+\.\d+", "", line).strip() | |
| if line and line not in seen: | |
| seen.add(line) | |
| out.append(line) | |
| return " ".join(out) | |
| def fetch_captions(url: str) -> str | None: | |
| tmp = tempfile.gettempdir() | |
| ydl_opts = { | |
| "skip_download": True, | |
| "writeautomaticsub": True, | |
| "writesubtitles": True, | |
| "subtitleslangs": ["en"], | |
| "subtitlesformat": "vtt", | |
| "quiet": True, | |
| "outtmpl": os.path.join(tmp, "%(id)s.%(ext)s"), | |
| } | |
| with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
| info = ydl.extract_info(url, download=True) | |
| video_id = info.get("id", "video") | |
| for fname in os.listdir(tmp): | |
| if video_id in fname and fname.endswith(".vtt"): | |
| path = os.path.join(tmp, fname) | |
| with open(path, "r", encoding="utf-8") as f: | |
| raw = f.read() | |
| os.remove(path) | |
| return clean_vtt(raw) | |
| return None | |
| def fetch_audio(url: str) -> str: | |
| out = os.path.join(tempfile.gettempdir(), "yt_audio") | |
| ydl_opts = { | |
| "format": "bestaudio/best", | |
| "outtmpl": out, | |
| "postprocessors": [{"key": "FFmpegExtractAudio", | |
| "preferredcodec": "mp3", | |
| "preferredquality": "96"}], | |
| "quiet": True, | |
| } | |
| with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
| ydl.download([url]) | |
| return out + ".mp3" | |
| def transcribe_whisper(audio_path: str, model_size: str) -> str: | |
| model = WhisperModel(model_size, device="cpu", compute_type="int8") | |
| segments, _ = model.transcribe(audio_path, beam_size=5) | |
| return " ".join(seg.text.strip() for seg in segments) | |
| def chunk_text(text: str, size: int) -> list[str]: | |
| words = text.split() | |
| return [" ".join(words[i:i+size]) for i in range(0, len(words), size)] | |
| class RAGIndex: | |
| def __init__(self, chunks: list[str]): | |
| self.chunks = chunks | |
| self.use_faiss = FAISS_AVAILABLE | |
| if self.use_faiss: | |
| self.encoder = SentenceTransformer("all-MiniLM-L6-v2") | |
| emb = np.array( | |
| self.encoder.encode(chunks, show_progress_bar=False) | |
| ).astype("float32") | |
| faiss.normalize_L2(emb) | |
| self.index = faiss.IndexFlatIP(emb.shape[1]) | |
| self.index.add(emb) | |
| def search(self, query: str, k: int) -> list[str]: | |
| if self.use_faiss: | |
| q = np.array( | |
| self.encoder.encode([query]) | |
| ).astype("float32") | |
| faiss.normalize_L2(q) | |
| _, idx = self.index.search(q, k) | |
| return [self.chunks[i] for i in idx[0] if i < len(self.chunks)] | |
| # keyword fallback | |
| qw = set(query.lower().split()) | |
| scored = sorted(self.chunks, | |
| key=lambda c: len(qw & set(c.lower().split())), | |
| reverse=True) | |
| return scored[:k] | |
| def stream_summary(transcript: str, client: Groq, model: str): | |
| prompt = f"""You are a sharp, efficient summariser. | |
| Summarise this video transcript: | |
| - One-line TL;DR first | |
| - Bullet the key ideas (skip pleasantries and filler) | |
| - End with actionable takeaways if any | |
| TRANSCRIPT: | |
| {transcript[:12000]}""" | |
| stream = client.chat.completions.create( | |
| model=model, | |
| messages=[{"role": "user", "content": prompt}], | |
| stream=True, max_tokens=1024, | |
| ) | |
| for chunk in stream: | |
| delta = chunk.choices[0].delta.content | |
| if delta: | |
| yield delta | |
| def answer_question(question: str, context: list[str], | |
| history: list, client: Groq, model: str) -> str: | |
| ctx = "\n\n---\n\n".join(context) | |
| messages = [ | |
| {"role": "system", "content": | |
| f"Answer questions about a video transcript using only the context below.\n\nCONTEXT:\n{ctx}"}, | |
| *history[-6:], | |
| {"role": "user", "content": question}, | |
| ] | |
| resp = client.chat.completions.create( | |
| model=model, messages=messages, max_tokens=512 | |
| ) | |
| return resp.choices[0].message.content | |
| # ββ session state βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| for k, v in {"transcript": None, "summary": None, | |
| "rag_index": None, "chat_history": []}.items(): | |
| if k not in st.session_state: | |
| st.session_state[k] = v | |
| # ββ main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| url = st.text_input("π YouTube URL", placeholder="https://www.youtube.com/watch?v=...") | |
| if st.button("π Process", disabled=not (url and groq_key)): | |
| st.session_state.update( | |
| transcript=None, summary=None, rag_index=None, chat_history=[] | |
| ) | |
| client = Groq(api_key=groq_key) | |
| with st.status("Working...", expanded=True) as status: | |
| transcript = None | |
| if not use_whisper: | |
| st.write("π₯ Fetching captions...") | |
| transcript = fetch_captions(url) | |
| if transcript: | |
| st.write("β Captions found") | |
| else: | |
| st.write("β οΈ No captions β trying Whisper...") | |
| if not transcript: | |
| if not WHISPER_AVAILABLE: | |
| st.error("No captions found and Whisper is not installed.") | |
| st.stop() | |
| st.write("ποΈ Downloading audio...") | |
| audio = fetch_audio(url) | |
| st.write(f"π§ Transcribing ({whisper_model_size})...") | |
| transcript = transcribe_whisper(audio, whisper_model_size) | |
| os.remove(audio) | |
| st.write("β Transcription done") | |
| st.session_state.transcript = transcript | |
| st.write("π Building RAG index...") | |
| chunks = chunk_text(transcript, chunk_size) | |
| st.session_state.rag_index = RAGIndex(chunks) | |
| st.write(f"β {len(chunks)} chunks indexed") | |
| status.update(label="β Done!", state="complete") | |
| # stream summary | |
| st.subheader("π Summary") | |
| box = st.empty() | |
| full = "" | |
| for token in stream_summary(transcript, client, groq_model): | |
| full += token | |
| box.markdown(full + "β") | |
| box.markdown(full) | |
| st.session_state.summary = full | |
| # ββ persistent view βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if st.session_state.transcript: | |
| left, right = st.columns([1, 1]) | |
| with left: | |
| if st.session_state.summary: | |
| st.subheader("π Summary") | |
| st.markdown(st.session_state.summary) | |
| with st.expander("π Full transcript"): | |
| st.write(st.session_state.transcript) | |
| with right: | |
| st.subheader("π¬ Chat with the video") | |
| for msg in st.session_state.chat_history: | |
| with st.chat_message(msg["role"]): | |
| st.markdown(msg["content"]) | |
| if question := st.chat_input("Ask anything about the video..."): | |
| if not groq_key: | |
| st.error("Add your Groq key in the sidebar.") | |
| else: | |
| client = Groq(api_key=groq_key) | |
| st.session_state.chat_history.append( | |
| {"role": "user", "content": question} | |
| ) | |
| with st.chat_message("user"): | |
| st.markdown(question) | |
| context = st.session_state.rag_index.search(question, top_k) | |
| with st.chat_message("assistant"): | |
| with st.spinner("Thinking..."): | |
| answer = answer_question( | |
| question, context, | |
| st.session_state.chat_history, | |
| client, groq_model | |
| ) | |
| st.markdown(answer) | |
| st.session_state.chat_history.append( | |
| {"role": "assistant", "content": answer} | |
| ) |