Ujeshhh commited on
Commit
48a842c
·
verified ·
1 Parent(s): b68577d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -88
app.py CHANGED
@@ -76,22 +76,22 @@ regional_resources = {
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
 
@@ -101,33 +101,27 @@ 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
- # 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,30 +131,25 @@ def chatbot_function(message, mood, conversation_mode, region, state):
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:
@@ -210,8 +199,8 @@ def show_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,7 +216,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,7 +231,6 @@ 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
 
@@ -261,12 +248,8 @@ Mental Health Chatbot
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,7 +274,7 @@ 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 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
@@ -303,107 +286,193 @@ def schedule_appointment(therapist, time_slot, date, user_email, state):
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",
@@ -412,7 +481,6 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
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,7 +519,7 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
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,7 +527,6 @@ 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
  **Helpful Resources:**
@@ -468,6 +535,5 @@ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
468
  - [Crisis Text Line](https://www.crisistextline.org/)
469
  """)
470
 
471
- # Launch (for local testing)
472
  if __name__ == "__main__":
473
  demo.launch()
 
76
  ]
77
  }
78
 
79
+ # Mock Therapist Database (times adjusted for time picker compatibility)
80
  therapists = {
81
  "Dr. Jane Smith": {
82
  "specialty": "Anxiety and Depression",
83
  "email": "[email protected]",
84
+ "times": ["09:00", "09:30", "10:00", "10:30", "11:00", "14:00", "14:30", "15:00", "16:00"]
85
  },
86
  "Dr. Amit Patel": {
87
  "specialty": "Stress Management",
88
  "email": "[email protected]",
89
+ "times": ["10:00", "10:30", "11:00", "11:30", "12:00", "15:00", "15:30", "16:00", "17:00"]
90
  },
91
  "Dr. Sarah Brown": {
92
  "specialty": "Trauma and PTSD",
93
  "email": "[email protected]",
94
+ "times": ["08:00", "08:30", "09:00", "13:00", "13:30", "14:00", "15:30", "16:00", "18:00"]
95
  }
96
  }
97
 
 
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 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}).
 
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:
 
199
  # Get available times for selected therapist
200
  def get_available_times(therapist):
201
  if therapist and therapist in therapists:
202
+ return f"Available times for {therapist} loaded. Please select a time."
203
+ return "Please select a therapist."
204
 
205
  # Create MIME message for Gmail API
206
  def create_message(to, subject, message_text):
 
216
  if "failed_emails" not in state:
217
  state["failed_emails"] = []
218
 
 
219
  therapist_body = f"""
220
  Dear {therapist},
221
 
 
231
  """
232
  therapist_message = create_message(therapist_email, "New Appointment", therapist_body)
233
 
 
234
  user_body = f"""
235
  Dear User,
236
 
 
248
 
249
  try:
250
  service = get_gmail_service()
 
 
251
  therapist_result = service.users().messages().send(userId="me", body=therapist_message).execute()
 
252
  user_result = service.users().messages().send(userId="me", body=user_message).execute()
 
253
  return True, ""
254
  except HttpError as e:
255
  error_msg = f"Gmail API error: {str(e)}"
 
274
  def schedule_appointment(therapist, time_slot, date, user_email, state):
275
  if not therapist or therapist not in therapists:
276
  return "Please select a therapist.", state
277
+ if not time_slot:
278
  return "Please select a valid time slot.", state
279
  if not date:
280
  return "Please select a date.", state
 
286
  if appointment_date < datetime.now():
287
  return "Please select a future date.", state
288
  except ValueError:
289
+ return "Invalid date format.", state
290
+
291
+ try:
292
+ appointment_time = datetime.strptime(time_slot, "%H:%M").strftime("%H:%M")
293
+ if appointment_time not in therapists[therapist]["times"]:
294
+ return f"Time {appointment_time} is not available for {therapist}.", state
295
+ except ValueError:
296
+ return "Invalid time format.", state
297
 
 
298
  appointment = {
299
  "therapist": therapist,
300
+ "time": appointment_time,
301
  "date": date,
302
  "user_email": user_email,
303
  "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
304
  }
305
  state["appointments"].append(appointment)
306
 
 
307
  therapist_email = therapists[therapist]["email"]
308
+ success, error_msg = send_emails(therapist, appointment_time, date, user_email, therapist_email, state)
309
  if success:
310
+ return f"Appointment booked with {therapist} on {date} at {appointment_time}. Emails sent from {GMAIL_ADDRESS} to {therapist_email} and {user_email}!", state
311
  else:
312
+ return (f"Appointment booked with {therapist} on {date} at {appointment_time}. "
313
  f"Emails from {GMAIL_ADDRESS} could not be sent. "
314
+ f"Please email {therapist_email} with your details (date: {date}, time: {appointment_time}) "
315
  f"and check {user_email} for confirmation (spam/junk)."), state
316
 
317
+ # Custom CSS for beautiful UI
318
+ custom_css = """
319
+ /* General Styling */
320
+ body {
321
+ font-family: 'Inter', sans-serif;
322
+ background-color: #f0f4f8;
323
+ }
324
+
325
+ /* Containers */
326
+ .gradio-container {
327
+ max-width: 900px;
328
+ margin: 0 auto;
329
+ padding: 20px;
330
+ background: white;
331
+ border-radius: 16px;
332
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
333
+ }
334
+
335
+ /* Headings */
336
+ h1 {
337
+ color: #2c3e50;
338
+ font-size: 2.5em;
339
+ text-align: center;
340
+ margin-bottom: 10px;
341
+ }
342
+
343
+ h2, h3 {
344
+ color: #34495e;
345
+ }
346
+
347
+ /* Inputs and Buttons */
348
+ input, select, textarea {
349
+ border-radius: 8px !important;
350
+ border: 1px solid #d1d9e0 !important;
351
+ padding: 10px !important;
352
+ transition: border-color 0.2s;
353
+ }
354
+
355
+ input:focus, select:focus, textarea:focus {
356
+ border-color: #3498db !important;
357
+ outline: none;
358
+ }
359
+
360
+ button {
361
+ background: linear-gradient(90deg, #3498db, #2980b9) !important;
362
+ color: white !important;
363
+ border: none !important;
364
+ border-radius: 8px !important;
365
+ padding: 12px 24px !important;
366
+ font-weight: 600 !important;
367
+ transition: transform 0.2s, box-shadow 0.2s !important;
368
+ }
369
+
370
+ button:hover {
371
+ transform: translateY(-2px) !important;
372
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
373
+ }
374
+
375
+ /* Chatbox */
376
+ textarea[readonly] {
377
+ background: #f8fafc !important;
378
+ border-radius: 12px !important;
379
+ padding: 15px !important;
380
+ }
381
+
382
+ /* Appointment Section */
383
+ #appointment-section .gr-box {
384
+ background: #e6f0fa !important;
385
+ border-radius: 12px !important;
386
+ padding: 20px !important;
387
+ }
388
+
389
+ /* Date and Time Pickers */
390
+ input[type="date"], input[type="time"] {
391
+ background: white !important;
392
+ cursor: pointer;
393
+ }
394
+
395
+ /* Responsive Design */
396
+ @media (max-width: 600px) {
397
+ .gradio-container {
398
+ padding: 15px;
399
+ }
400
+ button {
401
+ padding: 10px 20px !important;
402
+ }
403
+ }
404
+ """
405
+
406
  # Gradio Interface
407
+ with gr.Blocks(title="Mental Health Support Chatbot", css=custom_css) as demo:
 
408
  state = gr.State({"chat_history": [], "mood_journal": [], "feedback": [], "appointments": [], "failed_emails": []})
409
 
410
  gr.Markdown("# Mental Health Support Chatbot")
411
+ gr.Markdown("A safe space to share how you're feeling, with tools to support your well-being.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
  with gr.Row():
414
+ with gr.Column(scale=3):
415
+ mood = gr.Dropdown(
416
+ choices=["Select mood (optional)", "Happy", "Sad", "Anxious", "Stressed", "Other"],
417
+ label="How are you feeling today?",
418
+ value="Select mood (optional)"
419
+ )
420
+ conversation_mode = gr.Radio(
421
+ choices=["Neutral", "Calm", "Motivational"],
422
+ label="Conversation Style",
423
+ value="Neutral"
424
+ )
425
+ region = gr.Dropdown(
426
+ choices=["USA", "India", "UK", "Global"],
427
+ label="Your Region",
428
+ value="Global"
429
+ )
430
+ with gr.Column(scale=7):
431
+ chatbot = gr.Textbox(
432
+ label="Conversation",
433
+ value="",
434
+ interactive=False,
435
+ lines=12,
436
+ show_copy_button=True
437
+ )
438
+ user_input = gr.Textbox(
439
+ placeholder="Type your message here...",
440
+ label="Your Message",
441
+ lines=2
442
+ )
443
+ with gr.Row():
444
+ submit_btn = gr.Button("Send")
445
+ clear_btn = gr.Button("Clear Chat")
446
 
 
447
  emergency_btn = gr.Button("Emergency Resources")
448
  emergency_output = gr.Markdown("")
449
 
 
450
  with gr.Accordion("Mood Journal"):
451
  log_mood_btn = gr.Button("Log Mood")
452
  mood_log_output = gr.Textbox(label="Mood Log Status", interactive=False)
453
  mood_trend_btn = gr.Button("Show Mood Trends")
454
  mood_trend_output = gr.Plot()
455
 
 
456
  with gr.Accordion("Provide Feedback"):
457
+ feedback_text = gr.Textbox(label="Your Feedback", placeholder="How can we improve?")
458
  feedback_rating = gr.Slider(minimum=1, maximum=5, step=1, label="Rate this interaction")
459
  feedback_btn = gr.Button("Submit Feedback")
460
  feedback_output = gr.Textbox(label="Feedback Status", interactive=False)
461
 
462
+ with gr.Accordion("Schedule Appointment", elem_id="appointment-section"):
 
463
  therapist = gr.Dropdown(
464
  choices=list(therapists.keys()),
465
  label="Select a Therapist"
466
  )
 
 
 
 
 
 
467
  date = gr.Textbox(
468
+ label="Appointment Date",
469
+ type="date",
470
+ placeholder="Select a date"
471
+ )
472
+ time_slot = gr.Textbox(
473
+ label="Appointment Time",
474
+ type="time",
475
+ placeholder="Select a time"
476
  )
477
  user_email = gr.Textbox(
478
  label="Your Email Address",
 
481
  schedule_btn = gr.Button("Book Appointment")
482
  schedule_output = gr.Textbox(label="Booking Status", interactive=False)
483
 
 
484
  submit_btn.click(
485
  fn=chatbot_function,
486
  inputs=[user_input, mood, conversation_mode, region, state],
 
519
  therapist.change(
520
  fn=get_available_times,
521
  inputs=therapist,
522
+ outputs=schedule_output
523
  )
524
  schedule_btn.click(
525
  fn=schedule_appointment,
 
527
  outputs=[schedule_output, state]
528
  )
529
 
 
530
  gr.Markdown("""
531
  ---
532
  **Helpful Resources:**
 
535
  - [Crisis Text Line](https://www.crisistextline.org/)
536
  """)
537
 
 
538
  if __name__ == "__main__":
539
  demo.launch()