import os from huggingface_hub import snapshot_download SAVE_DIR = "./ahrag_save" if not os.path.exists(os.path.join(SAVE_DIR, "config.json")): print("Downloading data...") snapshot_download( repo_id="Varun-rajwe12/ahrag-data", repo_type="dataset", local_dir=SAVE_DIR, ignore_patterns=["*.gitattributes","README.md"] ) print("✓ Data downloaded!") else: print("✓ Data already present") # ═══════════════════════════════════════════════════════════════════ # AHRAG GRADIO — FRESH COLAB NOTEBOOK (Single File) # # INSTRUCTIONS: # 1. Open a NEW Colab notebook # 2. Upload ahrag_save.zip to Colab (or mount Google Drive) # 3. Run Cell 1 (install), Cell 2 (unzip), Cell 3 (this file) # # CELL 1 — paste and run: # !pip install -q gradio sentence-transformers faiss-gpu transformers accelerate bitsandbytes # # CELL 2 — paste and run: # !unzip -q ahrag_save.zip # # CELL 3 — paste and run this entire file # ═══════════════════════════════════════════════════════════════════ import os, json, re, time, gc, warnings import numpy as np import torch import faiss import gradio as gr from dataclasses import dataclass, field from collections import defaultdict from nltk.tokenize import sent_tokenize import nltk warnings.filterwarnings("ignore") nltk.download('punkt', quiet=True) nltk.download('punkt_tab', quiet=True) # ── Find the save directory ───────────────────────────────────────────── for _candidate in ["./ahrag_save/ahrag_save", "./ahrag_save", "/content/ahrag_save/ahrag_save", "/content/ahrag_save"]: if os.path.exists(os.path.join(_candidate, "config.json")): SAVE_DIR = _candidate break else: raise FileNotFoundError("ahrag_save folder not found! Run: !unzip ahrag_save.zip") print("=" * 60) print(" AHRAG GRADIO — Loading from saved files") print(f" Save dir: {SAVE_DIR}") print("=" * 60) # ════════════════════════════════════════════════════════════════ # 1. CONFIG # ════════════════════════════════════════════════════════════════ with open(os.path.join(SAVE_DIR, "config.json")) as f: CFG = json.load(f) DEVICE = "cuda" if torch.cuda.is_available() else "cpu" print(f"\n[1/6] Device: {DEVICE.upper()}") # ════════════════════════════════════════════════════════════════ # 2. EMBEDDER # ════════════════════════════════════════════════════════════════ from sentence_transformers import SentenceTransformer, CrossEncoder print("[2/6] Loading embedder...") emb_path = os.path.join(SAVE_DIR, "embedder_model") embedder = SentenceTransformer(emb_path if os.path.isdir(emb_path) else CFG.get("embedding_model", "BAAI/bge-small-en-v1.5"), device=DEVICE) print(f" ✓ Embedder ready on {DEVICE.upper()}") # ════════════════════════════════════════════════════════════════ # 3. RERANKER # ════════════════════════════════════════════════════════════════ print("[3/6] Loading reranker...") rnk_path = os.path.join(SAVE_DIR, "reranker_model") reranker = CrossEncoder(rnk_path if os.path.isdir(rnk_path) else CFG.get("cross_encoder_model", "cross-encoder/ms-marco-MiniLM-L-6-v2"), device=DEVICE) print(f" ✓ Reranker ready on {DEVICE.upper()}") # ════════════════════════════════════════════════════════════════ # 4. LLMs (4-bit on GPU, float32 on CPU) # ════════════════════════════════════════════════════════════════ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig def _load_llm(name): folder = os.path.join(SAVE_DIR, f"{name}_model") name_file = os.path.join(SAVE_DIR, f"{name}_model_name.txt") src = (folder if os.path.isdir(folder) else open(name_file).read().strip() if os.path.exists(name_file) else CFG["llm_models"].get(name, "")) print(f" Loading {name} from: {src}") tok = AutoTokenizer.from_pretrained(src, trust_remote_code=True) if tok.pad_token is None: tok.pad_token = tok.eos_token if DEVICE == "cuda": bnb = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True, ) model = AutoModelForCausalLM.from_pretrained( src, quantization_config=bnb, device_map="auto", trust_remote_code=True, torch_dtype=torch.float16, ) else: model = AutoModelForCausalLM.from_pretrained( src, trust_remote_code=True, torch_dtype=torch.float32, # dtype param low_cpu_mem_usage=True, ) model.eval() print(f" ✓ {name} ready") return model, tok print("[4/6] Loading Qwen only (CPU free tier)...") _qwen_model, _qwen_tok = _load_llm("qwen") _mistral_model, _mistral_tok = None, None print(" ⚠ Mistral skipped (insufficient RAM on free tier)") # ════════════════════════════════════════════════════════════════ # 5. KNOWLEDGE BASE (chunks + FAISS + KG + metadata) # ════════════════════════════════════════════════════════════════ print("[5/6] Loading knowledge base...") @dataclass class Chunk: chunk_id: str filename: str doc_type: str text: str entities: list = field(default_factory=list) topics: list = field(default_factory=list) confidence: float = 0.5 # Chunks with open(os.path.join(SAVE_DIR, "chunks.json"), encoding="utf-8") as f: chunks_raw = json.load(f) chunks = [Chunk( chunk_id = c["chunk_id"], filename = c["filename"], doc_type = c.get("doc_type", "unknown"), text = c["text"], entities = c.get("entities", []), topics = c.get("topics", []), confidence = float(c.get("confidence", 0.5)), ) for c in chunks_raw] chunk_lookup = {i: c for i, c in enumerate(chunks)} # FAISS faiss_index = faiss.read_index(os.path.join(SAVE_DIR, "faiss.index")) # Metadata index with open(os.path.join(SAVE_DIR, "metadata_index.json")) as f: metadata_index = json.load(f) # Confidence map with open(os.path.join(SAVE_DIR, "confidence_scores.json")) as f: confidence_map = {c["chunk_id"]: c["confidence"] for c in json.load(f)} # Knowledge graph with open(os.path.join(SAVE_DIR, "knowledge_graph.json")) as f: kg_data = json.load(f) # Entity → chunk map entity_chunk_map = defaultdict(set) for edge in kg_data.get("edges", []): if edge.get("edge_type") == "entity_document": did = edge.get("target", "") if did.startswith("DOC::"): fname = did.replace("DOC::", "") for i, c in enumerate(chunks): if c.filename == fname: entity_chunk_map[edge.get("source", "")].add(i) print(f" ✓ {len(chunks)} chunks | FAISS {faiss_index.ntotal} vectors") print(f" ✓ {len(metadata_index)} metadata keys | {len(kg_data.get('nodes',[]))} KG nodes") print("[6/6] All loaded.\n") # ════════════════════════════════════════════════════════════════ # RETRIEVAL # ════════════════════════════════════════════════════════════════ def retrieve(query: str, top_k: int = 5): q_emb = embedder.encode([query], normalize_embeddings=True, convert_to_numpy=True).astype("float32") scores, indices = faiss_index.search(q_emb, 30) merged = {int(i): float(s) for i, s in zip(indices[0], scores[0]) if i >= 0} for key, idx_list in metadata_index.items(): words = key.split(":")[-1].lower().split() if any(w in query.lower() for w in words if len(w) > 3): for idx in idx_list: merged[idx] = merged.get(idx, 0) + 0.10 for node in kg_data.get("nodes", []): if node.get("node_class") == "entity": label = node.get("label", "").lower() if label in query.lower() or any(w in label for w in query.lower().split() if len(w) > 3): for idx in entity_chunk_map.get(node.get("id", ""), set()): merged[idx] = merged.get(idx, 0) + 0.15 pool = [] for idx, sc in sorted(merged.items(), key=lambda x: -x[1])[:24]: chunk = chunk_lookup.get(idx) if not chunk: continue conf = confidence_map.get(chunk.chunk_id, 0.5) pool.append((idx, sc * (0.5 + 0.5 * conf), sc, conf)) pool.sort(key=lambda x: -x[1]) pool = pool[:12] if not pool: return [] pairs = [[query, chunk_lookup[idx].text[:2000]] for idx, *_ in pool] ce_scores = reranker.predict(pairs, show_progress_bar=False) results = [] for (idx, _, dense_sc, conf), ce in zip(pool, ce_scores): chunk = chunk_lookup[idx] combined = 0.6 * float(ce) + 0.25 * dense_sc + 0.15 * conf results.append({"chunk": chunk, "combined": round(combined, 4), "conf": round(conf, 4)}) results.sort(key=lambda x: -x["combined"]) return results[:top_k] # ════════════════════════════════════════════════════════════════ # GENERATION (CUDA-safe) # ════════════════════════════════════════════════════════════════ def generate(which: str, query: str, ctx_chunks: list, max_tokens: int = 512): model = _qwen_model if which == "qwen" else _mistral_model tok = _qwen_tok if which == "qwen" else _mistral_tok context = "\n\n".join(f"[Source: {c['filename']}]\n{c['text'][:800]}" for c in ctx_chunks) messages = [ {"role": "system", "content": "You are a helpful assistant. Answer based only on the provided context. Be concise and accurate."}, {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {query}\n\nAnswer:"}, ] try: prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) except Exception: prompt = messages[-1]["content"] def _run(dev): inp = tok(prompt, return_tensors="pt", truncation=True, max_length=2048, padding=True) inp = {k: v.to(dev) for k, v in inp.items()} with torch.no_grad(): out = model.generate(**inp, max_new_tokens=max_tokens, do_sample=True, temperature=0.7, top_p=0.9, pad_token_id=tok.eos_token_id) return tok.decode(out[0][inp["input_ids"].shape[1]:], skip_special_tokens=True).strip() try: resp = _run(DEVICE) except RuntimeError as e: if any(k in str(e) for k in ("CUDA", "device-side assert", "out of memory")): gc.collect() try: torch.cuda.empty_cache() except: pass try: model.to("cpu") resp = _run("cpu") except Exception as ce: return f"[Error: {ce}]", 0.0 else: return f"[Error: {e}]", 0.0 except Exception as e: return f"[Error: {e}]", 0.0 conf = min(0.95, 0.5 + len(resp.split()) / 400) return resp, round(conf, 4) # ════════════════════════════════════════════════════════════════ # FUSION + ROUTER + COSINE # ════════════════════════════════════════════════════════════════ def cos_sim(a, b): if not a or not b: return 0.0 emb = embedder.encode([a[:1000], b[:1000]], normalize_embeddings=True) return round(float(np.dot(emb[0], emb[1])), 4) def fuse(query, ctx, ra, ca, rb, cb): ctx_emb = embedder.encode([" ".join(c["text"] for c in ctx)[:2000]], normalize_embeddings=True)[0] def q(r, c): if not r or len(r.strip()) < 10: return 0.01 re_ = embedder.encode([r[:1000]], normalize_embeddings=True)[0] return 0.4*float(np.dot(re_, ctx_emb)) + 0.3*cos_sim(query,r) + 0.2*c + 0.1*min(len([s for s in r.split(".") if len(s.strip())>10])/6,1.0) qa, qb = max(0.01, q(ra,ca)), max(0.01, q(rb,cb)) wa = round(qa/(qa+qb), 4); wb = round(1.0-wa, 4) sa = [s.strip() for s in re.split(r'(?<=[.!?])\s+', ra) if len(s.strip())>15] if ra else [] sb = [s.strip() for s in re.split(r'(?<=[.!?])\s+', rb) if len(s.strip())>15] if rb else [] cands = sa[:max(1,round(wa*6))] + sb[:max(1,round(wb*6))] seen, kept, nrm = [], [], 0 if cands: cembs = embedder.encode(cands, normalize_embeddings=True) for sent, emb in zip(cands, cembs): if any(float(np.dot(emb,se))>0.92 for se in seen): nrm+=1 else: seen.append(emb); kept.append(sent) fused = " ".join(kept) if kept else (ra or rb or "") return fused, round(wa*ca+wb*cb,4), wa, wb, nrm def route(query): q=query.lower(); n=len(query.split()) cplx=sum(1 for s in ["explain","compare","analyze","discuss","evaluate","how does","why does","difference","relationship"] if s in q) mp=round(min(0.95,0.4+cplx*0.12+(n/50)*0.1),4); qp=round(1.0-mp,4) if mp>0.55: return "mistral",qp,mp,f"{cplx} complexity signals, {n} words → Mistral-7B" return "qwen",qp,mp,f"{n} words, factual → Qwen2.5-1.5B" # ════════════════════════════════════════════════════════════════ # HTML RENDERING # ════════════════════════════════════════════════════════════════ def _bc(v,h=False): if h: return "g" if v<0.15 else "a" if v<0.30 else "r" return "g" if v>=0.85 else "b" if v>=0.65 else "a" if v>=0.45 else "r" C = {"g":"#10B981","b":"#3B82F6","a":"#F59E0B","r":"#EF4444"} BG = {"g":"rgba(16,185,129,0.15)","b":"rgba(59,130,246,0.15)","a":"rgba(245,158,11,0.15)","r":"rgba(239,68,68,0.15)"} def badge(v,cls): return f'{v:.4f}' def bar(v,cls): return f'
' def render_metrics(faith,halluc,relev,coher,conf,tr,tg,tt): rows=[("Faithfulness",faith,"Context-supported statements",_bc(faith)), ("Hallucination",halluc,"Unsupported fraction",_bc(halluc,True)), ("Relevancy",relev,"Query ↔ Response cosine",_bc(relev)), ("Coherence",coher,"Sentence-pair continuity",_bc(coher)), ("Confidence",conf,"Weighted LLM confidence",_bc(conf))] html="" for lbl,v,desc,cls in rows: html+=(f'