File size: 7,048 Bytes
0a237fa
 
42c842c
 
 
52687ba
0a237fa
 
61493dd
 
4620dc9
 
 
52687ba
 
 
4620dc9
52687ba
 
 
4620dc9
52687ba
 
 
 
0a237fa
52687ba
 
 
 
 
 
0a237fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52687ba
0a237fa
 
 
 
 
 
3893edc
0a237fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52687ba
0a237fa
 
 
 
 
 
3893edc
0a237fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3893edc
 
ba26853
 
 
0a237fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52687ba
0a237fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52687ba
0a237fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61493dd
 
0a237fa
 
61493dd
 
 
0a237fa
 
 
61493dd
 
 
 
 
 
 
 
0a237fa
61493dd
 
 
0a237fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61493dd
0a237fa
61493dd
 
 
0a237fa
 
61493dd
0a237fa
 
 
 
 
 
 
 
 
 
 
61493dd
 
 
0a237fa
3893edc
61493dd
0a237fa
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import nltk
import os, json
from dotenv import load_dotenv
load_dotenv()


nltk.download("punkt_tab")

RETRIEVER = None

import gradio as gr
import nltk
from typing import List
from nltk.tokenize import sent_tokenize
from dataclasses import dataclass
import re

from sentence_transformers import CrossEncoder
from llama_index.retrievers.bm25 import BM25Retriever
from llama_index.core.retrievers import QueryFusionRetriever

from llama_index.core import Settings, VectorStoreIndex
from llama_index.core.schema import TextNode
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.openai import OpenAI




Settings.embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
Settings.llm = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"), base_url=os.environ.get("OPENAI_API_BASE"))

@dataclass
class Utterance:
    start: float
    end: float
    speaker: str
    text: str


def ts_to_sec(ts: str) -> float:
    h, m, s = ts.split(":")
    return int(h) * 3600 + int(m) * 60 + float(s)


def parse_webvtt(path: str) -> list[Utterance]:
    utterances = []
    lines = open(path, encoding="utf-8").readlines()

    i = 0
    while i < len(lines):
        line = lines[i].strip()
        if "-->" in line:
            start, end = map(str.strip, line.split("-->"))
            start, end = ts_to_sec(start), ts_to_sec(end)

            i += 1
            speaker, text = "UNKNOWN", ""
            if ":" in lines[i]:
                speaker, text = lines[i].split(":", 1)
                speaker, text = speaker.strip(), text.strip()
            else:
                text = lines[i].strip()

            utterances.append(Utterance(start, end, speaker, text))
        i += 1

    return utterances





def build_subchunks(
    utterances,
    max_gap_sec=25,
    max_words=120,
    sentences_per_chunk=3
):
    chunks, current = [], []
    last_end = None

    for u in utterances:
        gap = None if last_end is None else u.start - last_end
        wc = sum(len(x.text.split()) for x in current)

        if (gap and gap > max_gap_sec) or wc > max_words:
            chunks.append(current)
            current = []

        current.append(u)
        last_end = u.end

    if current:
        chunks.append(current)

    subchunks = []
    for c in chunks:
        text = " ".join(u.text for u in c)
        sentences = sent_tokenize(text)

        for i in range(0, len(sentences), sentences_per_chunk):
            subchunks.append({
                "text": " ".join(sentences[i:i+sentences_per_chunk]),
                "start": c[0].start,
                "end": c[-1].end,
                "speakers": list(set(u.speaker for u in c))
            })

    return subchunks




TOPIC_RULES = {
    "gpu": ["gpu", "graphics card", "cuda", "vram", "nvidia"],
    "technical_challenge": [
        "issue", "problem", "challenge", "difficulty",
        "error", "not working", "failed", "crash"
    ],
    "real_world_use_case": [
        "use case", "real world", "industry",
        "production", "business case", "example"
    ],
    "qa": [
        "question", "follow up", "does that help",
        "good question", "let me clarify"
    ]
}


