Spaces:
Runtime error

File size: 10,416 Bytes
1c320b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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}
                )