Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,122 +1,134 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import re
|
| 3 |
-
import faiss
|
| 4 |
-
import numpy as np
|
| 5 |
-
import pandas as pd
|
| 6 |
-
import torch
|
| 7 |
-
import gradio as gr
|
| 8 |
-
|
| 9 |
-
from
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
# -----------------------------
|
| 17 |
-
# Load
|
| 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 |
-
def
|
| 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 |
interface.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import faiss
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import torch
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
+
from transformers import (
|
| 11 |
+
AutoTokenizer,
|
| 12 |
+
AutoModelForCausalLM,
|
| 13 |
+
BitsAndBytesConfig
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# -----------------------------
|
| 17 |
+
# Load Embedding Model
|
| 18 |
+
# -----------------------------
|
| 19 |
+
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 20 |
+
|
| 21 |
+
# -----------------------------
|
| 22 |
+
# Load Data
|
| 23 |
+
# -----------------------------
|
| 24 |
+
docs_df = pd.read_pickle("docs.pkl") # make sure this file exists in HF Space
|
| 25 |
+
|
| 26 |
+
embeddings = np.array(docs_df["embeddings"].tolist()).astype("float32")
|
| 27 |
+
|
| 28 |
+
# Normalize for cosine similarity
|
| 29 |
+
faiss.normalize_L2(embeddings)
|
| 30 |
+
|
| 31 |
+
dimension = embeddings.shape[1]
|
| 32 |
+
index = faiss.IndexFlatIP(dimension)
|
| 33 |
+
index.add(embeddings)
|
| 34 |
+
|
| 35 |
+
# -----------------------------
|
| 36 |
+
# Load LLM (Mistral 7B 4-bit)
|
| 37 |
+
# -----------------------------
|
| 38 |
+
model_name = "mistralai/Mistral-7B-Instruct-v0.1"
|
| 39 |
+
|
| 40 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 41 |
+
|
| 42 |
+
bnb_config = BitsAndBytesConfig(
|
| 43 |
+
load_in_4bit=True,
|
| 44 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 45 |
+
bnb_4bit_use_double_quant=True,
|
| 46 |
+
bnb_4bit_quant_type="nf4"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 50 |
+
model_name,
|
| 51 |
+
device_map="auto",
|
| 52 |
+
quantization_config=bnb_config
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# -----------------------------
|
| 56 |
+
# Preprocessing
|
| 57 |
+
# -----------------------------
|
| 58 |
+
def preprocess_text(text):
|
| 59 |
+
text = text.lower()
|
| 60 |
+
text = text.replace("\n", " ").replace("\t", " ")
|
| 61 |
+
text = re.sub(r"[^\w\s.,;:>-]", " ", text)
|
| 62 |
+
return " ".join(text.split()).strip()
|
| 63 |
+
|
| 64 |
+
# -----------------------------
|
| 65 |
+
# Retrieval Function
|
| 66 |
+
# -----------------------------
|
| 67 |
+
def retrieve_docs(query, k=3):
|
| 68 |
+
query_embedding = embedding_model.encode([query])[0].astype("float32")
|
| 69 |
+
faiss.normalize_L2(query_embedding.reshape(1, -1))
|
| 70 |
+
|
| 71 |
+
distances, indices = index.search(np.array([query_embedding]), k)
|
| 72 |
+
|
| 73 |
+
results = docs_df.iloc[indices[0]].copy()
|
| 74 |
+
results["score"] = distances[0]
|
| 75 |
+
|
| 76 |
+
return results
|
| 77 |
+
|
| 78 |
+
# -----------------------------
|
| 79 |
+
# RAG Pipeline
|
| 80 |
+
# -----------------------------
|
| 81 |
+
def rag_pipeline(query):
|
| 82 |
+
query = preprocess_text(query)
|
| 83 |
+
|
| 84 |
+
retrieved_docs = retrieve_docs(query)
|
| 85 |
+
context = "\n".join(retrieved_docs["text"].tolist())
|
| 86 |
+
|
| 87 |
+
prompt = f"""
|
| 88 |
+
You are a medical assistant.
|
| 89 |
+
|
| 90 |
+
Only answer using the provided context.
|
| 91 |
+
If the answer is not in the context, say: "Insufficient information."
|
| 92 |
+
|
| 93 |
+
Query:
|
| 94 |
+
{query}
|
| 95 |
+
|
| 96 |
+
Context:
|
| 97 |
+
{context}
|
| 98 |
+
|
| 99 |
+
Answer:
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 103 |
+
inputs = {k: v.to(model.device) for k, v in inputs.items()}
|
| 104 |
+
|
| 105 |
+
outputs = model.generate(
|
| 106 |
+
**inputs,
|
| 107 |
+
max_new_tokens=150,
|
| 108 |
+
temperature=0.1,
|
| 109 |
+
do_sample=False
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 113 |
+
|
| 114 |
+
return answer, retrieved_docs[["source", "score"]]
|
| 115 |
+
|
| 116 |
+
# -----------------------------
|
| 117 |
+
# Gradio Interface
|
| 118 |
+
# -----------------------------
|
| 119 |
+
def app_fn(query):
|
| 120 |
+
answer, sources = rag_pipeline(query)
|
| 121 |
+
return answer, sources
|
| 122 |
+
|
| 123 |
+
interface = gr.Interface(
|
| 124 |
+
fn=app_fn,
|
| 125 |
+
inputs=gr.Textbox(label="Enter Medical Query"),
|
| 126 |
+
outputs=[
|
| 127 |
+
gr.Textbox(label="AI Response"),
|
| 128 |
+
gr.Dataframe(label="Retrieved Sources")
|
| 129 |
+
],
|
| 130 |
+
title="🧠 Medical RAG Assistant (FAISS + Mistral 7B)",
|
| 131 |
+
description="Retrieval-Augmented Generation system using FAISS + Mistral 7B Instruct (4-bit)"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
interface.launch()
|