Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,86 +1,221 @@
|
|
1 |
-
from
|
2 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
# ---
|
5 |
-
|
6 |
-
|
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 |
st.set_page_config(
|
37 |
-
page_title="DoctorX",
|
38 |
-
page_icon="
|
39 |
layout="wide",
|
40 |
initial_sidebar_state="expanded"
|
41 |
)
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
st.session_state.history = []
|
46 |
-
|
47 |
-
# Sidebar for emergency contacts
|
48 |
with st.sidebar:
|
|
|
49 |
st.header("π¨ Emergency Contacts")
|
50 |
-
for key, value in
|
51 |
st.subheader(key)
|
52 |
st.caption(value)
|
53 |
st.divider()
|
54 |
-
st.
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
st.
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
cols = st.columns(len(common_queries))
|
78 |
for col, query in zip(cols, common_queries):
|
79 |
if col.button(query):
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
if __name__ == "__main__":
|
86 |
main()
|
|
|
1 |
+
from groq import Groq
|
2 |
import streamlit as st
|
3 |
+
import re
|
4 |
+
from datetime import datetime
|
5 |
+
# import os
|
6 |
+
from typing import Generator, List, Tuple, Optional
|
7 |
+
import logging
|
8 |
+
# from dotenv import load_dotenv
|
9 |
|
10 |
+
# --- Load Environment Variables ---
|
11 |
+
# load_dotenv()
|
12 |
+
|
13 |
+
# --- Logging Configuration ---
|
14 |
+
logging.basicConfig(level=logging.INFO)
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
+
|
17 |
+
# --- Constants ---
|
18 |
+
MODEL_CONFIG = {
|
19 |
+
"model": "meta-llama/llama-4-scout-17b-16e-instruct",
|
20 |
+
"temperature": 0.5,
|
21 |
+
"max_completion_tokens": 1024,
|
22 |
+
"stream": True,
|
23 |
+
"stop": None
|
24 |
+
}
|
25 |
+
|
26 |
+
EMERGENCY_CONTACTS = {
|
27 |
+
"Hospital Address": "John Smith Hospital, 123 Health St.",
|
28 |
+
"Ambulance": "911 (US) / 112 (EU)",
|
29 |
+
"24/7 Support": "+1-800-123-4567"
|
30 |
+
}
|
31 |
+
|
32 |
+
EMERGENCY_KEYWORDS = [
|
33 |
+
"emergency", "911", "112", "immediate help",
|
34 |
+
"severe pain", "cannot breathe", "chest pain",
|
35 |
+
"unconscious", "seizure", "stroke"
|
36 |
+
]
|
37 |
+
|
38 |
+
SYSTEM_PROMPT = """You are DoctorX, a medical AI assistant. Follow these guidelines:
|
39 |
+
1. Never diagnose - only suggest possible conditions
|
40 |
+
2. Always recommend consulting a medical professional
|
41 |
+
3. Prioritize patient safety and well-being
|
42 |
+
4. Maintain professional yet empathetic tone
|
43 |
+
5. Be clear about being an AI
|
44 |
+
6. For emergencies, direct to emergency services
|
45 |
+
|
46 |
+
Format your responses as follows:
|
47 |
+
π€ AI Assistant: [Your greeting]
|
48 |
+
π Understanding: [Brief interpretation of the query]
|
49 |
+
π₯ Medical Context: [Relevant medical information]
|
50 |
+
π Suggestions:
|
51 |
+
- [Point 1]
|
52 |
+
- [Point 2]
|
53 |
+
β οΈ Important: Always consult a healthcare professional for proper diagnosis and treatment."""
|
54 |
+
|
55 |
+
# --- Security & Input Validation ---
|
56 |
+
def sanitize_input(text: str) -> str:
|
57 |
+
"""Remove potentially harmful patterns from user input."""
|
58 |
+
if not text:
|
59 |
+
return ""
|
60 |
+
# Remove potential XSS and injection patterns
|
61 |
+
sanitized = re.sub(r"[<>{}[\]~`]", "", text[:2000])
|
62 |
+
return sanitized.strip()
|
63 |
+
|
64 |
+
def validate_response(response: str) -> bool:
|
65 |
+
"""Validate AI response for safety concerns."""
|
66 |
+
blacklist = ["take your own life", "kill yourself", "hate you"]
|
67 |
+
return not any(phrase in response.lower() for phrase in blacklist)
|
68 |
+
|
69 |
+
def process_emergency(query: str) -> bool:
|
70 |
+
"""Check if query indicates a medical emergency."""
|
71 |
+
return any(keyword in query.lower() for keyword in EMERGENCY_KEYWORDS)
|
72 |
+
|
73 |
+
def generate_medical_response(query: str, chat_history: List[Tuple[str, str]]) -> Generator[str, None, None]:
|
74 |
+
"""
|
75 |
+
Generate a medical response using the LLM with streaming support.
|
76 |
+
|
77 |
+
Args:
|
78 |
+
query: The user's medical query
|
79 |
+
chat_history: List of previous interactions as (role, message) tuples
|
80 |
+
|
81 |
+
Yields:
|
82 |
+
Chunks of the generated response
|
83 |
+
"""
|
84 |
+
try:
|
85 |
+
# Format chat history
|
86 |
+
history_messages = [
|
87 |
+
{"role": "user" if role == "user" else "assistant", "content": msg}
|
88 |
+
for role, msg in chat_history[-5:]
|
89 |
+
]
|
90 |
+
|
91 |
+
# Construct messages with system prompt
|
92 |
+
messages = [
|
93 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
94 |
+
*history_messages,
|
95 |
+
{"role": "user", "content": query}
|
96 |
+
]
|
97 |
+
|
98 |
+
# Generate streaming response
|
99 |
+
completion = client.chat.completions.create(
|
100 |
+
messages=messages,
|
101 |
+
**MODEL_CONFIG
|
102 |
+
)
|
103 |
+
|
104 |
+
# Process response chunks
|
105 |
+
for chunk in completion:
|
106 |
+
if chunk.choices[0].delta.content:
|
107 |
+
yield chunk.choices[0].delta.content
|
108 |
+
|
109 |
+
except Exception as e:
|
110 |
+
logger.error(f"Error generating response: {str(e)}")
|
111 |
+
yield "I apologize, but I encountered an error. Please try again or contact support."
|
112 |
+
|
113 |
+
# --- Main Application ---
|
114 |
+
def initialize_session_state() -> None:
|
115 |
+
"""Initialize Streamlit session state variables."""
|
116 |
+
if "chat_history" not in st.session_state:
|
117 |
+
st.session_state.chat_history = []
|
118 |
+
|
119 |
+
def setup_page() -> None:
|
120 |
+
"""Configure Streamlit page settings."""
|
121 |
st.set_page_config(
|
122 |
+
page_title="DoctorX - Your AI Health Assistant",
|
123 |
+
page_icon="π§ ",
|
124 |
layout="wide",
|
125 |
initial_sidebar_state="expanded"
|
126 |
)
|
127 |
|
128 |
+
def render_sidebar() -> None:
|
129 |
+
"""Render the sidebar with emergency information."""
|
|
|
|
|
|
|
130 |
with st.sidebar:
|
131 |
+
st.image("https://img.icons8.com/color/96/000000/heart-health.png")
|
132 |
st.header("π¨ Emergency Contacts")
|
133 |
+
for key, value in EMERGENCY_CONTACTS.items():
|
134 |
st.subheader(key)
|
135 |
st.caption(value)
|
136 |
st.divider()
|
137 |
+
st.warning("β οΈ This is not a substitute for emergency medical care")
|
138 |
+
|
139 |
+
def handle_user_input(user_input: str) -> None:
|
140 |
+
"""Process and respond to user input."""
|
141 |
+
cleaned_input = sanitize_input(user_input)
|
142 |
+
|
143 |
+
if process_emergency(cleaned_input):
|
144 |
+
st.error("π¨ This appears to be an emergency. Please contact emergency services immediately!")
|
145 |
+
st.info("See emergency contacts in the sidebar β")
|
146 |
+
return
|
147 |
+
|
148 |
+
st.session_state.chat_history.append(("user", cleaned_input))
|
149 |
+
|
150 |
+
with st.chat_message("assistant"):
|
151 |
+
response_placeholder = st.empty()
|
152 |
+
full_response = []
|
153 |
+
|
154 |
+
with st.spinner("π€ Analyzing your query..."):
|
155 |
+
for response_chunk in generate_medical_response(cleaned_input, st.session_state.chat_history):
|
156 |
+
full_response.append(response_chunk)
|
157 |
+
response_placeholder.markdown("".join(full_response))
|
158 |
+
|
159 |
+
if validate_response("".join(full_response)):
|
160 |
+
st.session_state.chat_history.append(("assistant", "".join(full_response)))
|
161 |
+
else:
|
162 |
+
safe_response = "I apologize, but I cannot provide that information. Please consult a healthcare professional."
|
163 |
+
response_placeholder.markdown(safe_response)
|
164 |
+
st.session_state.chat_history.append(("assistant", safe_response))
|
165 |
+
|
166 |
+
def render_quick_access_buttons() -> None:
|
167 |
+
"""Render quick access buttons for common health queries."""
|
168 |
+
st.divider()
|
169 |
+
st.subheader("π Common Health Topics")
|
170 |
+
|
171 |
+
common_queries = [
|
172 |
+
"What are common symptoms of anxiety?",
|
173 |
+
"How to maintain good sleep hygiene?",
|
174 |
+
"When should I see a doctor about headaches?",
|
175 |
+
"Tips for managing stress",
|
176 |
+
"Understanding blood pressure readings"
|
177 |
+
]
|
178 |
+
|
179 |
cols = st.columns(len(common_queries))
|
180 |
for col, query in zip(cols, common_queries):
|
181 |
if col.button(query):
|
182 |
+
handle_user_input(query)
|
183 |
+
|
184 |
+
def main() -> None:
|
185 |
+
"""Main application function."""
|
186 |
+
try:
|
187 |
+
setup_page()
|
188 |
+
initialize_session_state()
|
189 |
+
render_sidebar()
|
190 |
+
|
191 |
+
st.title("π§ DoctorX")
|
192 |
+
st.caption("Preliminary health guidance - Always consult healthcare professionals")
|
193 |
+
|
194 |
+
# Display chat history
|
195 |
+
for role, message in st.session_state.chat_history:
|
196 |
+
with st.chat_message(role):
|
197 |
+
st.markdown(message)
|
198 |
+
|
199 |
+
# Handle user input
|
200 |
+
if user_input := st.chat_input("Type your health question here...", key="user_input"):
|
201 |
+
handle_user_input(user_input)
|
202 |
+
|
203 |
+
render_quick_access_buttons()
|
204 |
+
|
205 |
+
except Exception as e:
|
206 |
+
logger.error(f"Application error: {str(e)}")
|
207 |
+
st.error("An unexpected error occurred. Please refresh the page and try again.")
|
208 |
+
|
209 |
+
# --- LLM Initialization ---
|
210 |
+
try:
|
211 |
+
# client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
212 |
+
client = Groq(api_key=GROQ_API_KEY)
|
213 |
+
if not client:
|
214 |
+
raise ValueError("Failed to initialize Groq client. Please check your API key.")
|
215 |
+
except Exception as e:
|
216 |
+
logger.error(f"Error initializing Groq client: {str(e)}")
|
217 |
+
st.error("Failed to initialize AI model. Please check your API key.")
|
218 |
+
st.stop()
|
219 |
|
220 |
if __name__ == "__main__":
|
221 |
main()
|