Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -14,10 +14,10 @@ from email.mime.text import MIMEText
|
|
14 |
import re
|
15 |
import json
|
16 |
|
17 |
-
# Configure Gemini API
|
18 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
19 |
|
20 |
-
# Gmail API configuration
|
21 |
GMAIL_ADDRESS = os.getenv("GMAIL_ADDRESS")
|
22 |
GMAIL_TOKEN_JSON = os.getenv("GMAIL_TOKEN_JSON")
|
23 |
|
@@ -25,19 +25,19 @@ GMAIL_TOKEN_JSON = os.getenv("GMAIL_TOKEN_JSON")
|
|
25 |
def get_gmail_service():
|
26 |
try:
|
27 |
creds = Credentials.from_authorized_user_info(json.loads(GMAIL_TOKEN_JSON))
|
28 |
-
return build("gmail", "v1", credentials=creds)
|
29 |
except Exception as e:
|
30 |
-
|
31 |
|
32 |
# Coping Strategies Library
|
33 |
coping_strategies = {
|
34 |
"happy": [
|
35 |
-
"Keep the positivity flowing! Try writing down three things you
|
36 |
"Share your joy! Call a friend or loved one to spread the good vibes."
|
37 |
],
|
38 |
"sad": [
|
39 |
-
"It
|
40 |
-
"Write down your thoughts in a journal to process what
|
41 |
],
|
42 |
"anxious": [
|
43 |
"Take slow, deep breaths: inhale for 4 seconds, hold for 4, exhale for 4.",
|
@@ -47,9 +47,25 @@ coping_strategies = {
|
|
47 |
"Pause for a moment and stretch your body to release tension.",
|
48 |
"Break tasks into smaller steps and tackle one at a time."
|
49 |
],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
"other": [
|
51 |
-
"Reflect on what
|
52 |
-
"Engage in a favorite
|
53 |
]
|
54 |
}
|
55 |
|
@@ -81,17 +97,17 @@ therapists = {
|
|
81 |
"Dr. Jane Smith": {
|
82 |
"specialty": "Anxiety and Depression",
|
83 |
"email": "[email protected]",
|
84 |
-
"times": ["09:00", "11:00", "14:00", "
|
85 |
},
|
86 |
"Dr. Amit Patel": {
|
87 |
"specialty": "Stress Management",
|
88 |
"email": "[email protected]",
|
89 |
-
"times": ["10:00", "12:00", "15:00", "
|
90 |
},
|
91 |
"Dr. Sarah Brown": {
|
92 |
"specialty": "Trauma and PTSD",
|
93 |
"email": "[email protected]",
|
94 |
-
"times": ["08:00", "13:00", "
|
95 |
}
|
96 |
}
|
97 |
|
@@ -101,66 +117,60 @@ model = genai.GenerativeModel("gemini-1.5-flash",
|
|
101 |
|
102 |
# Chatbot function
|
103 |
def chatbot_function(message, mood, conversation_mode, region, state):
|
104 |
-
# Initialize chat history if not present
|
105 |
if "chat_history" not in state:
|
106 |
state["chat_history"] = []
|
107 |
|
108 |
history = state["chat_history"]
|
109 |
|
110 |
-
|
|
|
|
|
111 |
try:
|
112 |
-
lang = detect(message)
|
113 |
except:
|
114 |
lang = "en"
|
115 |
|
116 |
-
|
117 |
-
if mood and mood != "Select mood (optional)":
|
118 |
history.append([f"I'm feeling {mood.lower()}.", None])
|
119 |
|
120 |
-
# Append user message
|
121 |
history.append([message, None])
|
122 |
|
123 |
-
# Themed Conversation Modes: Adjust tone
|
124 |
tone_instruction = {
|
|
|
125 |
"Calm": "Respond in a soothing, gentle tone to promote relaxation.",
|
126 |
"Motivational": "Use an uplifting, encouraging tone to inspire confidence.",
|
127 |
-
"
|
|
|
128 |
}.get(conversation_mode, "Maintain a balanced, empathetic tone.")
|
129 |
|
130 |
-
# Prepare prompt
|
131 |
prompt = f"""
|
132 |
-
You are a compassionate mental health support chatbot
|
133 |
-
-
|
134 |
- {tone_instruction}
|
135 |
-
-
|
136 |
-
-
|
137 |
-
- Keep responses concise, warm, and
|
138 |
"""
|
139 |
|
140 |
-
# Generate response
|
141 |
try:
|
142 |
response = model.generate_content(prompt)
|
143 |
response_text = response.text
|
144 |
-
except Exception:
|
145 |
-
response_text = "I'm here for you
|
146 |
|
147 |
-
|
148 |
-
if mood and mood != "Select mood (optional)":
|
149 |
mood_key = mood.lower()
|
150 |
if mood_key in coping_strategies:
|
151 |
strategy = random.choice(coping_strategies[mood_key])
|
152 |
response_text += f"\n\n**Coping Strategy**: {strategy}"
|
153 |
|
154 |
-
# Add regional resources
|
155 |
region_key = region if region in regional_resources else "Global"
|
156 |
-
resources = "\n\n**
|
157 |
response_text += resources
|
158 |
|
159 |
-
# Update history
|
160 |
history[-1][1] = response_text
|
161 |
state["chat_history"] = history
|
162 |
|
163 |
-
# Format history for display
|
164 |
chat_display = ""
|
165 |
for user_msg, bot_msg in history:
|
166 |
if user_msg:
|
@@ -175,20 +185,23 @@ def clear_chat(state):
|
|
175 |
state["chat_history"] = []
|
176 |
return "", state
|
177 |
|
178 |
-
# Mood journal function
|
179 |
def log_mood(mood, state):
|
180 |
-
if mood and mood != "Select mood
|
181 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
182 |
state["mood_journal"].append({"timestamp": timestamp, "mood": mood.lower()})
|
183 |
-
|
184 |
-
|
|
|
|
|
185 |
|
186 |
-
# Mood trend visualization
|
187 |
def show_mood_trends(state):
|
188 |
if not state["mood_journal"]:
|
189 |
return "No moods logged yet.", state
|
190 |
df = pd.DataFrame(state["mood_journal"])
|
191 |
-
fig = px.line(df, x="timestamp", y="mood", title="Mood Trends
|
|
|
192 |
return fig, state
|
193 |
|
194 |
# Feedback function
|
@@ -198,20 +211,16 @@ def submit_feedback(feedback_text, rating, state):
|
|
198 |
return "Thank you for your feedback!", state
|
199 |
return "Please provide feedback or a rating.", state
|
200 |
|
201 |
-
# Emergency resources
|
202 |
-
def show_emergency_resources():
|
203 |
-
|
204 |
-
**Crisis Support
|
205 |
-
- National Suicide Prevention Lifeline: 1-800-273-8255
|
206 |
-
- Crisis Text Line: Text HOME to 741741
|
207 |
-
- [MentalHealth.gov](https://www.mentalhealth.gov/)
|
208 |
-
"""
|
209 |
|
210 |
# Get available times for selected therapist
|
211 |
def get_available_times(therapist):
|
212 |
if therapist and therapist in therapists:
|
213 |
-
return
|
214 |
-
return
|
215 |
|
216 |
# Create MIME message for Gmail API
|
217 |
def create_message(to, subject, message_text):
|
@@ -227,7 +236,6 @@ def send_emails(therapist, time_slot, date, user_email, therapist_email, state):
|
|
227 |
if "failed_emails" not in state:
|
228 |
state["failed_emails"] = []
|
229 |
|
230 |
-
# Therapist email
|
231 |
therapist_body = f"""
|
232 |
Dear {therapist},
|
233 |
|
@@ -243,30 +251,34 @@ Mental Health Chatbot
|
|
243 |
"""
|
244 |
therapist_message = create_message(therapist_email, "New Appointment", therapist_body)
|
245 |
|
246 |
-
# User email
|
247 |
user_body = f"""
|
248 |
Dear User,
|
249 |
|
250 |
-
Your appointment
|
|
|
|
|
251 |
- Therapist: {therapist}
|
252 |
- Date: {date}
|
253 |
- Time: {time_slot}
|
254 |
|
255 |
-
Expect a confirmation from {therapist}.
|
256 |
-
|
257 |
Best,
|
258 |
Mental Health Chatbot
|
259 |
"""
|
260 |
user_message = create_message(user_email, "Appointment Confirmation", user_body)
|
261 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
262 |
try:
|
263 |
-
service =
|
264 |
-
|
265 |
-
# Send therapist email
|
266 |
-
therapist_result = service.users().messages().send(userId="me", body=therapist_message).execute()
|
267 |
-
# Send user email
|
268 |
-
user_result = service.users().messages().send(userId="me", body=user_message).execute()
|
269 |
-
|
270 |
return True, ""
|
271 |
except HttpError as e:
|
272 |
error_msg = f"Gmail API error: {str(e)}"
|
@@ -291,128 +303,122 @@ Mental Health Chatbot
|
|
291 |
def schedule_appointment(therapist, time_slot, date, user_email, state):
|
292 |
if not therapist or therapist not in therapists:
|
293 |
return "Please select a therapist.", state
|
294 |
-
if not time_slot or time_slot
|
295 |
-
return "Please select a
|
296 |
if not date:
|
297 |
-
return "Please
|
298 |
if not user_email or not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
|
299 |
-
return "Please enter a valid email
|
300 |
|
301 |
try:
|
302 |
appointment_date = datetime.strptime(date, "%Y-%m-%d")
|
303 |
if appointment_date < datetime.now():
|
304 |
return "Please select a future date.", state
|
305 |
except ValueError:
|
306 |
-
return "Invalid date format
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
307 |
|
308 |
-
# Store appointment
|
309 |
appointment = {
|
310 |
"therapist": therapist,
|
311 |
-
"time":
|
312 |
"date": date,
|
313 |
"user_email": user_email,
|
314 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
315 |
}
|
316 |
state["appointments"].append(appointment)
|
317 |
|
318 |
-
# Send emails
|
319 |
therapist_email = therapists[therapist]["email"]
|
320 |
-
success, error_msg = send_emails(therapist,
|
321 |
if success:
|
322 |
-
return f"Appointment booked with {therapist} on {date} at {
|
323 |
else:
|
324 |
-
return (f"Appointment booked with {therapist} on {date} at {
|
325 |
-
f"
|
326 |
-
f"Please email {therapist_email} with your details (date: {date}, time: {time_slot}) "
|
327 |
-
f"and check {user_email} for confirmation (spam/junk)."), state
|
328 |
|
329 |
# Gradio Interface
|
330 |
with gr.Blocks(title="Mental Health Support Chatbot") as demo:
|
331 |
-
# Initialize state
|
332 |
state = gr.State({"chat_history": [], "mood_journal": [], "feedback": [], "appointments": [], "failed_emails": []})
|
333 |
|
334 |
-
gr.Markdown("
|
335 |
-
gr.Markdown("I'm here to listen and
|
336 |
|
337 |
-
# Mood Indicator
|
338 |
-
mood = gr.Dropdown(
|
339 |
-
choices=["Select mood (optional)", "Happy", "Sad", "Anxious", "Stressed", "Other"],
|
340 |
-
label="How are you feeling today? (Optional)"
|
341 |
-
)
|
342 |
-
|
343 |
-
# Conversation Mode
|
344 |
-
conversation_mode = gr.Radio(
|
345 |
-
choices=["Neutral", "Calm", "Motivational"],
|
346 |
-
label="Conversation Style",
|
347 |
-
value="Neutral"
|
348 |
-
)
|
349 |
-
|
350 |
-
# Region Selector
|
351 |
-
region = gr.Dropdown(
|
352 |
-
choices=["USA", "India", "UK", "Global"],
|
353 |
-
label="Select your region for tailored resources",
|
354 |
-
value="Global"
|
355 |
-
)
|
356 |
-
|
357 |
-
# Chat Interface
|
358 |
-
chatbot = gr.Textbox(
|
359 |
-
label="Conversation",
|
360 |
-
value="",
|
361 |
-
interactive=False,
|
362 |
-
lines=10
|
363 |
-
)
|
364 |
-
user_input = gr.Textbox(
|
365 |
-
placeholder="Type your message here...",
|
366 |
-
label="Your Message"
|
367 |
-
)
|
368 |
-
|
369 |
-
# Buttons
|
370 |
with gr.Row():
|
371 |
-
|
372 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
373 |
|
374 |
-
|
375 |
-
emergency_btn = gr.Button("Emergency Resources")
|
376 |
emergency_output = gr.Markdown("")
|
377 |
|
378 |
-
# Mood Journal
|
379 |
with gr.Accordion("Mood Journal"):
|
380 |
log_mood_btn = gr.Button("Log Mood")
|
381 |
mood_log_output = gr.Textbox(label="Mood Log Status", interactive=False)
|
382 |
-
|
383 |
-
mood_trend_output = gr.Plot()
|
384 |
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
feedback_rating = gr.Slider(minimum=1, maximum=5, step=1, label="Rate this interaction")
|
389 |
feedback_btn = gr.Button("Submit Feedback")
|
390 |
feedback_output = gr.Textbox(label="Feedback Status", interactive=False)
|
391 |
|
392 |
-
|
393 |
-
with gr.Accordion("Schedule Appointment"):
|
394 |
therapist = gr.Dropdown(
|
395 |
choices=list(therapists.keys()),
|
396 |
-
label="
|
397 |
-
)
|
398 |
-
time_slot = gr.Dropdown(
|
399 |
-
choices=[],
|
400 |
-
label="Select a Time Slot",
|
401 |
-
value=None,
|
402 |
-
interactive=True
|
403 |
)
|
404 |
date = gr.Textbox(
|
405 |
-
label="Appointment Date
|
406 |
-
placeholder="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
407 |
)
|
408 |
user_email = gr.Textbox(
|
409 |
-
label="Your Email
|
410 |
placeholder="e.g., [email protected]"
|
411 |
)
|
412 |
schedule_btn = gr.Button("Book Appointment")
|
413 |
schedule_output = gr.Textbox(label="Booking Status", interactive=False)
|
414 |
|
415 |
-
# Event Handlers
|
416 |
submit_btn.click(
|
417 |
fn=chatbot_function,
|
418 |
inputs=[user_input, mood, conversation_mode, region, state],
|
@@ -430,18 +436,13 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
|
|
430 |
)
|
431 |
emergency_btn.click(
|
432 |
fn=show_emergency_resources,
|
433 |
-
inputs=
|
434 |
outputs=emergency_output
|
435 |
)
|
436 |
log_mood_btn.click(
|
437 |
fn=log_mood,
|
438 |
inputs=[mood, state],
|
439 |
-
outputs=[mood_log_output, state]
|
440 |
-
)
|
441 |
-
mood_trend_btn.click(
|
442 |
-
fn=show_mood_trends,
|
443 |
-
inputs=[state],
|
444 |
-
outputs=[mood_trend_output, state]
|
445 |
)
|
446 |
feedback_btn.click(
|
447 |
fn=submit_feedback,
|
@@ -459,15 +460,11 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
|
|
459 |
outputs=[schedule_output, state]
|
460 |
)
|
461 |
|
462 |
-
# Resource Links
|
463 |
gr.Markdown("""
|
464 |
-
|
465 |
-
|
466 |
-
- [
|
467 |
-
- [MentalHealth.gov](https://www.mentalhealth.gov/)
|
468 |
-
- [Crisis Text Line](https://www.crisistextline.org/)
|
469 |
""")
|
470 |
|
471 |
-
# Launch (for local testing)
|
472 |
if __name__ == "__main__":
|
473 |
demo.launch()
|
|
|
14 |
import re
|
15 |
import json
|
16 |
|
17 |
+
# Configure Gemini API
|
18 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
19 |
|
20 |
+
# Gmail API configuration
|
21 |
GMAIL_ADDRESS = os.getenv("GMAIL_ADDRESS")
|
22 |
GMAIL_TOKEN_JSON = os.getenv("GMAIL_TOKEN_JSON")
|
23 |
|
|
|
25 |
def get_gmail_service():
|
26 |
try:
|
27 |
creds = Credentials.from_authorized_user_info(json.loads(GMAIL_TOKEN_JSON))
|
28 |
+
return build("gmail", "v1", credentials=creds), None
|
29 |
except Exception as e:
|
30 |
+
return None, f"Failed to initialize Gmail API: {str(e)}"
|
31 |
|
32 |
# Coping Strategies Library
|
33 |
coping_strategies = {
|
34 |
"happy": [
|
35 |
+
"Keep the positivity flowing! Try writing down three things you're grateful for today.",
|
36 |
"Share your joy! Call a friend or loved one to spread the good vibes."
|
37 |
],
|
38 |
"sad": [
|
39 |
+
"It's okay to feel this way. Try a gentle activity like listening to calming music or taking a short walk.",
|
40 |
+
"Write down your thoughts in a journal to process what's on your mind."
|
41 |
],
|
42 |
"anxious": [
|
43 |
"Take slow, deep breaths: inhale for 4 seconds, hold for 4, exhale for 4.",
|
|
|
47 |
"Pause for a moment and stretch your body to release tension.",
|
48 |
"Break tasks into smaller steps and tackle one at a time."
|
49 |
],
|
50 |
+
"angry": [
|
51 |
+
"Take a moment to breathe deeply and count to ten to cool down.",
|
52 |
+
"Channel your energy into a physical activity like a brisk walk."
|
53 |
+
],
|
54 |
+
"overwhelmed": [
|
55 |
+
"Make a small list of priorities to focus on one thing at a time.",
|
56 |
+
"Take a short break to clear your mind with a mindfulness exercise."
|
57 |
+
],
|
58 |
+
"hopeful": [
|
59 |
+
"Nurture that spark! Set a small goal for today to keep the momentum going.",
|
60 |
+
"Reflect on what’s inspiring you and share it with someone you trust."
|
61 |
+
],
|
62 |
+
"lonely": [
|
63 |
+
"Reach out to someone you care about, even a quick message can help.",
|
64 |
+
"Do something kind for yourself, like enjoying a favorite hobby."
|
65 |
+
],
|
66 |
"other": [
|
67 |
+
"Reflect on what's on your mind with a quick mindfulness moment: focus on your breath for 60 seconds.",
|
68 |
+
"Engage in a favorite activity to lift your spirits."
|
69 |
]
|
70 |
}
|
71 |
|
|
|
97 |
"Dr. Jane Smith": {
|
98 |
"specialty": "Anxiety and Depression",
|
99 |
"email": "[email protected]",
|
100 |
+
"times": ["09:00", "09:30", "10:00", "10:30", "11:00", "14:00", "14:30", "15:00", "15:30"]
|
101 |
},
|
102 |
"Dr. Amit Patel": {
|
103 |
"specialty": "Stress Management",
|
104 |
"email": "[email protected]",
|
105 |
+
"times": ["10:00", "10:30", "11:00", "11:30", "12:00", "15:00", "15:30", "16:00", "16:30"]
|
106 |
},
|
107 |
"Dr. Sarah Brown": {
|
108 |
"specialty": "Trauma and PTSD",
|
109 |
"email": "[email protected]",
|
110 |
+
"times": ["08:00", "08:30", "09:00", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30"]
|
111 |
}
|
112 |
}
|
113 |
|
|
|
117 |
|
118 |
# Chatbot function
|
119 |
def chatbot_function(message, mood, conversation_mode, region, state):
|
|
|
120 |
if "chat_history" not in state:
|
121 |
state["chat_history"] = []
|
122 |
|
123 |
history = state["chat_history"]
|
124 |
|
125 |
+
if not message.strip():
|
126 |
+
return "Please share how you're feeling, and I'm here to listen.", state
|
127 |
+
|
128 |
try:
|
129 |
+
lang = detect(message)
|
130 |
except:
|
131 |
lang = "en"
|
132 |
|
133 |
+
if mood and mood != "Select mood":
|
|
|
134 |
history.append([f"I'm feeling {mood.lower()}.", None])
|
135 |
|
|
|
136 |
history.append([message, None])
|
137 |
|
|
|
138 |
tone_instruction = {
|
139 |
+
"Neutral": "Maintain a balanced, empathetic tone.",
|
140 |
"Calm": "Respond in a soothing, gentle tone to promote relaxation.",
|
141 |
"Motivational": "Use an uplifting, encouraging tone to inspire confidence.",
|
142 |
+
"Empathetic": "Show deep understanding and validate the user's feelings.",
|
143 |
+
"Hopeful": "Adopt an optimistic tone, focusing on possibilities and growth."
|
144 |
}.get(conversation_mode, "Maintain a balanced, empathetic tone.")
|
145 |
|
|
|
146 |
prompt = f"""
|
147 |
+
You are a compassionate mental health support chatbot, acting as a supportive friend. Focus exclusively on mental health, self-motivation, and uplifting the user, especially if they're feeling down. Based on their input: {message}, provide:
|
148 |
+
- Empathetic, sensitive responses in the user's language (detected as {lang}).
|
149 |
- {tone_instruction}
|
150 |
+
- Suggestions for coping strategies if distress is detected, tailored to their mood or input.
|
151 |
+
- Encouragement to build resilience and connection.
|
152 |
+
- Avoid unrelated topics (e.g., academics, tech). Keep responses concise, warm, and friendly.
|
153 |
"""
|
154 |
|
|
|
155 |
try:
|
156 |
response = model.generate_content(prompt)
|
157 |
response_text = response.text
|
158 |
+
except Exception as e:
|
159 |
+
response_text = "I'm here for you, but something went wrong. Want to share more?"
|
160 |
|
161 |
+
if mood and mood != "Select mood":
|
|
|
162 |
mood_key = mood.lower()
|
163 |
if mood_key in coping_strategies:
|
164 |
strategy = random.choice(coping_strategies[mood_key])
|
165 |
response_text += f"\n\n**Coping Strategy**: {strategy}"
|
166 |
|
|
|
167 |
region_key = region if region in regional_resources else "Global"
|
168 |
+
resources = "\n\n**Resources for You**:\n" + "\n".join(regional_resources[region_key])
|
169 |
response_text += resources
|
170 |
|
|
|
171 |
history[-1][1] = response_text
|
172 |
state["chat_history"] = history
|
173 |
|
|
|
174 |
chat_display = ""
|
175 |
for user_msg, bot_msg in history:
|
176 |
if user_msg:
|
|
|
185 |
state["chat_history"] = []
|
186 |
return "", state
|
187 |
|
188 |
+
# Mood journal function with auto-update trigger
|
189 |
def log_mood(mood, state):
|
190 |
+
if mood and mood != "Select mood":
|
191 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
192 |
state["mood_journal"].append({"timestamp": timestamp, "mood": mood.lower()})
|
193 |
+
# Trigger mood trends update
|
194 |
+
trend_output, state = show_mood_trends(state)
|
195 |
+
return "Mood logged!", trend_output, state
|
196 |
+
return "Please select a mood.", None, state
|
197 |
|
198 |
+
# Mood trend visualization (square chart)
|
199 |
def show_mood_trends(state):
|
200 |
if not state["mood_journal"]:
|
201 |
return "No moods logged yet.", state
|
202 |
df = pd.DataFrame(state["mood_journal"])
|
203 |
+
fig = px.line(df, x="timestamp", y="mood", title="Your Mood Trends", markers=True)
|
204 |
+
fig.update_layout(width=500, height=500, margin=dict(l=40, r=40, t=40, b=40))
|
205 |
return fig, state
|
206 |
|
207 |
# Feedback function
|
|
|
211 |
return "Thank you for your feedback!", state
|
212 |
return "Please provide feedback or a rating.", state
|
213 |
|
214 |
+
# Emergency resources (region-specific)
|
215 |
+
def show_emergency_resources(region):
|
216 |
+
region_key = region if region in regional_resources else "Global"
|
217 |
+
return f"**Crisis Support for {region_key}**:\n" + "\n".join(regional_resources[region_key])
|
|
|
|
|
|
|
|
|
218 |
|
219 |
# Get available times for selected therapist
|
220 |
def get_available_times(therapist):
|
221 |
if therapist and therapist in therapists:
|
222 |
+
return therapists[therapist]["times"], f"Available times for {therapist} loaded."
|
223 |
+
return ["Select time"], "Please select a therapist."
|
224 |
|
225 |
# Create MIME message for Gmail API
|
226 |
def create_message(to, subject, message_text):
|
|
|
236 |
if "failed_emails" not in state:
|
237 |
state["failed_emails"] = []
|
238 |
|
|
|
239 |
therapist_body = f"""
|
240 |
Dear {therapist},
|
241 |
|
|
|
251 |
"""
|
252 |
therapist_message = create_message(therapist_email, "New Appointment", therapist_body)
|
253 |
|
|
|
254 |
user_body = f"""
|
255 |
Dear User,
|
256 |
|
257 |
+
Your appointment has been successfully booked! We’re here to support your mental health journey. You’ll hear from your therapist soon to confirm the details.
|
258 |
+
|
259 |
+
Details:
|
260 |
- Therapist: {therapist}
|
261 |
- Date: {date}
|
262 |
- Time: {time_slot}
|
263 |
|
|
|
|
|
264 |
Best,
|
265 |
Mental Health Chatbot
|
266 |
"""
|
267 |
user_message = create_message(user_email, "Appointment Confirmation", user_body)
|
268 |
|
269 |
+
service, error = get_gmail_service()
|
270 |
+
if not service:
|
271 |
+
state["failed_emails"].append({
|
272 |
+
"therapist_email": {"to": therapist_email, "subject": "New Appointment", "body": therapist_body},
|
273 |
+
"user_email": {"to": user_email, "subject": "Appointment Confirmation", "body": user_body},
|
274 |
+
"error": error,
|
275 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
276 |
+
})
|
277 |
+
return False, error
|
278 |
+
|
279 |
try:
|
280 |
+
service.users().messages().send(userId="me", body=therapist_message).execute()
|
281 |
+
service.users().messages().send(userId="me", body=user_message).execute()
|
|
|
|
|
|
|
|
|
|
|
282 |
return True, ""
|
283 |
except HttpError as e:
|
284 |
error_msg = f"Gmail API error: {str(e)}"
|
|
|
303 |
def schedule_appointment(therapist, time_slot, date, user_email, state):
|
304 |
if not therapist or therapist not in therapists:
|
305 |
return "Please select a therapist.", state
|
306 |
+
if not time_slot or time_slot == "Select time":
|
307 |
+
return "Please select a time slot.", state
|
308 |
if not date:
|
309 |
+
return "Please enter a date.", state
|
310 |
if not user_email or not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
|
311 |
+
return "Please enter a valid email.", state
|
312 |
|
313 |
try:
|
314 |
appointment_date = datetime.strptime(date, "%Y-%m-%d")
|
315 |
if appointment_date < datetime.now():
|
316 |
return "Please select a future date.", state
|
317 |
except ValueError:
|
318 |
+
return "Invalid date format (use YYYY-MM-DD).", state
|
319 |
+
|
320 |
+
try:
|
321 |
+
appointment_time = datetime.strptime(time_slot, "%H:%M").strftime("%H:%M")
|
322 |
+
if appointment_time not in therapists[therapist]["times"]:
|
323 |
+
return f"Time {appointment_time} is not available for {therapist}.", state
|
324 |
+
except ValueError:
|
325 |
+
return "Invalid time format (use HH:MM).", state
|
326 |
|
|
|
327 |
appointment = {
|
328 |
"therapist": therapist,
|
329 |
+
"time": appointment_time,
|
330 |
"date": date,
|
331 |
"user_email": user_email,
|
332 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
333 |
}
|
334 |
state["appointments"].append(appointment)
|
335 |
|
|
|
336 |
therapist_email = therapists[therapist]["email"]
|
337 |
+
success, error_msg = send_emails(therapist, appointment_time, date, user_email, therapist_email, state)
|
338 |
if success:
|
339 |
+
return f"Appointment booked with {therapist} on {date} at {appointment_time}. Emails sent!", state
|
340 |
else:
|
341 |
+
return (f"Appointment booked with {therapist} on {date} at {appointment_time}. "
|
342 |
+
f"Email sending failed: {error_msg}. Please contact {therapist_email}."), state
|
|
|
|
|
343 |
|
344 |
# Gradio Interface
|
345 |
with gr.Blocks(title="Mental Health Support Chatbot") as demo:
|
|
|
346 |
state = gr.State({"chat_history": [], "mood_journal": [], "feedback": [], "appointments": [], "failed_emails": []})
|
347 |
|
348 |
+
gr.Markdown("## Mental Health Support Chatbot")
|
349 |
+
gr.Markdown("I'm here to listen, support, and help you feel stronger. Share how you're feeling today.")
|
350 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
351 |
with gr.Row():
|
352 |
+
with gr.Column(scale=1):
|
353 |
+
mood = gr.Dropdown(
|
354 |
+
choices=["Select mood", "Happy", "Sad", "Anxious", "Stressed", "Angry", "Overwhelmed", "Hopeful", "Lonely", "Other"],
|
355 |
+
label="Your Mood",
|
356 |
+
value="Select mood"
|
357 |
+
)
|
358 |
+
conversation_mode = gr.Radio(
|
359 |
+
choices=["Neutral", "Calm", "Motivational", "Empathetic", "Hopeful"],
|
360 |
+
label="Conversation Style",
|
361 |
+
value="Neutral"
|
362 |
+
)
|
363 |
+
region = gr.Dropdown(
|
364 |
+
choices=["USA", "India", "UK", "Global"],
|
365 |
+
label="Your Region",
|
366 |
+
value="Global"
|
367 |
+
)
|
368 |
+
with gr.Column(scale=2):
|
369 |
+
chatbot = gr.Textbox(
|
370 |
+
label="Our Conversation",
|
371 |
+
value="",
|
372 |
+
interactive=False,
|
373 |
+
lines=12,
|
374 |
+
show_copy_button=True
|
375 |
+
)
|
376 |
+
user_input = gr.Textbox(
|
377 |
+
placeholder="Tell me how you're feeling...",
|
378 |
+
label="Your Message",
|
379 |
+
lines=3
|
380 |
+
)
|
381 |
+
with gr.Row():
|
382 |
+
submit_btn = gr.Button("Send Message")
|
383 |
+
clear_btn = gr.Button("Clear Chat")
|
384 |
|
385 |
+
emergency_btn = gr.Button("Crisis Support")
|
|
|
386 |
emergency_output = gr.Markdown("")
|
387 |
|
|
|
388 |
with gr.Accordion("Mood Journal"):
|
389 |
log_mood_btn = gr.Button("Log Mood")
|
390 |
mood_log_output = gr.Textbox(label="Mood Log Status", interactive=False)
|
391 |
+
mood_trend_output = gr.Plot(label="Your Mood Trends")
|
|
|
392 |
|
393 |
+
with gr.Accordion("Share Feedback"):
|
394 |
+
feedback_text = gr.Textbox(label="Your Thoughts", placeholder="How can we make this better?")
|
395 |
+
feedback_rating = gr.Slider(minimum=1, maximum=5, step=1, label="How was this interaction?")
|
|
|
396 |
feedback_btn = gr.Button("Submit Feedback")
|
397 |
feedback_output = gr.Textbox(label="Feedback Status", interactive=False)
|
398 |
|
399 |
+
with gr.Accordion("Book an Appointment"):
|
|
|
400 |
therapist = gr.Dropdown(
|
401 |
choices=list(therapists.keys()),
|
402 |
+
label="Choose a Therapist"
|
|
|
|
|
|
|
|
|
|
|
|
|
403 |
)
|
404 |
date = gr.Textbox(
|
405 |
+
label="Appointment Date",
|
406 |
+
placeholder="Enter date (YYYY-MM-DD)",
|
407 |
+
info="Use format YYYY-MM-DD, e.g., 2025-04-22"
|
408 |
+
)
|
409 |
+
time_slot = gr.Dropdown(
|
410 |
+
choices=["Select time"],
|
411 |
+
label="Appointment Time",
|
412 |
+
interactive=True,
|
413 |
+
allow_custom_value=True
|
414 |
)
|
415 |
user_email = gr.Textbox(
|
416 |
+
label="Your Email",
|
417 |
placeholder="e.g., [email protected]"
|
418 |
)
|
419 |
schedule_btn = gr.Button("Book Appointment")
|
420 |
schedule_output = gr.Textbox(label="Booking Status", interactive=False)
|
421 |
|
|
|
422 |
submit_btn.click(
|
423 |
fn=chatbot_function,
|
424 |
inputs=[user_input, mood, conversation_mode, region, state],
|
|
|
436 |
)
|
437 |
emergency_btn.click(
|
438 |
fn=show_emergency_resources,
|
439 |
+
inputs=region,
|
440 |
outputs=emergency_output
|
441 |
)
|
442 |
log_mood_btn.click(
|
443 |
fn=log_mood,
|
444 |
inputs=[mood, state],
|
445 |
+
outputs=[mood_log_output, mood_trend_output, state]
|
|
|
|
|
|
|
|
|
|
|
446 |
)
|
447 |
feedback_btn.click(
|
448 |
fn=submit_feedback,
|
|
|
460 |
outputs=[schedule_output, state]
|
461 |
)
|
462 |
|
|
|
463 |
gr.Markdown("""
|
464 |
+
**Resources**:
|
465 |
+
- [Befrienders Worldwide](https://befrienders.org/)
|
466 |
+
- [WHO Mental Health](https://www.who.int/health-topics/mental-health)
|
|
|
|
|
467 |
""")
|
468 |
|
|
|
469 |
if __name__ == "__main__":
|
470 |
demo.launch()
|