Haseeb-001 commited on
Commit
1215503
·
verified ·
1 Parent(s): 956a0a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -59
app.py CHANGED
@@ -1,62 +1,147 @@
1
  from langchain_google_genai import GoogleGenerativeAI
2
  import streamlit as st
 
 
3
 
4
- # initializing llm
5
- llm = GoogleGenerativeAI(
6
- model="gemini-1.5-flash",
7
- google_api_key="AIzaSyDgOkz_5iou4gl5aaDUNyXfhb63W3E27-o",
8
- temperature=0.7,
9
- top_p=0.9,
10
- max_tokens=1000,
11
- frequency_penalty=0.5,
12
- presence_penalty=0.3,
13
- stop_sequences=["User:", "Assistant:"]
14
- )
15
-
16
- # initializing role, requirements
17
- instruction = "Answer user's(patient) questions politely and provide him accurate information."
18
- context = (
19
- "You are a medical assistant doctor named DoctorX."
20
- "You will ask user which might be a patient about his health, get symptoms from him, predicts his disease and suggest him a good and quick remeedy or prescription based on users condition."
21
- "Continue Asking more about his condition or health and suggest him a doctor if required."
22
- "Also give user you a good line to reduce his tension"
23
- )
24
- input_data = (
25
- "Additional information:\n",
26
- "Hospital Address: John Smith Hospital",
27
- "Ambulance Call: 1111",
28
- "Doctor Number: +3100-1000-100"
29
- )
30
-
31
- # Streamlit UI Setup
32
- st.set_page_config(page_title="DoctorX: HealthCare", layout="wide")
33
- st.title("🧠 DoctorX: HealthCare")
34
-
35
- # Enhanced logic for chatbot interaction
36
- if prompt := st.chat_input("Type your question here..."):
37
- with st.chat_message("user"):
38
- st.markdown(prompt)
39
-
40
- with st.chat_message("bot"):
41
- with st.spinner("🤖 Thinking..."):
42
- try:
43
- # Constructing the prompt with enhanced context
44
- enhanced_prompt = (
45
- f"{instruction}\n\n"
46
- f"{context}\n\n"
47
- f"{input_data}\n\n"
48
- f"User's Query: {prompt}\n\n"
49
- "Follow-up: Ask the user about their symptoms, provide a possible diagnosis, and suggest remedies or prescriptions."
50
- )
51
-
52
- # Stream the response from the LLM
53
- response = ""
54
- for chunk in llm.stream(enhanced_prompt):
55
- response += chunk
56
- st.markdown(response) # Display the response incrementally
57
-
58
- # Add stress-relief advice
59
- st.markdown("\n**Stress-Relief Tip:** Remember to take deep breaths and stay hydrated.")
60
-
61
- except Exception as e:
62
- st.error(f"⚠️ Error processing query: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()