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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import google.generativeai as genai
|
3 |
+
import os
|
4 |
+
from datetime import datetime
|
5 |
+
import plotly.express as px
|
6 |
+
import pandas as pd
|
7 |
+
from langdetect import detect
|
8 |
+
import random
|
9 |
+
from google.oauth2.credentials import Credentials
|
10 |
+
from googleapiclient.discovery import build
|
11 |
+
from googleapiclient.errors import HttpError
|
12 |
+
import base64
|
13 |
+
from email.mime.text import MIMEText
|
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 |
+
|
24 |
+
# Initialize Gmail API client
|
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.",
|
44 |
+
"Try a grounding exercise: name 5 things you see, 4 you can touch, 3 you hear, 2 you smell, 1 you taste."
|
45 |
+
],
|
46 |
+
"stressed": [
|
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’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 |
+
}
|
55 |
+
|
56 |
+
# Regional Resources
|
57 |
+
regional_resources = {
|
58 |
+
"USA": [
|
59 |
+
"National Suicide Prevention Lifeline: 1-800-273-8255",
|
60 |
+
"Crisis Text Line: Text HOME to 741741",
|
61 |
+
"[MentalHealth.gov](https://www.mentalhealth.gov/)"
|
62 |
+
],
|
63 |
+
"India": [
|
64 |
+
"Vandrevala Foundation: 1860-2662-345",
|
65 |
+
"AASRA Suicide Prevention: +91-9820466726",
|
66 |
+
"[iCall Helpline](https://icallhelpline.org/)"
|
67 |
+
],
|
68 |
+
"UK": [
|
69 |
+
"Samaritans: 116 123",
|
70 |
+
"Shout Crisis Text Line: Text SHOUT to 85258",
|
71 |
+
"[Mind UK](https://www.mind.org.uk/)"
|
72 |
+
],
|
73 |
+
"Global": [
|
74 |
+
"Befrienders Worldwide: [Find a helpline](https://befrienders.org/)",
|
75 |
+
"[WHO Mental Health Resources](https://www.who.int/health-topics/mental-health)"
|
76 |
+
]
|
77 |
+
}
|
78 |
+
|
79 |
+
# Mock Therapist Database
|
80 |
+
therapists = {
|
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 |
+
|
98 |
+
# Initialize Gemini model
|
99 |
+
model = genai.GenerativeModel("gemini-1.5-flash",
|
100 |
+
generation_config={"temperature": 0.7, "max_output_tokens": 200})
|
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 |
+
try:
|
110 |
+
lang = detect(message) if message.strip() else "en"
|
111 |
+
except:
|
112 |
+
lang = "en"
|
113 |
+
|
114 |
+
if mood and mood != "Select mood (optional)":
|
115 |
+
history.append([f"I'm feeling {mood.lower()}.", None])
|
116 |
+
|
117 |
+
history.append([message, None])
|
118 |
+
|
119 |
+
tone_instruction = {
|
120 |
+
"Calm": "Respond in a soothing, gentle tone to promote relaxation.",
|
121 |
+
"Motivational": "Use an uplifting, encouraging tone to inspire confidence.",
|
122 |
+
"Neutral": "Maintain a balanced, empathetic tone."
|
123 |
+
}.get(conversation_mode, "Maintain a balanced, empathetic tone.")
|
124 |
+
|
125 |
+
prompt = f"""
|
126 |
+
You are Healora, a compassionate mental health support chatbot. Engage in a supportive conversation with the user based on their input: {message}.
|
127 |
+
- Provide empathetic, sensitive responses in the user's language (detected as {lang}).
|
128 |
+
- {tone_instruction}
|
129 |
+
- If signs of distress are detected, suggest coping strategies relevant to their mood or input.
|
130 |
+
- Recommend professional resources tailored to the user's region ({region}).
|
131 |
+
- Keep responses concise, warm, and encouraging.
|
132 |
+
"""
|
133 |
+
|
134 |
+
try:
|
135 |
+
response = model.generate_content(prompt)
|
136 |
+
response_text = response.text
|
137 |
+
except Exception:
|
138 |
+
response_text = "I'm here for you. Could you share a bit more so I can support you better?"
|
139 |
+
|
140 |
+
if mood and mood != "Select mood (optional)":
|
141 |
+
mood_key = mood.lower()
|
142 |
+
if mood_key in coping_strategies:
|
143 |
+
strategy = random.choice(coping_strategies[mood_key])
|
144 |
+
response_text += f"\n\n**Coping Strategy**: {strategy}"
|
145 |
+
|
146 |
+
region_key = region if region in regional_resources else "Global"
|
147 |
+
resources = "\n\n**Recommended Resources**:\n" + "\n".join(regional_resources[region_key])
|
148 |
+
response_text += resources
|
149 |
+
|
150 |
+
history[-1][1] = response_text
|
151 |
+
state["chat_history"] = history
|
152 |
+
|
153 |
+
chat_display = ""
|
154 |
+
for user_msg, bot_msg in history:
|
155 |
+
if user_msg:
|
156 |
+
chat_display += f"**You**: {user_msg}\n\n"
|
157 |
+
if bot_msg:
|
158 |
+
chat_display += f"**Healora**: {bot_msg}\n\n"
|
159 |
+
|
160 |
+
return chat_display, state
|
161 |
+
|
162 |
+
# Clear chat history
|
163 |
+
def clear_chat(state):
|
164 |
+
state["chat_history"] = []
|
165 |
+
return "", state
|
166 |
+
|
167 |
+
# Mood journal function
|
168 |
+
def log_mood(mood, state):
|
169 |
+
if mood and mood != "Select mood (optional)":
|
170 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
171 |
+
state["mood_journal"].append({"timestamp": timestamp, "mood": mood.lower()})
|
172 |
+
return "Mood logged successfully!", state
|
173 |
+
return "Please select a mood to log.", state
|
174 |
+
|
175 |
+
# Mood trend visualization
|
176 |
+
def show_mood_trends(state):
|
177 |
+
if not state["mood_journal"]:
|
178 |
+
return "No moods logged yet.", state
|
179 |
+
df = pd.DataFrame(state["mood_journal"])
|
180 |
+
fig = px.line(df, x="timestamp", y="mood", title="Mood Trends Over Time", markers=True)
|
181 |
+
return fig, state
|
182 |
+
|
183 |
+
# Emergency resources
|
184 |
+
def show_emergency_resources(region):
|
185 |
+
region_key = region if region in regional_resources else "Global"
|
186 |
+
return f"**Crisis Support ({region_key})**:\n" + "\n".join(regional_resources[region_key])
|
187 |
+
|
188 |
+
# Get available times and therapist details
|
189 |
+
def get_therapist_details(therapist):
|
190 |
+
if therapist and therapist in therapists:
|
191 |
+
details = f"""
|
192 |
+
**Therapist Details**:
|
193 |
+
- Name: {therapist}
|
194 |
+
- Specialty: {therapists[therapist]["specialty"]}
|
195 |
+
- Email: {therapists[therapist]["email"]}
|
196 |
+
"""
|
197 |
+
return gr.update(choices=therapists[therapist]["times"], value=None), details
|
198 |
+
return gr.update(choices=[], value=None), "Please select a therapist."
|
199 |
+
|
200 |
+
# Create MIME message for Gmail API
|
201 |
+
def create_message(to, subject, message_text):
|
202 |
+
message = MIMEText(message_text)
|
203 |
+
message["to"] = to
|
204 |
+
message["from"] = GMAIL_ADDRESS
|
205 |
+
message["subject"] = subject
|
206 |
+
raw = base64.urlsafe_b64encode(message.as_bytes()).decode()
|
207 |
+
return {"raw": raw}
|
208 |
+
|
209 |
+
# Send emails using Gmail API
|
210 |
+
def send_emails(therapist, time_slot, date, user_email, therapist_email, appointment_note, state):
|
211 |
+
if "failed_emails" not in state:
|
212 |
+
state["failed_emails"] = []
|
213 |
+
|
214 |
+
therapist_body = f"""
|
215 |
+
Dear {therapist},
|
216 |
+
|
217 |
+
You have a new appointment:
|
218 |
+
- Date: {date}
|
219 |
+
- Time: {time_slot}
|
220 |
+
- Client Email: {user_email}
|
221 |
+
- Note: {appointment_note}
|
222 |
+
- Therapist Details:
|
223 |
+
- Specialty: {therapists[therapist]["specialty"]}
|
224 |
+
- Email: {therapist_email}
|
225 |
+
|
226 |
+
Please confirm with the client.
|
227 |
+
|
228 |
+
Best,
|
229 |
+
Healora
|
230 |
+
"""
|
231 |
+
therapist_message = create_message(therapist_email, "New Appointment", therapist_body)
|
232 |
+
|
233 |
+
user_body = f"""
|
234 |
+
Dear User,
|
235 |
+
|
236 |
+
Your appointment is booked:
|
237 |
+
- Therapist: {therapist}
|
238 |
+
- Specialty: {therapists[therapist]["specialty"]}
|
239 |
+
- Email: {therapist_email}
|
240 |
+
- Date: {date}
|
241 |
+
- Time: {time_slot}
|
242 |
+
- Note: {appointment_note}
|
243 |
+
|
244 |
+
Expect a confirmation from {therapist}.
|
245 |
+
|
246 |
+
Best,
|
247 |
+
Healora
|
248 |
+
"""
|
249 |
+
user_message = create_message(user_email, "Appointment Confirmation", user_body)
|
250 |
+
|
251 |
+
try:
|
252 |
+
service = get_gmail_service()
|
253 |
+
therapist_result = service.users().messages().send(userId="me", body=therapist_message).execute()
|
254 |
+
user_result = service.users().messages().send(userId="me", body=user_message).execute()
|
255 |
+
return True, ""
|
256 |
+
except HttpError as e:
|
257 |
+
error_msg = f"Gmail API error: {str(e)}"
|
258 |
+
state["failed_emails"].append({
|
259 |
+
"therapist_email": {"to": therapist_email, "subject": "New Appointment", "body": therapist_body},
|
260 |
+
"user_email": {"to": user_email, "subject": "Appointment Confirmation", "body": user_body},
|
261 |
+
"error": error_msg,
|
262 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
263 |
+
})
|
264 |
+
return False, error_msg
|
265 |
+
except Exception as e:
|
266 |
+
error_msg = f"Unexpected error: {str(e)}"
|
267 |
+
state["failed_emails"].append({
|
268 |
+
"therapist_email": {"to": therapist_email, "subject": "New Appointment", "body": therapist_body},
|
269 |
+
"user_email": {"to": user_email, "subject": "Appointment Confirmation", "body": user_body},
|
270 |
+
"error": error_msg,
|
271 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
272 |
+
})
|
273 |
+
return False, error_msg
|
274 |
+
|
275 |
+
# Schedule appointment
|
276 |
+
def schedule_appointment(therapist, time_slot, date, user_email, appointment_note, state):
|
277 |
+
if not therapist or therapist not in therapists:
|
278 |
+
return "Please select a therapist.", state
|
279 |
+
if not time_slot or time_slot not in therapists[therapist]["times"]:
|
280 |
+
return "Please select a valid time slot.", state
|
281 |
+
if not date:
|
282 |
+
return "Please select a date.", state
|
283 |
+
if not user_email or not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
|
284 |
+
return "Please enter a valid email address.", state
|
285 |
+
|
286 |
+
try:
|
287 |
+
appointment_date = datetime.strptime(date, "%Y-%m-%d")
|
288 |
+
if appointment_date < datetime.now():
|
289 |
+
return "Please select a future date.", state
|
290 |
+
except ValueError:
|
291 |
+
return "Invalid date format. Use YYYY-MM-DD.", state
|
292 |
+
|
293 |
+
appointment = {
|
294 |
+
"therapist": therapist,
|
295 |
+
"time": time_slot,
|
296 |
+
"date": date,
|
297 |
+
"user_email": user_email,
|
298 |
+
"appointment_note": appointment_note,
|
299 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
300 |
+
}
|
301 |
+
state["appointments"].append(appointment)
|
302 |
+
|
303 |
+
therapist_email = therapists[therapist]["email"]
|
304 |
+
success, error_msg = send_emails(therapist, time_slot, date, user_email, therapist_email, appointment_note, state)
|
305 |
+
if success:
|
306 |
+
return f"Appointment booked with {therapist} on {date} at {time_slot}. Emails sent from {GMAIL_ADDRESS} to {therapist_email} and {user_email}!", state
|
307 |
+
else:
|
308 |
+
return (f"Appointment booked with {therapist} on {date} at {time_slot}. "
|
309 |
+
f"Emails from {GMAIL_ADDRESS} could not be sent. "
|
310 |
+
f"Please email {therapist_email} with your details (date: {date}, time: {time_slot}, note: {appointment_note}) "
|
311 |
+
f"and check {user_email} for confirmation (spam/junk)."), state
|
312 |
+
|
313 |
+
# Emergency meeting
|
314 |
+
def request_emergency_meeting(therapist, user_name, gender, age, user_email, state):
|
315 |
+
if not therapist or therapist not in therapists:
|
316 |
+
return "Please select a therapist.", "", state
|
317 |
+
if not user_name:
|
318 |
+
return "Please enter your name.", "", state
|
319 |
+
if not gender:
|
320 |
+
return "Please select your gender.", "", state
|
321 |
+
if not age:
|
322 |
+
return "Please enter your age.", "", state
|
323 |
+
if not user_email or not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
|
324 |
+
return "Please enter a valid email address.", "", state
|
325 |
+
|
326 |
+
meeting_link = "https://meet.google.com/rek-ocrw-sjc"
|
327 |
+
confirmation_message = f"""
|
328 |
+
**Emergency Meeting Requested**
|
329 |
+
- Therapist: {therapist}
|
330 |
+
- Meeting Link: {meeting_link}
|
331 |
+
|
332 |
+
Would you like to start the meeting now?
|
333 |
+
"""
|
334 |
+
state["emergency_meeting"] = {
|
335 |
+
"therapist": therapist,
|
336 |
+
"user_name": user_name,
|
337 |
+
"gender": gender,
|
338 |
+
"age": age,
|
339 |
+
"user_email": user_email,
|
340 |
+
"meeting_link": meeting_link
|
341 |
+
}
|
342 |
+
return confirmation_message, gr.update(visible=True), state
|
343 |
+
|
344 |
+
# Confirm emergency meeting
|
345 |
+
def confirm_emergency_meeting(confirm, state):
|
346 |
+
if "emergency_meeting" not in state:
|
347 |
+
return "No emergency meeting requested.", state
|
348 |
+
|
349 |
+
if confirm == "Yes":
|
350 |
+
meeting_info = state["emergency_meeting"]
|
351 |
+
therapist = meeting_info["therapist"]
|
352 |
+
user_name = meeting_info["user_name"]
|
353 |
+
gender = meeting_info["gender"]
|
354 |
+
age = meeting_info["age"]
|
355 |
+
user_email = meeting_info["user_email"]
|
356 |
+
meeting_link = meeting_info["meeting_link"]
|
357 |
+
therapist_email = "[email protected]"
|
358 |
+
|
359 |
+
alert_body = f"""
|
360 |
+
Dear {therapist},
|
361 |
+
|
362 |
+
An emergency meeting has been requested:
|
363 |
+
- Client Name: {user_name}
|
364 |
+
- Gender: {gender}
|
365 |
+
- Age: {age}
|
366 |
+
- Client Email: {user_email}
|
367 |
+
- Google Meet Link: {meeting_link}
|
368 |
+
|
369 |
+
Please join the meeting as soon as possible.
|
370 |
+
|
371 |
+
Best,
|
372 |
+
Healora
|
373 |
+
"""
|
374 |
+
alert_message = create_message(therapist_email, "Emergency Meeting Request", alert_body)
|
375 |
+
|
376 |
+
try:
|
377 |
+
service = get_gmail_service()
|
378 |
+
service.users().messages().send(userId="me", body=alert_message).execute()
|
379 |
+
return f"Emergency meeting alert sent to {therapist_email}. Join the meeting at {meeting_link}.", state
|
380 |
+
except Exception as e:
|
381 |
+
state["failed_emails"].append({
|
382 |
+
"therapist_email": {"to": therapist_email, "subject": "Emergency Meeting Request", "body": alert_body},
|
383 |
+
"error": str(e),
|
384 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
385 |
+
})
|
386 |
+
return (f"Failed to send emergency meeting alert to {therapist_email}. "
|
387 |
+
f"Please contact {therapist_email} directly with the meeting link: {meeting_link}."), state
|
388 |
+
else:
|
389 |
+
return "Emergency meeting cancelled.", state
|
390 |
+
|
391 |
+
# Gradio Interface
|
392 |
+
with gr.Blocks(title="Healora: Mental Health Support Chatbot") as demo:
|
393 |
+
state = gr.State({"chat_history": [], "mood_journal": [], "appointments": [], "failed_emails": []})
|
394 |
+
|
395 |
+
gr.Markdown("# Healora: Your Safe Space for Healing and Hope")
|
396 |
+
gr.Markdown("I'm here to listen and support you. Feel free to share how you're feeling.")
|
397 |
+
|
398 |
+
mood = gr.Dropdown(
|
399 |
+
choices=["Select mood (optional)", "Happy", "Sad", "Anxious", "Stressed", "Other"],
|
400 |
+
label="How are you feeling today? (Optional)"
|
401 |
+
)
|
402 |
+
|
403 |
+
conversation_mode = gr.Radio(
|
404 |
+
choices=["Neutral", "Calm", "Motivational"],
|
405 |
+
label="Conversation Style",
|
406 |
+
value="Neutral"
|
407 |
+
)
|
408 |
+
|
409 |
+
region = gr.Dropdown(
|
410 |
+
choices=["USA", "India", "UK", "Global"],
|
411 |
+
label="Select your region for tailored resources",
|
412 |
+
value="Global"
|
413 |
+
)
|
414 |
+
|
415 |
+
chatbot = gr.Textbox(
|
416 |
+
label="Conversation",
|
417 |
+
value="",
|
418 |
+
interactive=False,
|
419 |
+
lines=10
|
420 |
+
)
|
421 |
+
user_input = gr.Textbox(
|
422 |
+
placeholder="Type your message here...",
|
423 |
+
label="Your Message"
|
424 |
+
)
|
425 |
+
|
426 |
+
with gr.Row():
|
427 |
+
submit_btn = gr.Button("Send")
|
428 |
+
clear_btn = gr.Button("Clear Chat")
|
429 |
+
|
430 |
+
emergency_btn = gr.Button("Emergency Resources")
|
431 |
+
emergency_output = gr.Markdown("")
|
432 |
+
|
433 |
+
with gr.Accordion("Mood Journal"):
|
434 |
+
log_mood_btn = gr.Button("Log Mood")
|
435 |
+
mood_log_output = gr.Textbox(label="Mood Log Status", interactive=False)
|
436 |
+
mood_trend_btn = gr.Button("Show Mood Trends")
|
437 |
+
mood_trend_output = gr.Plot()
|
438 |
+
|
439 |
+
with gr.Accordion("Schedule Appointment"):
|
440 |
+
therapist = gr.Dropdown(
|
441 |
+
choices=list(therapists.keys()),
|
442 |
+
label="Select a Therapist"
|
443 |
+
)
|
444 |
+
therapist_details = gr.Markdown("Select a therapist to view details.")
|
445 |
+
time_slot = gr.Dropdown(
|
446 |
+
choices=[],
|
447 |
+
label="Select a Time Slot",
|
448 |
+
value=None,
|
449 |
+
interactive=True
|
450 |
+
)
|
451 |
+
date = gr.Textbox(
|
452 |
+
label="Appointment Date (YYYY-MM-DD)",
|
453 |
+
placeholder="e.g., 2025-04-20"
|
454 |
+
)
|
455 |
+
user_email = gr.Textbox(
|
456 |
+
label="Your Email Address",
|
457 |
+
placeholder="e.g., [email protected]"
|
458 |
+
)
|
459 |
+
appointment_note = gr.Textbox(
|
460 |
+
label="Additional Note (Optional)",
|
461 |
+
placeholder="Any specific details or concerns for the therapist"
|
462 |
+
)
|
463 |
+
schedule_btn = gr.Button("Book Appointment")
|
464 |
+
schedule_output = gr.Textbox(label="Booking Status", interactive=False)
|
465 |
+
|
466 |
+
with gr.Accordion("Request Emergency Meeting"):
|
467 |
+
emergency_therapist = gr.Dropdown(
|
468 |
+
choices=list(therapists.keys()),
|
469 |
+
label="Select a Therapist"
|
470 |
+
)
|
471 |
+
user_name = gr.Textbox(
|
472 |
+
label="Your Name",
|
473 |
+
placeholder="e.g., John Doe"
|
474 |
+
)
|
475 |
+
gender = gr.Dropdown(
|
476 |
+
choices=["Male", "Female", "Other"],
|
477 |
+
label="Gender"
|
478 |
+
)
|
479 |
+
age = gr.Textbox(
|
480 |
+
label="Age",
|
481 |
+
placeholder="e.g., 30"
|
482 |
+
)
|
483 |
+
emergency_email = gr.Textbox(
|
484 |
+
label="Your Email Address",
|
485 |
+
placeholder="e.g., [email protected]"
|
486 |
+
)
|
487 |
+
emergency_btn = gr.Button("Request Emergency Meeting")
|
488 |
+
emergency_output = gr.Markdown("")
|
489 |
+
confirm_buttons = gr.Radio(
|
490 |
+
choices=["Yes", "No"],
|
491 |
+
label="Confirm Emergency Meeting",
|
492 |
+
visible=False
|
493 |
+
)
|
494 |
+
|
495 |
+
submit_btn.click(
|
496 |
+
fn=chatbot_function,
|
497 |
+
inputs=[user_input, mood, conversation_mode, region, state],
|
498 |
+
outputs=[chatbot, state]
|
499 |
+
)
|
500 |
+
user_input.submit(
|
501 |
+
fn=chatbot_function,
|
502 |
+
inputs=[user_input, mood, conversation_mode, region, state],
|
503 |
+
outputs=[chatbot, state]
|
504 |
+
)
|
505 |
+
clear_btn.click(
|
506 |
+
fn=clear_chat,
|
507 |
+
inputs=[state],
|
508 |
+
outputs=[chatbot, state]
|
509 |
+
)
|
510 |
+
emergency_btn.click(
|
511 |
+
fn=show_emergency_resources,
|
512 |
+
inputs=region,
|
513 |
+
outputs=emergency_output
|
514 |
+
)
|
515 |
+
log_mood_btn.click(
|
516 |
+
fn=log_mood,
|
517 |
+
inputs=[mood, state],
|
518 |
+
outputs=[mood_log_output, state]
|
519 |
+
)
|
520 |
+
mood_trend_btn.click(
|
521 |
+
fn=show_mood_trends,
|
522 |
+
inputs=[state],
|
523 |
+
outputs=[mood_trend_output, state]
|
524 |
+
)
|
525 |
+
therapist.change(
|
526 |
+
fn=get_therapist_details,
|
527 |
+
inputs=therapist,
|
528 |
+
outputs=[time_slot, therapist_details]
|
529 |
+
)
|
530 |
+
schedule_btn.click(
|
531 |
+
fn=schedule_appointment,
|
532 |
+
inputs=[therapist, time_slot, date, user_email, appointment_note, state],
|
533 |
+
outputs=[schedule_output, state]
|
534 |
+
)
|
535 |
+
emergency_btn.click(
|
536 |
+
fn=request_emergency_meeting,
|
537 |
+
inputs=[emergency_therapist, user_name, gender, age, emergency_email, state],
|
538 |
+
outputs=[emergency_output, confirm_buttons, state]
|
539 |
+
)
|
540 |
+
confirm_buttons.change(
|
541 |
+
fn=confirm_emergency_meeting,
|
542 |
+
inputs=[confirm_buttons, state],
|
543 |
+
outputs=[emergency_output, state]
|
544 |
+
)
|
545 |
+
|
546 |
+
gr.Markdown("""
|
547 |
+
---
|
548 |
+
**Helpful Resources:**
|
549 |
+
- [National Suicide Prevention Lifeline](https://suicidepreventionlifeline.org/)
|
550 |
+
- [MentalHealth.gov](https://www.mentalhealth.gov/)
|
551 |
+
- [Crisis Text Line](https://www.crisistextline.org/)
|
552 |
+
""")
|
553 |
+
|
554 |
+
if __name__ == "__main__":
|
555 |
+
demo.launch()
|