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.",
|
@@ -48,7 +48,7 @@ coping_strategies = {
|
|
48 |
"Break tasks into smaller steps and tackle one at a time."
|
49 |
],
|
50 |
"other": [
|
51 |
-
"Reflect on what
|
52 |
"Engage in a favorite hobby to lift your spirits."
|
53 |
]
|
54 |
}
|
@@ -81,17 +81,17 @@ therapists = {
|
|
81 |
"Dr. Jane Smith": {
|
82 |
"specialty": "Anxiety and Depression",
|
83 |
"email": "[email protected]",
|
84 |
-
"times": ["09:00", "
|
85 |
},
|
86 |
"Dr. Amit Patel": {
|
87 |
"specialty": "Stress Management",
|
88 |
"email": "[email protected]",
|
89 |
-
"times": ["10:00", "
|
90 |
},
|
91 |
"Dr. Sarah Brown": {
|
92 |
"specialty": "Trauma and PTSD",
|
93 |
"email": "[email protected]",
|
94 |
-
"times": ["08:00", "
|
95 |
}
|
96 |
}
|
97 |
|
@@ -101,30 +101,33 @@ model = genai.GenerativeModel("gemini-1.5-flash",
|
|
101 |
|
102 |
# Chatbot function
|
103 |
def chatbot_function(message, mood, conversation_mode, region, state):
|
|
|
104 |
if "chat_history" not in state:
|
105 |
state["chat_history"] = []
|
106 |
|
107 |
history = state["chat_history"]
|
108 |
|
109 |
-
|
110 |
-
return "Please enter a message.", state
|
111 |
-
|
112 |
try:
|
113 |
-
lang = detect(message)
|
114 |
except:
|
115 |
lang = "en"
|
116 |
|
117 |
-
|
|
|
118 |
history.append([f"I'm feeling {mood.lower()}.", None])
|
119 |
|
|
|
120 |
history.append([message, None])
|
121 |
|
|
|
122 |
tone_instruction = {
|
123 |
"Calm": "Respond in a soothing, gentle tone to promote relaxation.",
|
124 |
"Motivational": "Use an uplifting, encouraging tone to inspire confidence.",
|
125 |
"Neutral": "Maintain a balanced, empathetic tone."
|
126 |
}.get(conversation_mode, "Maintain a balanced, empathetic tone.")
|
127 |
|
|
|
128 |
prompt = f"""
|
129 |
You are a compassionate mental health support chatbot. Engage in a supportive conversation with the user based on their input: {message}.
|
130 |
- Provide empathetic, sensitive responses in the user's language (detected as {lang}).
|
@@ -134,25 +137,30 @@ def chatbot_function(message, mood, conversation_mode, region, state):
|
|
134 |
- Keep responses concise, warm, and encouraging.
|
135 |
"""
|
136 |
|
|
|
137 |
try:
|
138 |
response = model.generate_content(prompt)
|
139 |
response_text = response.text
|
140 |
-
except Exception
|
141 |
-
response_text = "I'm here for you
|
142 |
|
143 |
-
|
|
|
144 |
mood_key = mood.lower()
|
145 |
if mood_key in coping_strategies:
|
146 |
strategy = random.choice(coping_strategies[mood_key])
|
147 |
response_text += f"\n\n**Coping Strategy**: {strategy}"
|
148 |
|
|
|
149 |
region_key = region if region in regional_resources else "Global"
|
150 |
-
resources = "\n\n**Resources**:\n" + "\n".join(regional_resources[region_key])
|
151 |
response_text += resources
|
152 |
|
|
|
153 |
history[-1][1] = response_text
|
154 |
state["chat_history"] = history
|
155 |
|
|
|
156 |
chat_display = ""
|
157 |
for user_msg, bot_msg in history:
|
158 |
if user_msg:
|
@@ -169,25 +177,25 @@ def clear_chat(state):
|
|
169 |
|
170 |
# Mood journal function
|
171 |
def log_mood(mood, state):
|
172 |
-
if mood and mood != "Select mood":
|
173 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
174 |
state["mood_journal"].append({"timestamp": timestamp, "mood": mood.lower()})
|
175 |
-
return "Mood logged!", state
|
176 |
-
return "Please select a mood.", state
|
177 |
|
178 |
# Mood trend visualization
|
179 |
def show_mood_trends(state):
|
180 |
if not state["mood_journal"]:
|
181 |
return "No moods logged yet.", state
|
182 |
df = pd.DataFrame(state["mood_journal"])
|
183 |
-
fig = px.line(df, x="timestamp", y="mood", title="Mood Trends", markers=True)
|
184 |
return fig, state
|
185 |
|
186 |
# Feedback function
|
187 |
def submit_feedback(feedback_text, rating, state):
|
188 |
if feedback_text or rating:
|
189 |
state["feedback"].append({"text": feedback_text, "rating": rating, "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
|
190 |
-
return "
|
191 |
return "Please provide feedback or a rating.", state
|
192 |
|
193 |
# Emergency resources
|
@@ -202,9 +210,8 @@ def show_emergency_resources():
|
|
202 |
# Get available times for selected therapist
|
203 |
def get_available_times(therapist):
|
204 |
if therapist and therapist in therapists:
|
205 |
-
|
206 |
-
|
207 |
-
return [], "Please select a therapist."
|
208 |
|
209 |
# Create MIME message for Gmail API
|
210 |
def create_message(to, subject, message_text):
|
@@ -220,6 +227,7 @@ def send_emails(therapist, time_slot, date, user_email, therapist_email, state):
|
|
220 |
if "failed_emails" not in state:
|
221 |
state["failed_emails"] = []
|
222 |
|
|
|
223 |
therapist_body = f"""
|
224 |
Dear {therapist},
|
225 |
|
@@ -235,6 +243,7 @@ Mental Health Chatbot
|
|
235 |
"""
|
236 |
therapist_message = create_message(therapist_email, "New Appointment", therapist_body)
|
237 |
|
|
|
238 |
user_body = f"""
|
239 |
Dear User,
|
240 |
|
@@ -250,19 +259,14 @@ Mental Health Chatbot
|
|
250 |
"""
|
251 |
user_message = create_message(user_email, "Appointment Confirmation", user_body)
|
252 |
|
253 |
-
service, error = get_gmail_service()
|
254 |
-
if not service:
|
255 |
-
state["failed_emails"].append({
|
256 |
-
"therapist_email": {"to": therapist_email, "subject": "New Appointment", "body": therapist_body},
|
257 |
-
"user_email": {"to": user_email, "subject": "Appointment Confirmation", "body": user_body},
|
258 |
-
"error": error,
|
259 |
-
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
260 |
-
})
|
261 |
-
return False, error
|
262 |
-
|
263 |
try:
|
264 |
-
service
|
265 |
-
|
|
|
|
|
|
|
|
|
|
|
266 |
return True, ""
|
267 |
except HttpError as e:
|
268 |
error_msg = f"Gmail API error: {str(e)}"
|
@@ -287,160 +291,128 @@ Mental Health Chatbot
|
|
287 |
def schedule_appointment(therapist, time_slot, date, user_email, state):
|
288 |
if not therapist or therapist not in therapists:
|
289 |
return "Please select a therapist.", state
|
290 |
-
if not time_slot:
|
291 |
-
return "Please select a time.", state
|
292 |
if not date:
|
293 |
return "Please select a date.", state
|
294 |
if not user_email or not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
|
295 |
-
return "Please enter a valid email.", state
|
296 |
|
297 |
try:
|
298 |
appointment_date = datetime.strptime(date, "%Y-%m-%d")
|
299 |
if appointment_date < datetime.now():
|
300 |
return "Please select a future date.", state
|
301 |
except ValueError:
|
302 |
-
return "Invalid date format
|
303 |
-
|
304 |
-
try:
|
305 |
-
appointment_time = datetime.strptime(time_slot, "%H:%M").strftime("%H:%M")
|
306 |
-
if appointment_time not in therapists[therapist]["times"]:
|
307 |
-
return f"Time {appointment_time} is not available for {therapist}. Please choose from available times.", state
|
308 |
-
except ValueError:
|
309 |
-
return "Invalid time format (use HH:MM).", state
|
310 |
|
|
|
311 |
appointment = {
|
312 |
"therapist": therapist,
|
313 |
-
"time":
|
314 |
"date": date,
|
315 |
"user_email": user_email,
|
316 |
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
317 |
}
|
318 |
state["appointments"].append(appointment)
|
319 |
|
|
|
320 |
therapist_email = therapists[therapist]["email"]
|
321 |
-
success, error_msg = send_emails(therapist,
|
322 |
if success:
|
323 |
-
return f"Appointment booked with {therapist} on {date} at {
|
324 |
else:
|
325 |
-
return (f"Appointment booked with {therapist} on {date} at {
|
326 |
-
f"
|
327 |
-
|
328 |
-
|
329 |
-
custom_css = """
|
330 |
-
#date-picker input[type="date"], #time-picker input[type="time"] {
|
331 |
-
width: 100%;
|
332 |
-
padding: 10px;
|
333 |
-
border: 1px solid #d1d5db;
|
334 |
-
border-radius: 6px;
|
335 |
-
font-size: 16px;
|
336 |
-
box-sizing: border-box;
|
337 |
-
}
|
338 |
-
#date-picker input[type="date"]:focus, #time-picker input[type="time"]:focus {
|
339 |
-
border-color: #3b82f6;
|
340 |
-
outline: none;
|
341 |
-
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
|
342 |
-
}
|
343 |
-
#date-picker input[type="date"]::-webkit-calendar-picker-indicator,
|
344 |
-
#time-picker input[type="time"]::-webkit-calendar-picker-indicator {
|
345 |
-
cursor: pointer;
|
346 |
-
}
|
347 |
-
"""
|
348 |
-
|
349 |
-
# JavaScript for date and time pickers
|
350 |
-
custom_js = """
|
351 |
-
document.addEventListener('DOMContentLoaded', function() {
|
352 |
-
const dateInput = document.querySelector('#date-picker input');
|
353 |
-
const timeInput = document.querySelector('#time-picker input');
|
354 |
-
if (dateInput) {
|
355 |
-
dateInput.type = 'date';
|
356 |
-
dateInput.placeholder = 'YYYY-MM-DD';
|
357 |
-
}
|
358 |
-
if (timeInput) {
|
359 |
-
timeInput.type = 'time';
|
360 |
-
timeInput.placeholder = 'HH:MM';
|
361 |
-
}
|
362 |
-
});
|
363 |
-
"""
|
364 |
|
365 |
# Gradio Interface
|
366 |
-
with gr.Blocks(title="Mental Health Support Chatbot"
|
|
|
367 |
state = gr.State({"chat_history": [], "mood_journal": [], "feedback": [], "appointments": [], "failed_emails": []})
|
368 |
|
369 |
-
gr.Markdown("
|
370 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
371 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
372 |
with gr.Row():
|
373 |
-
|
374 |
-
|
375 |
-
choices=["Select mood", "Happy", "Sad", "Anxious", "Stressed", "Other"],
|
376 |
-
label="Mood",
|
377 |
-
value="Select mood"
|
378 |
-
)
|
379 |
-
conversation_mode = gr.Radio(
|
380 |
-
choices=["Neutral", "Calm", "Motivational"],
|
381 |
-
label="Conversation Style",
|
382 |
-
value="Neutral"
|
383 |
-
)
|
384 |
-
region = gr.Dropdown(
|
385 |
-
choices=["USA", "India", "UK", "Global"],
|
386 |
-
label="Region",
|
387 |
-
value="Global"
|
388 |
-
)
|
389 |
-
with gr.Column(scale=2):
|
390 |
-
chatbot = gr.Textbox(
|
391 |
-
label="Conversation",
|
392 |
-
value="",
|
393 |
-
interactive=False,
|
394 |
-
lines=10,
|
395 |
-
show_copy_button=True
|
396 |
-
)
|
397 |
-
user_input = gr.Textbox(
|
398 |
-
placeholder="Type your message here...",
|
399 |
-
label="Your Message",
|
400 |
-
lines=2
|
401 |
-
)
|
402 |
-
with gr.Row():
|
403 |
-
submit_btn = gr.Button("Send Message")
|
404 |
-
clear_btn = gr.Button("Clear Chat")
|
405 |
|
406 |
-
|
|
|
407 |
emergency_output = gr.Markdown("")
|
408 |
|
|
|
409 |
with gr.Accordion("Mood Journal"):
|
410 |
log_mood_btn = gr.Button("Log Mood")
|
411 |
mood_log_output = gr.Textbox(label="Mood Log Status", interactive=False)
|
412 |
-
mood_trend_btn = gr.Button("
|
413 |
mood_trend_output = gr.Plot()
|
414 |
|
|
|
415 |
with gr.Accordion("Provide Feedback"):
|
416 |
-
feedback_text = gr.Textbox(label="Your Feedback", placeholder="How can we improve?")
|
417 |
-
feedback_rating = gr.Slider(minimum=1, maximum=5, step=1, label="
|
418 |
feedback_btn = gr.Button("Submit Feedback")
|
419 |
feedback_output = gr.Textbox(label="Feedback Status", interactive=False)
|
420 |
|
|
|
421 |
with gr.Accordion("Schedule Appointment"):
|
422 |
therapist = gr.Dropdown(
|
423 |
choices=list(therapists.keys()),
|
424 |
-
label="Select Therapist"
|
425 |
)
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
|
|
430 |
)
|
431 |
-
|
432 |
-
label="Appointment
|
433 |
-
placeholder="
|
434 |
-
elem_id="time-picker"
|
435 |
)
|
436 |
-
time_suggestions = gr.Markdown("Select a therapist to see available times.")
|
437 |
user_email = gr.Textbox(
|
438 |
-
label="Your Email",
|
439 |
placeholder="e.g., [email protected]"
|
440 |
)
|
441 |
schedule_btn = gr.Button("Book Appointment")
|
442 |
schedule_output = gr.Textbox(label="Booking Status", interactive=False)
|
443 |
|
|
|
444 |
submit_btn.click(
|
445 |
fn=chatbot_function,
|
446 |
inputs=[user_input, mood, conversation_mode, region, state],
|
@@ -479,7 +451,7 @@ with gr.Blocks(title="Mental Health Support Chatbot", css=custom_css, js=custom_
|
|
479 |
therapist.change(
|
480 |
fn=get_available_times,
|
481 |
inputs=therapist,
|
482 |
-
outputs=[time_slot,
|
483 |
)
|
484 |
schedule_btn.click(
|
485 |
fn=schedule_appointment,
|
@@ -487,12 +459,15 @@ with gr.Blocks(title="Mental Health Support Chatbot", css=custom_css, js=custom_
|
|
487 |
outputs=[schedule_output, state]
|
488 |
)
|
489 |
|
|
|
490 |
gr.Markdown("""
|
491 |
-
|
492 |
-
|
|
|
493 |
- [MentalHealth.gov](https://www.mentalhealth.gov/)
|
494 |
- [Crisis Text Line](https://www.crisistextline.org/)
|
495 |
""")
|
496 |
|
|
|
497 |
if __name__ == "__main__":
|
498 |
demo.launch()
|
|
|
14 |
import re
|
15 |
import json
|
16 |
|
17 |
+
# Configure Gemini API (expects GEMINI_API_KEY in Hugging Face secrets)
|
18 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
19 |
|
20 |
+
# Gmail API configuration (expects GMAIL_ADDRESS, GMAIL_TOKEN_JSON in secrets)
|
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)
|
29 |
except Exception as e:
|
30 |
+
raise Exception(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.",
|
|
|
48 |
"Break tasks into smaller steps and tackle one at a time."
|
49 |
],
|
50 |
"other": [
|
51 |
+
"Reflect on what’s on your mind with a quick mindfulness moment: focus on your breath for 60 seconds.",
|
52 |
"Engage in a favorite hobby to lift your spirits."
|
53 |
]
|
54 |
}
|
|
|
81 |
"Dr. Jane Smith": {
|
82 |
"specialty": "Anxiety and Depression",
|
83 |
"email": "[email protected]",
|
84 |
+
"times": ["09:00", "11:00", "14:00", "16:00"]
|
85 |
},
|
86 |
"Dr. Amit Patel": {
|
87 |
"specialty": "Stress Management",
|
88 |
"email": "[email protected]",
|
89 |
+
"times": ["10:00", "12:00", "15:00", "17:00"]
|
90 |
},
|
91 |
"Dr. Sarah Brown": {
|
92 |
"specialty": "Trauma and PTSD",
|
93 |
"email": "[email protected]",
|
94 |
+
"times": ["08:00", "13:00", "15:30", "18:00"]
|
95 |
}
|
96 |
}
|
97 |
|
|
|
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 |
+
# Multilingual Support: Detect input language
|
|
|
|
|
111 |
try:
|
112 |
+
lang = detect(message) if message.strip() else "en"
|
113 |
except:
|
114 |
lang = "en"
|
115 |
|
116 |
+
# Append mood to history if provided
|
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 |
"Neutral": "Maintain a balanced, empathetic tone."
|
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. Engage in a supportive conversation with the user based on their input: {message}.
|
133 |
- Provide empathetic, sensitive responses in the user's language (detected as {lang}).
|
|
|
137 |
- Keep responses concise, warm, and encouraging.
|
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. Could you share a bit more so I can support you better?"
|
146 |
|
147 |
+
# Add coping strategy if mood is provided
|
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**Recommended Resources**:\n" + "\n".join(regional_resources[region_key])
|
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:
|
|
|
177 |
|
178 |
# Mood journal function
|
179 |
def log_mood(mood, state):
|
180 |
+
if mood and mood != "Select mood (optional)":
|
181 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
182 |
state["mood_journal"].append({"timestamp": timestamp, "mood": mood.lower()})
|
183 |
+
return "Mood logged successfully!", state
|
184 |
+
return "Please select a mood to log.", state
|
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 Over Time", markers=True)
|
192 |
return fig, state
|
193 |
|
194 |
# Feedback function
|
195 |
def submit_feedback(feedback_text, rating, state):
|
196 |
if feedback_text or rating:
|
197 |
state["feedback"].append({"text": feedback_text, "rating": rating, "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
|
198 |
+
return "Thank you for your feedback!", state
|
199 |
return "Please provide feedback or a rating.", state
|
200 |
|
201 |
# Emergency resources
|
|
|
210 |
# Get available times for selected therapist
|
211 |
def get_available_times(therapist):
|
212 |
if therapist and therapist in therapists:
|
213 |
+
return gr.update(choices=therapists[therapist]["times"], value=None), f"Available times for {therapist} loaded."
|
214 |
+
return gr.update(choices=[], value=None), "Please select a therapist."
|
|
|
215 |
|
216 |
# Create MIME message for Gmail API
|
217 |
def create_message(to, subject, message_text):
|
|
|
227 |
if "failed_emails" not in state:
|
228 |
state["failed_emails"] = []
|
229 |
|
230 |
+
# Therapist email
|
231 |
therapist_body = f"""
|
232 |
Dear {therapist},
|
233 |
|
|
|
243 |
"""
|
244 |
therapist_message = create_message(therapist_email, "New Appointment", therapist_body)
|
245 |
|
246 |
+
# User email
|
247 |
user_body = f"""
|
248 |
Dear User,
|
249 |
|
|
|
259 |
"""
|
260 |
user_message = create_message(user_email, "Appointment Confirmation", user_body)
|
261 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
262 |
try:
|
263 |
+
service = get_gmail_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 |
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 not in therapists[therapist]["times"]:
|
295 |
+
return "Please select a valid time slot.", state
|
296 |
if not date:
|
297 |
return "Please select a date.", state
|
298 |
if not user_email or not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
|
299 |
+
return "Please enter a valid email address.", state
|
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. Use YYYY-MM-DD.", state
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
307 |
|
308 |
+
# Store appointment
|
309 |
appointment = {
|
310 |
"therapist": therapist,
|
311 |
+
"time": time_slot,
|
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, time_slot, date, user_email, therapist_email, state)
|
321 |
if success:
|
322 |
+
return f"Appointment booked with {therapist} on {date} at {time_slot}. Emails sent from {GMAIL_ADDRESS} to {therapist_email} and {user_email}!", state
|
323 |
else:
|
324 |
+
return (f"Appointment booked with {therapist} on {date} at {time_slot}. "
|
325 |
+
f"Emails from {GMAIL_ADDRESS} could not be sent. "
|
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("# Mental Health Support Chatbot")
|
335 |
+
gr.Markdown("I'm here to listen and support you. Feel free to share how you're feeling.")
|
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 |
+
submit_btn = gr.Button("Send")
|
372 |
+
clear_btn = gr.Button("Clear Chat")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
373 |
|
374 |
+
# Emergency Resources
|
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 |
+
mood_trend_btn = gr.Button("Show Mood Trends")
|
383 |
mood_trend_output = gr.Plot()
|
384 |
|
385 |
+
# Feedback
|
386 |
with gr.Accordion("Provide Feedback"):
|
387 |
+
feedback_text = gr.Textbox(label="Your Feedback (Optional)", placeholder="How can we improve?")
|
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 |
+
# Appointment Scheduling
|
393 |
with gr.Accordion("Schedule Appointment"):
|
394 |
therapist = gr.Dropdown(
|
395 |
choices=list(therapists.keys()),
|
396 |
+
label="Select a Therapist"
|
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 (YYYY-MM-DD)",
|
406 |
+
placeholder="e.g., 2025-04-20"
|
|
|
407 |
)
|
|
|
408 |
user_email = gr.Textbox(
|
409 |
+
label="Your Email Address",
|
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],
|
|
|
451 |
therapist.change(
|
452 |
fn=get_available_times,
|
453 |
inputs=therapist,
|
454 |
+
outputs=[time_slot, schedule_output]
|
455 |
)
|
456 |
schedule_btn.click(
|
457 |
fn=schedule_appointment,
|
|
|
459 |
outputs=[schedule_output, state]
|
460 |
)
|
461 |
|
462 |
+
# Resource Links
|
463 |
gr.Markdown("""
|
464 |
+
---
|
465 |
+
**Helpful Resources:**
|
466 |
+
- [National Suicide Prevention Lifeline](https://suicidepreventionlifeline.org/)
|
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()
|