Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -7,98 +7,83 @@ import google.generativeai as genai
|
|
7 |
import re
|
8 |
import os
|
9 |
|
10 |
-
# Load
|
11 |
-
def
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
return docs_df, index
|
18 |
|
19 |
-
docs_df, index =
|
20 |
|
21 |
-
#
|
22 |
-
|
23 |
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
genai.
|
29 |
-
model = genai.GenerativeModel('gemini-2.0-flash')
|
30 |
|
31 |
-
#
|
32 |
-
def
|
33 |
text = text.lower()
|
34 |
-
text =
|
35 |
-
|
36 |
-
text = ' '.join(text.split()).strip()
|
37 |
-
return text
|
38 |
|
39 |
-
# Retrieve
|
40 |
-
def
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
retrieved_docs['distance'] = distances[0]
|
45 |
-
return retrieved_docs
|
46 |
|
47 |
-
# RAG
|
48 |
-
def
|
49 |
-
|
50 |
-
|
51 |
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
f"
|
60 |
-
f"
|
61 |
-
f"
|
62 |
-
f"
|
|
|
|
|
|
|
63 |
)
|
64 |
-
|
65 |
-
|
66 |
-
response = model.generate_content(
|
67 |
prompt,
|
68 |
generation_config=genai.types.GenerationConfig(
|
69 |
max_output_tokens=max_tokens,
|
70 |
-
temperature=
|
71 |
)
|
72 |
)
|
73 |
-
|
74 |
-
if not answer.endswith('.'):
|
75 |
-
last_period = answer.rfind('.')
|
76 |
-
if last_period != -1:
|
77 |
-
answer = answer[:last_period + 1]
|
78 |
-
else:
|
79 |
-
answer += "."
|
80 |
-
|
81 |
-
return answer
|
82 |
-
|
83 |
-
# Simple Gradio Interface
|
84 |
-
def chatbot_interface(message, system_message, max_tokens, temperature):
|
85 |
-
return respond(message, system_message, max_tokens, temperature)
|
86 |
|
|
|
87 |
demo = gr.Interface(
|
88 |
-
fn=
|
89 |
inputs=[
|
90 |
-
gr.Textbox(label="
|
91 |
gr.Textbox(
|
92 |
-
value="You are a medical
|
93 |
-
label="System
|
94 |
),
|
95 |
-
gr.Slider(
|
96 |
-
gr.Slider(
|
97 |
],
|
98 |
-
outputs=gr.Textbox(label="
|
99 |
-
title="
|
100 |
-
description="
|
101 |
)
|
102 |
|
103 |
if __name__ == "__main__":
|
104 |
-
demo.launch()
|
|
|
7 |
import re
|
8 |
import os
|
9 |
|
10 |
+
# Load documents and FAISS index
|
11 |
+
def load_index_and_data():
|
12 |
+
df = pd.read_pickle("data.pkl")
|
13 |
+
vecs = np.array(df['embeddings'].tolist(), dtype=np.float32)
|
14 |
+
idx = faiss.IndexFlatL2(vecs.shape[1])
|
15 |
+
idx.add(vecs)
|
16 |
+
return df, idx
|
|
|
17 |
|
18 |
+
docs_df, index = load_index_and_data()
|
19 |
|
20 |
+
# Embedding model and Gemini setup
|
21 |
+
encoder = SentenceTransformer("all-MiniLM-L6-v2")
|
22 |
|
23 |
+
API_KEY = os.getenv("GEMINI_API_KEY")
|
24 |
+
if not API_KEY:
|
25 |
+
raise EnvironmentError("Missing Gemini API key.")
|
26 |
+
genai.configure(api_key=API_KEY)
|
27 |
+
llm = genai.GenerativeModel("gemini-2.0-flash")
|
|
|
28 |
|
29 |
+
# Clean text input
|
30 |
+
def clean_text(text):
|
31 |
text = text.lower()
|
32 |
+
text = re.sub(r"[^\w\s.,]", " ", text)
|
33 |
+
return " ".join(text.split())
|
|
|
|
|
34 |
|
35 |
+
# Retrieve relevant document context
|
36 |
+
def get_context(query, k=5):
|
37 |
+
q_vec = encoder.encode([query])[0].astype(np.float32)
|
38 |
+
_, indices = index.search(np.array([q_vec]), k)
|
39 |
+
return "\n".join(docs_df.iloc[indices[0]]["text"].tolist())
|
|
|
|
|
40 |
|
41 |
+
# RAG-based Gemini response generation
|
42 |
+
def generate_answer(user_input, system_note, max_tokens, temp):
|
43 |
+
query = clean_text(user_input)
|
44 |
+
context = get_context(query)
|
45 |
|
46 |
+
prompt = (
|
47 |
+
f"Role Description:\n{system_note}\n\n"
|
48 |
+
f"User Question:\n{user_input}\n\n"
|
49 |
+
f"Knowledge Extracted From Records:\n{context}\n\n"
|
50 |
+
f"Instructions:\n"
|
51 |
+
f"- Analyze the user's query using ONLY the above context.\n"
|
52 |
+
f"- Do NOT add external or made-up information.\n"
|
53 |
+
f"- Begin with a brief summary of the identified condition or concern.\n"
|
54 |
+
f"- Provide detailed reasoning and explanation in bullet points:\n"
|
55 |
+
f" • Include possible causes, symptoms, and diagnostic considerations.\n"
|
56 |
+
f" • Mention relevant terms or observations from context.\n"
|
57 |
+
f" • Explain how the context supports the conclusions.\n"
|
58 |
+
f"- End with a short, clear recommendation (if context permits).\n"
|
59 |
+
f"- Avoid medical advice unless the context contains it."
|
60 |
)
|
61 |
+
|
62 |
+
result = llm.generate_content(
|
|
|
63 |
prompt,
|
64 |
generation_config=genai.types.GenerationConfig(
|
65 |
max_output_tokens=max_tokens,
|
66 |
+
temperature=temp
|
67 |
)
|
68 |
)
|
69 |
+
return result.text.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
+
# Gradio interface
|
72 |
demo = gr.Interface(
|
73 |
+
fn=generate_answer,
|
74 |
inputs=[
|
75 |
+
gr.Textbox(label="Ask Something", placeholder="Describe your symptom or condition..."),
|
76 |
gr.Textbox(
|
77 |
+
value="You are a virtual medical assistant using past medical records to respond intelligently.",
|
78 |
+
label="System Role"
|
79 |
),
|
80 |
+
gr.Slider(50, 500, value=300, step=10, label="Max Tokens"),
|
81 |
+
gr.Slider(0.0, 1.0, value=0.4, step=0.1, label="Creativity (Temperature)")
|
82 |
],
|
83 |
+
outputs=gr.Textbox(label="AI Diagnosis"),
|
84 |
+
title="🩺 Smart Medical Query Assistant",
|
85 |
+
description="Submit a health-related question. The assistant analyzes similar past records to respond accurately and clearly."
|
86 |
)
|
87 |
|
88 |
if __name__ == "__main__":
|
89 |
+
demo.launch()
|