Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,62 +1,147 @@
|
|
1 |
from langchain_google_genai import GoogleGenerativeAI
|
2 |
import streamlit as st
|
|
|
|
|
3 |
|
4 |
-
#
|
5 |
-
|
6 |
-
model
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
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 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from langchain_google_genai import GoogleGenerativeAI
|
2 |
import streamlit as st
|
3 |
+
import re
|
4 |
+
from datetime import datetime
|
5 |
|
6 |
+
# --- Configuration ---
|
7 |
+
MODEL_CONFIG = {
|
8 |
+
"model": "gemini-pro",
|
9 |
+
"temperature": 0.7,
|
10 |
+
"top_p": 0.85,
|
11 |
+
"max_tokens": 1024,
|
12 |
+
"safety_settings": {
|
13 |
+
"HARASSMENT":"BLOCK_ONLY_HIGH",
|
14 |
+
"HATE_SPEECH":"BLOCK_ONLY_HIGH",
|
15 |
+
"SEXUAL":"BLOCK_ONLY_HIGH",
|
16 |
+
"DANGEROUS":"BLOCK_ONLY_HIGH"
|
17 |
+
}
|
18 |
+
}
|
19 |
+
|
20 |
+
EMERGENCY_CONTACTS = {
|
21 |
+
"Hospital Address": "John Smith Hospital, 123 Health St.",
|
22 |
+
"Ambulance": "911 (US) / 112 (EU)",
|
23 |
+
"24/7 Support": "+1-800-123-4567"
|
24 |
+
}
|
25 |
+
|
26 |
+
# --- Security & Sanitization ---
|
27 |
+
def sanitize_input(text):
|
28 |
+
"""Remove potentially harmful patterns"""
|
29 |
+
return re.sub(r"[<>{}[\]~`]", "", text[:2000])
|
30 |
+
|
31 |
+
# --- AI Response Validation ---
|
32 |
+
def validate_medical_response(text):
|
33 |
+
"""Basic safety checks for AI responses"""
|
34 |
+
blacklist = ["take your own life", "kill yourself", "hate you"]
|
35 |
+
return not any(phrase in text.lower() for phrase in blacklist)
|
36 |
+
|
37 |
+
# --- Streamlit App ---
|
38 |
+
def main():
|
39 |
+
st.set_page_config(
|
40 |
+
page_title="DoctorX: AI Health Assistant",
|
41 |
+
page_icon="🩺",
|
42 |
+
layout="centered",
|
43 |
+
initial_sidebar_state="collapsed"
|
44 |
+
)
|
45 |
+
|
46 |
+
# Initialize session state
|
47 |
+
if "history" not in st.session_state:
|
48 |
+
st.session_state.history = []
|
49 |
+
|
50 |
+
# --- Sidebar with Emergency Info ---
|
51 |
+
with st.sidebar:
|
52 |
+
st.header("🆘 Emergency Contacts")
|
53 |
+
for key, value in EMERGENCY_CONTACTS.items():
|
54 |
+
st.subheader(key)
|
55 |
+
st.caption(value)
|
56 |
+
st.divider()
|
57 |
+
st.caption("⚠️ This is not a substitute for emergency medical care")
|
58 |
+
|
59 |
+
# --- Main Interface ---
|
60 |
+
st.title("🩺 DoctorX Health Assistant")
|
61 |
+
st.caption("AI-powered preliminary health guidance - Always consult a human doctor for final diagnosis")
|
62 |
+
|
63 |
+
# Display chat history
|
64 |
+
for role, message in st.session_state.history:
|
65 |
+
with st.chat_message(role):
|
66 |
+
st.markdown(message)
|
67 |
+
|
68 |
+
# User input with enhanced options
|
69 |
+
with st.form("chat_input"):
|
70 |
+
col1, col2 = st.columns([4, 1])
|
71 |
+
with col1:
|
72 |
+
user_input = st.text_input(
|
73 |
+
"Describe your symptoms or ask a question:",
|
74 |
+
placeholder="E.g., I've had a headache for 3 days...",
|
75 |
+
max_chars=500
|
76 |
+
)
|
77 |
+
with col2:
|
78 |
+
if st.form_submit_button("Send", use_container_width=True):
|
79 |
+
user_input = sanitize_input(user_input.strip())
|
80 |
+
|
81 |
+
if user_input.lower() in ["emergency", "911", "112"]:
|
82 |
+
st.session_state.history.append(("user", user_input))
|
83 |
+
st.session_state.history.append(("bot", "🚨 Please use the emergency contacts in the sidebar immediately!"))
|
84 |
+
st.rerun()
|
85 |
+
|
86 |
+
elif user_input:
|
87 |
+
process_user_input(user_input)
|
88 |
+
|
89 |
+
# Quick symptom buttons
|
90 |
+
common_symptoms = ["Fever", "Headache", "Cough", "Rash", "Nausea"]
|
91 |
+
cols = st.columns(len(common_symptoms))
|
92 |
+
for col, symptom in zip(cols, common_symptoms):
|
93 |
+
if col.button(symptom):
|
94 |
+
process_user_input(f"I'm experiencing {symptom.lower()}")
|
95 |
+
|
96 |
+
# Quick response buttons for common queries
|
97 |
+
common_queries = ["What are the symptoms of epilepsy?", "How to manage stress?"]
|
98 |
+
cols = st.columns(len(common_queries))
|
99 |
+
for col, query in zip(cols, common_queries):
|
100 |
+
if col.button(query):
|
101 |
+
process_user_input(query)
|
102 |
+
|
103 |
+
def process_user_input(user_input):
|
104 |
+
"""Handle user input and generate AI response"""
|
105 |
+
llm = GoogleGenerativeAI(google_api_key=st.secrets["GOOGLE_API_KEY"], **MODEL_CONFIG)
|
106 |
+
|
107 |
+
# Build medical context
|
108 |
+
system_prompt = f"""
|
109 |
+
You are DoctorX, an AI medical assistant. Follow these rules STRICTLY:
|
110 |
+
1. Never diagnose - suggest POSSIBLE conditions
|
111 |
+
2. Always recommend consulting a human doctor
|
112 |
+
3. Prioritize patient safety over all else
|
113 |
+
4. Maintain professional, empathetic tone
|
114 |
+
5. Disclose your AI nature clearly
|
115 |
+
6. For emergencies, direct to sidebar contacts
|
116 |
+
|
117 |
+
Current Date: {datetime.now().strftime("%Y-%m-%d")}
|
118 |
+
User Input: {user_input}
|
119 |
+
"""
|
120 |
+
|
121 |
+
try:
|
122 |
+
with st.chat_message("user"):
|
123 |
+
st.markdown(user_input)
|
124 |
+
|
125 |
+
with st.chat_message("bot"):
|
126 |
+
with st.spinner("🔍 Analyzing symptoms..."):
|
127 |
+
response = llm.invoke(system_prompt)
|
128 |
+
|
129 |
+
if not validate_medical_response(response):
|
130 |
+
raise ValueError("Response validation failed")
|
131 |
+
|
132 |
+
# Format medical information
|
133 |
+
response = response.replace("**Possible Condition:**", "\n🩺 **Possible Condition:**")
|
134 |
+
response = response.replace("**Recommendation:**", "\n📋 **Recommendation:**")
|
135 |
+
|
136 |
+
st.markdown(response)
|
137 |
+
st.caption("ℹ️ AI-generated suggestion - Verify with healthcare professional")
|
138 |
+
|
139 |
+
st.session_state.history.append(("user", user_input))
|
140 |
+
st.session_state.history.append(("bot", response))
|
141 |
+
|
142 |
+
except Exception as e:
|
143 |
+
st.error(f"⚠️ System Error: {str(e)}")
|
144 |
+
st.session_state.history.append(("bot", "🚨 Error processing request. Please try again later."))
|
145 |
+
|
146 |
+
if __name__ == "__main__":
|
147 |
+
main()
|