abhivsh commited on
Commit
3958741
·
verified ·
1 Parent(s): 3b9e162

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +357 -0
app.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EnggSS RAG ChatBot — HuggingFace Space (serving only)
3
+ ======================================================
4
+ Loads a pre-built PRIVATE HuggingFace Dataset (embeddings already computed
5
+ by preprocessing/create_dataset.py) and serves a conversational Q&A interface.
6
+
7
+ No PDF loading. No chunking. No embedding of documents at runtime.
8
+ Only the user query is embedded on each call (~20 ms).
9
+
10
+ Required Space Secrets (Settings → Variables and Secrets):
11
+ HF_TOKEN — HuggingFace token with READ access to the dataset
12
+ HF_DATASET_REPO — e.g. your-org/enggss-rag-dataset
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import os
19
+ from collections import Counter
20
+ from typing import Any
21
+
22
+ import gradio as gr
23
+ import numpy as np
24
+ from datasets import load_dataset
25
+ from dotenv import load_dotenv
26
+ from langchain_core.messages import AIMessage, HumanMessage
27
+ from langchain_core.output_parsers import StrOutputParser
28
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
29
+ from langchain_huggingface import HuggingFaceEndpoint
30
+ from sentence_transformers import SentenceTransformer
31
+
32
+ load_dotenv()
33
+
34
+ # ─── Configuration ────────────────────────────────────────────────────────────
35
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
36
+ DATASET_REPO = os.environ.get("HF_DATASET_REPO", "")
37
+ LLM_REPO = "Qwen/Qwen2.5-7B-Instruct"
38
+ EMBED_MODEL = "BAAI/bge-large-en-v1.5"
39
+ QUERY_PREFIX = "Represent this sentence for searching relevant passages: "
40
+
41
+ TOP_K = 3
42
+ FETCH_K = 15
43
+ LAMBDA_MMR = 0.7 # 1.0 = pure relevance · 0.0 = pure diversity
44
+
45
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
46
+ log = logging.getLogger(__name__)
47
+
48
+
49
+ # ═════════════════════════════════════════════════════════════════════════════
50
+ # 1 ─ Embedding model (local, cached by sentence-transformers after 1st run)
51
+ # ═════════════════════════════════════════════════════════════════════════════
52
+ log.info("Loading embedding model: %s", EMBED_MODEL)
53
+ try:
54
+ _embed_model = SentenceTransformer(EMBED_MODEL)
55
+ EMBED_ERROR = None
56
+ except Exception as _exc:
57
+ _embed_model = None
58
+ EMBED_ERROR = str(_exc)
59
+ log.error("Embedding model failed: %s", _exc)
60
+
61
+
62
+ def embed_query(text: str) -> np.ndarray:
63
+ """
64
+ Embed a single query string with the BGE instruction prefix.
65
+ Returns a unit-normalised float32 vector of shape (1024,).
66
+ """
67
+ if _embed_model is None:
68
+ raise RuntimeError(f"Embedding model unavailable: {EMBED_ERROR}")
69
+ vec = _embed_model.encode(
70
+ QUERY_PREFIX + text,
71
+ normalize_embeddings=True,
72
+ show_progress_bar=False,
73
+ )
74
+ return vec.astype(np.float32)
75
+
76
+
77
+ # ═════════════════════════════════════════════════════════════════════════════
78
+ # 2 ─ LLM (HF Inference API — no local model download)
79
+ # ═════════════════════════════════════════════════════════════════════════════
80
+ try:
81
+ _llm = HuggingFaceEndpoint(
82
+ repo_id=LLM_REPO,
83
+ temperature=0.01,
84
+ max_new_tokens=1024,
85
+ huggingfacehub_api_token=HF_TOKEN,
86
+ )
87
+ LLM_ERROR = None
88
+ except Exception as _exc:
89
+ _llm = None
90
+ LLM_ERROR = str(_exc)
91
+ log.error("LLM init failed: %s", _exc)
92
+
93
+ _qa_prompt = ChatPromptTemplate.from_messages([
94
+ ("system",
95
+ "You are a technical expert on engineering specifications and IS/IEEE/BIS standards. "
96
+ "Answer ONLY from the provided context. Be precise and point-wise. "
97
+ "If the context does not contain the answer, say so clearly."),
98
+ MessagesPlaceholder("chat_history"),
99
+ ("human",
100
+ "Context from technical documents:\n{context}\n\n"
101
+ "Question: {question}"),
102
+ ])
103
+ _answer_chain = (_qa_prompt | _llm | StrOutputParser()) if _llm else None
104
+
105
+
106
+ # ═════════════════════════════════════════════════════════════════════════════
107
+ # 3 ─ Load dataset from HF Hub into a NumPy matrix
108
+ # ═════════════════════════════════════════════════════════════════════════════
109
+ EMB_MATRIX: np.ndarray | None = None
110
+ METADATA: list[dict] | None = None
111
+
112
+
113
+ def load_knowledge_base() -> tuple[str, str]:
114
+ """
115
+ Download the private HF Dataset, build the NumPy embedding matrix, and
116
+ populate the module-level EMB_MATRIX / METADATA.
117
+
118
+ Returns:
119
+ (status_str, detail_str) e.g. ("✅ Ready", "8 420 chunks · 35 docs")
120
+ """
121
+ global EMB_MATRIX, METADATA
122
+
123
+ if not DATASET_REPO:
124
+ return "❌ Not configured", "Set the HF_DATASET_REPO secret in Space Settings."
125
+ if not HF_TOKEN:
126
+ return "❌ Not configured", "Set the HF_TOKEN secret in Space Settings."
127
+
128
+ log.info("Loading dataset from HF Hub: %s", DATASET_REPO)
129
+ try:
130
+ ds = load_dataset(DATASET_REPO, token=HF_TOKEN, split="train")
131
+ except Exception as exc:
132
+ return "❌ Load failed", str(exc)
133
+
134
+ if len(ds) == 0:
135
+ return "❌ Empty dataset", "Dataset has no records. Run create_dataset.py first."
136
+
137
+ # Build normalised float32 matrix (N × 1024)
138
+ mat = np.array(ds["embedding"], dtype=np.float32)
139
+ norms = np.linalg.norm(mat, axis=1, keepdims=True)
140
+ mat = mat / np.where(norms == 0, 1.0, norms)
141
+
142
+ EMB_MATRIX = mat
143
+ METADATA = [
144
+ {
145
+ "text": r["text"],
146
+ "source": r["source"],
147
+ "page": r["page"],
148
+ "context": r.get("context", ""),
149
+ }
150
+ for r in ds
151
+ ]
152
+
153
+ n_docs = len({m["source"] for m in METADATA})
154
+ detail = f"{len(METADATA):,} chunks · {n_docs} documents"
155
+ log.info("Dataset ready: %s", detail)
156
+ return "✅ Ready", detail
157
+
158
+
159
+ # Load at startup
160
+ _status, _detail = load_knowledge_base()
161
+ log.info("Startup — %s: %s", _status, _detail)
162
+
163
+
164
+ # ═════════════════════════════════════════════════════════════════════════════
165
+ # 4 ─ Retrieval (cosine similarity + MMR, pure NumPy)
166
+ # ═════════════════════════════════════════════════════════════════════════════
167
+ def _mmr(
168
+ query_emb: np.ndarray,
169
+ scores: np.ndarray,
170
+ top_k: int,
171
+ fetch_k: int,
172
+ lambda_mult: float,
173
+ ) -> list[tuple[int, float]]:
174
+ """
175
+ Maximum Marginal Relevance selection.
176
+
177
+ Picks *top_k* results that balance relevance to the query (cosine score)
178
+ against redundancy with already-selected chunks.
179
+ """
180
+ candidates = list(np.argsort(scores)[::-1][:fetch_k])
181
+ selected: list[int] = []
182
+
183
+ while len(selected) < top_k and candidates:
184
+ if not selected:
185
+ best = candidates[0]
186
+ else:
187
+ sel_vecs = EMB_MATRIX[selected] # (n_sel, D)
188
+ mmr_vals = [
189
+ lambda_mult * scores[c]
190
+ - (1 - lambda_mult) * float(np.max(sel_vecs @ EMB_MATRIX[c]))
191
+ for c in candidates
192
+ ]
193
+ best = candidates[int(np.argmax(mmr_vals))]
194
+ selected.append(best)
195
+ candidates.remove(best)
196
+
197
+ return [(idx, float(scores[idx])) for idx in selected]
198
+
199
+
200
+ def retrieve(question: str) -> list[dict[str, Any]]:
201
+ """
202
+ Embed *question* and return top-k diverse chunks with similarity scores.
203
+ """
204
+ q_emb = embed_query(question)
205
+ scores = EMB_MATRIX @ q_emb # dot product = cosine (unit vecs)
206
+ hits = _mmr(q_emb, scores, TOP_K, FETCH_K, LAMBDA_MMR)
207
+ return [{**METADATA[idx], "score": score} for idx, score in hits]
208
+
209
+
210
+ # ═════════════════════════════════════════════════════════════════════════════
211
+ # 5 ─ Q&A function (wired to gr.ChatInterface)
212
+ # ═════════════════════════════════════════════════════════════════════════════
213
+ def qa_fn(question: str, history: list[dict]) -> str:
214
+ """
215
+ 1. Retrieve top-k contexts via MMR.
216
+ 2. Generate an answer with Qwen2.5-7B using the contexts + chat history.
217
+ 3. Return a formatted Markdown string with contexts + answer.
218
+ """
219
+ # Guard: dataset not loaded
220
+ if EMB_MATRIX is None:
221
+ return (
222
+ f"⚠️ **Dataset not loaded** ({_status}).\n\n"
223
+ f"{_detail}\n\n"
224
+ "Run `preprocessing/create_dataset.py` locally to build the dataset, "
225
+ "then restart this Space."
226
+ )
227
+
228
+ if not question.strip():
229
+ return "Please enter a question."
230
+
231
+ # ── Retrieve ─────────────────────────────────────────────────────────────
232
+ try:
233
+ contexts = retrieve(question)
234
+ except Exception as exc:
235
+ log.error("Retrieval error: %s", exc)
236
+ return f"❌ Retrieval failed: {exc}"
237
+
238
+ ctx_display = "\n\n".join(
239
+ f"**[{i+1}] {c['source']} — Page {c['page']} "
240
+ f"· similarity {c['score']:.3f}**\n"
241
+ f"> *{c['context']}*\n\n"
242
+ f"{c['text'][:600]}{'…' if len(c['text']) > 600 else ''}"
243
+ for i, c in enumerate(contexts)
244
+ )
245
+
246
+ # ── Generate ─────────────────────────────────────────────────────────────
247
+ if _answer_chain is None:
248
+ answer = f"⚠️ LLM unavailable: {LLM_ERROR}"
249
+ else:
250
+ context_str = "\n\n---\n\n".join(
251
+ f"[{i+1}] Source: {c['source']} | Page: {c['page']}\n{c['text']}"
252
+ for i, c in enumerate(contexts)
253
+ )
254
+ lc_history = [
255
+ HumanMessage(content=m["content"]) if m["role"] == "user"
256
+ else AIMessage(content=m["content"])
257
+ for m in history
258
+ ]
259
+ try:
260
+ answer = _answer_chain.invoke({
261
+ "context": context_str,
262
+ "question": question,
263
+ "chat_history": lc_history,
264
+ })
265
+ except Exception as exc:
266
+ log.error("LLM error: %s", exc)
267
+ answer = f"❌ LLM error: {exc}"
268
+
269
+ return (
270
+ f"## Retrieved Contexts\n\n{ctx_display}\n\n"
271
+ f"---\n\n"
272
+ f"## Answer\n\n{answer}"
273
+ )
274
+
275
+
276
+ # ═════════════════════════════════════════════════════════════════════════════
277
+ # 6 ─ Analytics
278
+ # ═════════════════════════════════════════════════════════════════════════════
279
+ def get_analytics() -> tuple[int, int, float, list[list]]:
280
+ if METADATA is None:
281
+ return 0, 0, 0.0, []
282
+ counts = Counter(m["source"] for m in METADATA)
283
+ total = len(METADATA)
284
+ n_docs = len(counts)
285
+ avg = round(total / n_docs, 1) if n_docs else 0.0
286
+ table = [[src, cnt] for src, cnt in sorted(counts.items())]
287
+ return total, n_docs, avg, table
288
+
289
+
290
+ # ═════════════════════════════════════════════════════════════════════════════
291
+ # 7 ─ Gradio UI
292
+ # ═════════════════════════════════════════════════════════════════════════════
293
+ EXAMPLES = [
294
+ "What should be the GIB height outside the GIS hall?",
295
+ "STATCOM station ratings and specifications",
296
+ "Specifications of XLPE power cables",
297
+ "Specification for Ethernet switches in SAS",
298
+ "Type tests for HV switchgear as per IS standards",
299
+ "Technical requirements for 765 kV class transformer",
300
+ ]
301
+
302
+ with gr.Blocks(title="EnggSS RAG ChatBot", theme=gr.themes.Base()) as demo:
303
+
304
+ gr.Markdown(
305
+ "# ⚡ EnggSS RAG ChatBot\n"
306
+ "Conversational Q&A over **Model Technical Specifications** & "
307
+ "**IS / IEEE / BIS Standards**\n\n"
308
+ f"> **Dataset:** {_status} — {_detail} &nbsp;|&nbsp; "
309
+ f"**Embedding:** `{EMBED_MODEL}` &nbsp;|&nbsp; "
310
+ f"**LLM:** `{LLM_REPO}`"
311
+ )
312
+
313
+ with gr.Tabs():
314
+
315
+ # ── Tab 1 : Q&A ───────────────────────────────────────────────────────
316
+ with gr.Tab("💬 Q&A"):
317
+ gr.ChatInterface(
318
+ fn=qa_fn,
319
+ type="messages",
320
+ examples=EXAMPLES,
321
+ concurrency_limit=None,
322
+ # fill_height removed in gradio 5.x
323
+ )
324
+
325
+ # ── Tab 2 : Analytics ─────────────────────────────────────────────────
326
+ with gr.Tab("📊 Analytics"):
327
+ gr.Markdown("### Knowledge Base Statistics")
328
+
329
+ refresh_btn = gr.Button("🔄 Refresh", size="sm")
330
+
331
+ with gr.Row():
332
+ m_chunks = gr.Metric(label="Total Chunks", value=0)
333
+ m_docs = gr.Metric(label="Documents Processed", value=0)
334
+ m_avg = gr.Metric(label="Avg Chunks / Doc", value=0.0)
335
+
336
+ tbl = gr.Dataframe(
337
+ headers=["Document", "Chunks"],
338
+ datatype=["str", "number"],
339
+ interactive=False,
340
+ label="Chunks per Document",
341
+ )
342
+
343
+ def _refresh():
344
+ return get_analytics()
345
+
346
+ refresh_btn.click(fn=_refresh, outputs=[m_chunks, m_docs, m_avg, tbl])
347
+ demo.load(fn=_refresh, outputs=[m_chunks, m_docs, m_avg, tbl])
348
+
349
+ gr.Markdown(
350
+ f"**Retrieval:** MMR · k={TOP_K} · fetch_k={FETCH_K} · λ={LAMBDA_MMR} \n"
351
+ f"**Embedding model:** `{EMBED_MODEL}` (1024-dim, L2-normalised) \n"
352
+ f"**LLM:** `{LLM_REPO}` via HF Inference API"
353
+ )
354
+
355
+
356
+ if __name__ == "__main__":
357
+ demo.launch(debug=True)