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'
' f'
{lbl}
{desc}
' f'
{bar(v,cls)}
{badge(v,cls)}
') return (f'
' f'
📊 Evaluation Metrics
{html}' f'
' f'⚡ Retrieval {tr:.3f}s' f'🤖 Generation {tg:.1f}s' f'🕐 Total {tt:.1f}s' f'
') def render_model(mode,llm,wa,wb,topk,maxt,reason): pa,pb=int(wa*100),int(wb*100) return (f'
' f'
🧠 Model Info
' f'
' f'
Mode
{mode}
' f'
LLM
{llm}
' f'
Chunks
{topk}
' f'
Max Tokens
{maxt}
' f'
' f'
' f'
AHFE WeightsQwen:{wa:.3f} | Mistral:{wb:.3f}
' f'
' f'
{f"{pa}% Qwen" if pa>15 else ""}
' f'
{f"{pb}% Mistral" if pb>15 else ""}
' f'
' f'
' f'
🧭 Routing
' f'
{reason}
') def render_context(retrieved): if not retrieved: return "
No context retrieved.
" cards="" for i,r in enumerate(retrieved,1): ch=r["chunk"] cards+=(f'
' f'
' f'#{i}' f'📄 {ch.filename}' f'Score:{r["combined"]:.4f}' f'Conf:{r["conf"]:.4f}' f'
{ch.text[:500]}
') return cards def render_sources(sources): chips="".join(f'📄 {s}' for s in sorted(set(sources))) return (f'
' f'
Attributed Files ({len(set(sources))}):
' f'
{chips}
') def render_compare(ra,ca,rb,cb): ta=ra or "Not generated in this mode." tb=rb or "Not generated in this mode." return (f'
' f'
' f'
' f'🤖 Qwen2.5-1.5BConf:{ca:.4f}
' f'
{ta}
' f'
' f'
' f'⚡ Mistral-7BConf:{cb:.4f}
' f'
{tb}
') # ════════════════════════════════════════════════════════════════ # MAIN QUERY HANDLER # ════════════════════════════════════════════════════════════════ def process_query(query, mode, top_k, max_tokens): empty="
Enter a query.
" if not query or not query.strip(): return ("Please enter a question.", empty, empty, empty, empty, empty, "") top_k=int(top_k); max_tokens=int(max_tokens) t_total=time.time() t0=time.time() retrieved=retrieve(query, top_k=top_k) t_ret=max(0.001, round(time.time()-t0, 3)) if not retrieved: return ("No relevant context found.", empty, empty, empty, empty, empty, "No context.") ctx=[{"text": r["chunk"].text, "filename": r["chunk"].filename} for r in retrieved] t0=time.time() ra,ca,rb,cb="",0.0,"",0.0 wa,wb=0.5,0.5; llm_name="AHFE"; reason="" if mode == "Qwen2.5-1.5B Only": resp,conf = generate("qwen", query, ctx, max_tokens) ra,ca=resp,conf; wa,wb=1.0,0.0 llm_name="Qwen2.5-1.5B"; reason="User selected Qwen2.5-1.5B Only." elif mode == "Mistral-7B Only": resp,conf = generate("mistral", query, ctx, max_tokens) rb,cb=resp,conf; wa,wb=0.0,1.0 llm_name="Mistral-7B"; reason="User selected Mistral-7B Only." elif mode == "AHFE Fusion (Both)": ra,ca = generate("qwen", query, ctx, max_tokens) rb,cb = generate("mistral", query, ctx, max_tokens) resp,conf,wa,wb,nrm = fuse(query, ctx, ra, ca, rb, cb) llm_name="AHFE Fusion Engine" reason=f"Bayesian Fusion: w_qwen={wa:.4f}, w_mistral={wb:.4f} | Pruned {nrm} duplicates." else: # LLM Routing (Auto) r,qp,mp,why = route(query) ra,ca = generate("qwen", query, ctx, max_tokens) rb,cb = generate("mistral", query, ctx, max_tokens) if r=="mistral": resp,conf,wa,wb=rb,cb,0.0,1.0; llm_name="Mistral-7B (Auto-Routed)" else: resp,conf,wa,wb=ra,ca,1.0,0.0; llm_name="Qwen2.5-1.5B (Auto-Routed)" reason=f"Router: Qwen={qp:.1%}, Mistral={mp:.1%} — {why}" t_gen=max(0.001, round(time.time()-t0, 1)) t_tot=max(0.001, round(time.time()-t_total, 1)) # Evaluate ctx_emb = embedder.encode([" ".join(c["text"] for c in ctx)[:2000]], normalize_embeddings=True)[0] try: faith_sents=[s.strip() for s in sent_tokenize(resp) if len(s.strip())>15] or [resp] except: faith_sents=[resp] supported=sum(1 for fs in faith_sents if float(np.dot(embedder.encode([fs], normalize_embeddings=True)[0], ctx_emb))>0.5) faith=round(supported/max(len(faith_sents),1),4) halluc=round(1.0-faith,4) relev=cos_sim(query,resp) if len(faith_sents)>=2: ce=embedder.encode(faith_sents, normalize_embeddings=True) coher=round(float(np.mean([float(np.dot(ce[i],ce[i+1])) for i in range(len(ce)-1)])),4) else: coher=0.90 sources=[r["chunk"].filename for r in retrieved] return (resp, render_metrics(faith,halluc,relev,coher,conf,t_ret,t_gen,t_tot), render_model(mode,llm_name,wa,wb,top_k,max_tokens,reason), render_context(retrieved), render_sources(sources), render_compare(ra,ca,rb,cb), reason) # ════════════════════════════════════════════════════════════════ # GRADIO UI # ════════════════════════════════════════════════════════════════ with gr.Blocks(title="AHRAG Framework") as demo: gr.HTML("""
AHRAG Enterprise Framework
Adaptive Hybrid Retrieval-Augmented Generation · AHFE Dual-Model Fusion
🟢 LIVE ⚡ Qwen2.5-1.5B + Mistral-7B 🔍 FAISS + KG + Metadata Retrieval 📊 Bayesian AHFE Fusion
""") with gr.Row(equal_height=False): with gr.Column(scale=4, min_width=300): gr.Markdown("### 📝 Query") query_in = gr.Textbox( label="Enter your question", placeholder="e.g., How do LLMs improve construction risk classification?", lines=4, ) gr.Markdown("### ⚙️ Settings") mode_in = gr.Radio( choices=["AHFE Fusion (Both)", "LLM Routing (Auto)", "Qwen2.5-1.5B Only", "Mistral-7B Only"], value="AHFE Fusion (Both)", label="Generation Mode", ) with gr.Row(): topk_in = gr.Slider(1, 10, value=5, step=1, label="Top-K Chunks") maxtok_in = gr.Slider(128, 1024, value=512, step=64, label="Max Tokens") with gr.Row(): submit_btn = gr.Button("🔍 Ask AHRAG", variant="primary", size="lg") clear_btn = gr.Button("🗑️ Clear", variant="secondary", size="lg") gr.Examples( examples=[ ["How do LLMs improve construction risk classification?", "AHFE Fusion (Both)", 5, 512], ["What ML techniques are used for network anomaly detection?", "LLM Routing (Auto)", 5, 512], ["Explain explainable AI for intrusion detection systems", "Mistral-7B Only", 5, 512], ["What is the purpose of SHAP in bug prediction?", "Qwen2.5-1.5B Only", 5, 512], ["Compare supervised and unsupervised learning approaches", "AHFE Fusion (Both)", 5, 512], ], inputs=[query_in, mode_in, topk_in, maxtok_in], ) with gr.Column(scale=7, min_width=480): with gr.Tabs(): with gr.Tab("✨ Response & Metrics"): resp_out = gr.Textbox(label="AHRAG Answer", lines=8) with gr.Row(): metrics_out = gr.HTML() model_out = gr.HTML() with gr.Tab("📚 Context & Sources"): source_out = gr.HTML() context_out = gr.HTML() with gr.Tab("⚖️ Qwen vs Mistral"): compare_out = gr.HTML() with gr.Tab("🧭 Routing Log"): routing_out = gr.Textbox(label="Routing Decision", lines=4) _out = [resp_out, metrics_out, model_out, context_out, source_out, compare_out, routing_out] _inp = [query_in, mode_in, topk_in, maxtok_in] submit_btn.click(fn=process_query, inputs=_inp, outputs=_out) query_in.submit(fn=process_query, inputs=_inp, outputs=_out) clear_btn.click(fn=lambda: ("","","","","","",""), outputs=_out) # ════════════════════════════════════════════════════════════════ # LAUNCH # ════════════════════════════════════════════════════════════════ print("\n" + "="*60) print(" AHRAG GRADIO READY") print("="*60) demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)