def tag_topics(text: str) -> list[str]:
    text = text.lower()
    tags = set()

    for topic, kws in TOPIC_RULES.items():
        if any(re.search(rf"\b{re.escape(k)}\b", text) for k in kws):
            tags.add(topic)

    return list(tags)








def build_nodes(subchunks):
    nodes = []
    for c in subchunks:
        nodes.append(
            TextNode(
                text=c["text"],
                metadata={
                    "start": c["start"],
                    "end": c["end"],
                    "speakers": c["speakers"],
                    "topics": tag_topics(c["text"])
                }
            )
        )
    return nodes




def build_hybrid_retriever(nodes):
    index = VectorStoreIndex(nodes)

    # Use nodes= keyword argument explicitly
    bm25 = BM25Retriever.from_defaults(nodes=nodes, similarity_top_k=20)
    vector = index.as_retriever(similarity_top_k=20)

    return QueryFusionRetriever(
        retrievers=[bm25, vector],
        similarity_top_k=10,
        mode="reciprocal_rerank"
    )


def expand_query(q: str) -> str:
    expansions = {
        "gpu": ["graphics card", "cuda", "vram"],
        "challenge": ["issue", "problem", "difficulty", "error"]
    }

    ql = q.lower()
    for k, v in expansions.items():
        if k in ql:
            q += " " + " ".join(v)

    return q


def infer_required_topics(q: str) -> set[str]:
    ql = q.lower()
    req = set()

    if any(w in ql for w in ["gpu", "cuda", "vram"]):
        req.add("gpu")
    if any(w in ql for w in ["challenge", "issue", "problem", "difficulty"]):
        req.add("technical_challenge")

    return req




reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

def rerank(query, nodes):
    scores = reranker.predict([[query, n.text] for n in nodes])
    return [n for _, n in sorted(zip(scores, nodes), reverse=True)]


def retrieve(query, retriever, top_k=5):
    expanded = expand_query(query)
    required_topics = infer_required_topics(query)

    candidates = retriever.retrieve(expanded)

    if required_topics:
        candidates = [
            n for n in candidates
            if required_topics.issubset(set(n.metadata["topics"]))
        ]

    reranked = rerank(expanded, candidates)

    return [{
        "text": n.text,
        "topics": n.metadata["topics"],
        "start": n.metadata["start"],
        "end": n.metadata["end"],
        "speakers": n.metadata["speakers"]
    } for n in reranked[:top_k]]



# -----------------------------
# Gradio App
# -----------------------------



def index_file(file):
    global RETRIEVER

    utterances = parse_webvtt(file.name)
    subchunks = build_subchunks(utterances)
    nodes = build_nodes(subchunks)

    RETRIEVER = build_hybrid_retriever(nodes)
    return "✅ Index built successfully"

    
def run_query(query):
    global RETRIEVER

    if RETRIEVER is None:
        return "❌ Please upload and index a transcript first."

    return retrieve(query, RETRIEVER)



with gr.Blocks(title="Transcript Hybrid RAG") as demo:
    gr.Markdown("## 🎙️ Transcript Hybrid Search (BM25 + Vectors)")
    gr.Markdown(
        "Upload a transcript and ask questions. "
        "**Retrieval only** (no hallucinations)."
    )

    upload = gr.File(
        label="Upload transcript",
        file_types=[".vtt", ".txt", ".transcript"]
    )

    index_btn = gr.Button("Build Index")
    status = gr.Textbox(label="Status")

    
    index_btn.click(
    fn=index_file,
    inputs=upload,
    outputs=status
    )


    query = gr.Textbox(
        label="Ask a question",
        placeholder="Did the instructor face GPU challenges?"
    )

    output = gr.Textbox(
        label="Retrieved Evidence",
        lines=15
    )

    query.submit(
    fn=run_query,
    inputs=query,
    outputs=output
    )


demo.launch()