LonewolfT141 commited on
Commit
c0f2cc0
·
verified ·
1 Parent(s): 4363e71

Update app.py

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