Ujeshhh commited on
Commit
6d68909
·
verified ·
1 Parent(s): ed7de7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +165 -31
app.py CHANGED
@@ -1,15 +1,22 @@
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
 
10
  # Configure Gemini API (expects GEMINI_API_KEY in Hugging Face secrets)
11
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
12
 
 
 
 
 
13
  # Coping Strategies Library
14
  coping_strategies = {
15
  "happy": [
@@ -57,14 +64,36 @@ regional_resources = {
57
  ]
58
  }
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  # Initialize Gemini model
61
  model = genai.GenerativeModel("gemini-1.5-flash",
62
  generation_config={"temperature": 0.7, "max_output_tokens": 200})
63
 
64
  # Chatbot function
65
- def chatbot_function(message, history, mood, conversation_mode, region, state):
66
- if history is None:
67
- history = []
 
 
 
68
 
69
  # Multilingual Support: Detect input language
70
  try:
@@ -117,6 +146,7 @@ def chatbot_function(message, history, mood, conversation_mode, region, state):
117
 
118
  # Update history
119
  history[-1][1] = response_text
 
120
 
121
  # Format history for display
122
  chat_display = ""
@@ -126,7 +156,12 @@ def chatbot_function(message, history, mood, conversation_mode, region, state):
126
  if bot_msg:
127
  chat_display += f"**Bot**: {bot_msg}\n\n"
128
 
129
- return chat_display, history, state
 
 
 
 
 
130
 
131
  # Mood journal function
132
  def log_mood(mood, state):
@@ -160,26 +195,93 @@ def show_emergency_resources():
160
  - [MentalHealth.gov](https://www.mentalhealth.gov/)
161
  """
162
 
163
- # Gradio Interface with Dark/Light Mode
164
- css = """
165
- body { transition: background-color 0.3s, color 0.3s; }
166
- .light-mode { background-color: #ffffff; color: #000000; }
167
- .dark-mode { background-color: #1a1a1a; color: #ffffff; }
168
- button, input, select, textarea { border-radius: 8px; margin: 5px; }
169
- """
170
- with gr.Blocks(css=css, title="Mental Health Support Chatbot") as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  # Initialize state
172
- state = gr.State({"mood_journal": [], "feedback": []})
173
- history = gr.State()
174
-
175
- # Theme Toggle
176
- theme_state = gr.State(value="light")
177
- def toggle_theme(theme):
178
- new_theme = "dark" if theme == "light" else "light"
179
- return new_theme, f".{new_theme}-mode"
180
- theme_btn = gr.Button("Toggle Dark/Light Mode")
181
- theme_output = gr.HTML(value=".light-mode")
182
- theme_btn.click(toggle_theme, inputs=theme_state, outputs=[theme_state, theme_output])
183
 
184
  gr.Markdown("# Mental Health Support Chatbot")
185
  gr.Markdown("I'm here to listen and support you. Feel free to share how you're feeling.")
@@ -239,21 +341,43 @@ with gr.Blocks(css=css, title="Mental Health Support Chatbot") as demo:
239
  feedback_btn = gr.Button("Submit Feedback")
240
  feedback_output = gr.Textbox(label="Feedback Status", interactive=False)
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  # Event Handlers
243
  submit_btn.click(
244
  fn=chatbot_function,
245
- inputs=[user_input, history, mood, conversation_mode, region, state],
246
- outputs=[chatbot, history, state]
247
  )
248
  user_input.submit(
249
  fn=chatbot_function,
250
- inputs=[user_input, history, mood, conversation_mode, region, state],
251
- outputs=[chatbot, history, state]
252
  )
253
  clear_btn.click(
254
- fn=lambda: ("", [], state),
255
- inputs=None,
256
- outputs=[chatbot, history, state]
257
  )
258
  emergency_btn.click(
259
  fn=show_emergency_resources,
@@ -275,6 +399,16 @@ with gr.Blocks(css=css, title="Mental Health Support Chatbot") as demo:
275
  inputs=[feedback_text, feedback_rating, state],
276
  outputs=[feedback_output, state]
277
  )
 
 
 
 
 
 
 
 
 
 
278
 
279
  # Resource Links
280
  gr.Markdown("""
 
1
  import gradio as gr
2
  import google.generativeai as genai
3
  import os
4
+ from datetime import datetime, timedelta
5
  import plotly.express as px
6
  import pandas as pd
7
  from langdetect import detect
8
  import random
9
+ import smtplib
10
+ from email.message import EmailMessage
11
+ import re
12
 
13
  # Configure Gemini API (expects GEMINI_API_KEY in Hugging Face secrets)
14
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
15
 
16
+ # Gmail SMTP configuration (expects GMAIL_ADDRESS and GMAIL_APP_PASSWORD in secrets)
17
+ GMAIL_ADDRESS = os.getenv("GMAIL_ADDRESS")
18
+ GMAIL_APP_PASSWORD = os.getenv("GMAIL_APP_PASSWORD")
19
+
20
  # Coping Strategies Library
21
  coping_strategies = {
22
  "happy": [
 
64
  ]
65
  }
66
 
67
+ # Mock Therapist Database
68
+ therapists = {
69
+ "Dr. Jane Smith": {
70
+ "specialty": "Anxiety and Depression",
71
+ "email": "[email protected]",
72
+ "times": ["09:00", "11:00", "14:00", "16:00"]
73
+ },
74
+ "Dr. Amit Patel": {
75
+ "specialty": "Stress Management",
76
+ "email": "[email protected]",
77
+ "times": ["10:00", "12:00", "15:00", "17:00"]
78
+ },
79
+ "Dr. Sarah Brown": {
80
+ "specialty": "Trauma and PTSD",
81
+ "email": "[email protected]",
82
+ "times": ["08:00", "13:00", "15:30", "18:00"]
83
+ }
84
+ }
85
+
86
  # Initialize Gemini model
87
  model = genai.GenerativeModel("gemini-1.5-flash",
88
  generation_config={"temperature": 0.7, "max_output_tokens": 200})
89
 
90
  # Chatbot function
91
+ def chatbot_function(message, mood, conversation_mode, region, state):
92
+ # Initialize chat history if not present
93
+ if "chat_history" not in state:
94
+ state["chat_history"] = []
95
+
96
+ history = state["chat_history"]
97
 
98
  # Multilingual Support: Detect input language
99
  try:
 
146
 
147
  # Update history
148
  history[-1][1] = response_text
149
+ state["chat_history"] = history
150
 
151
  # Format history for display
152
  chat_display = ""
 
156
  if bot_msg:
157
  chat_display += f"**Bot**: {bot_msg}\n\n"
158
 
159
+ return chat_display, state
160
+
161
+ # Clear chat history
162
+ def clear_chat(state):
163
+ state["chat_history"] = []
164
+ return "", state
165
 
166
  # Mood journal function
167
  def log_mood(mood, state):
 
195
  - [MentalHealth.gov](https://www.mentalhealth.gov/)
196
  """
197
 
198
+ # Get available times for selected therapist
199
+ def get_available_times(therapist):
200
+ if therapist and therapist in therapists:
201
+ return therapists[therapist]["times"], f"Available times for {therapist} loaded."
202
+ return [], "Please select a therapist."
203
+
204
+ # Schedule appointment
205
+ def schedule_appointment(therapist, time_slot, date, user_email, state):
206
+ if not therapist or therapist not in therapists:
207
+ return "Please select a therapist.", state
208
+ if not time_slot:
209
+ return "Please select a time slot.", state
210
+ if not date:
211
+ return "Please select a date.", state
212
+ if not user_email or not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
213
+ return "Please enter a valid email address.", state
214
+
215
+ try:
216
+ appointment_date = datetime.strptime(date, "%Y-%m-%d")
217
+ if appointment_date < datetime.now():
218
+ return "Please select a future date.", state
219
+ except ValueError:
220
+ return "Invalid date format. Use YYYY-MM-DD.", state
221
+
222
+ # Store appointment
223
+ appointment = {
224
+ "therapist": therapist,
225
+ "time": time_slot,
226
+ "date": date,
227
+ "user_email": user_email,
228
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
229
+ }
230
+ state["appointments"].append(appointment)
231
+
232
+ # Send email to therapist
233
+ therapist_email = therapists[therapist]["email"]
234
+ msg_therapist = EmailMessage()
235
+ msg_therapist.set_content(f"""
236
+ Dear {therapist},
237
+
238
+ You have a new appointment scheduled:
239
+ - Date: {date}
240
+ - Time: {time_slot}
241
+ - Client Email: {user_email}
242
+
243
+ Please confirm with the client.
244
+
245
+ Best regards,
246
+ Mental Health Chatbot
247
+ """)
248
+ msg_therapist["Subject"] = "New Appointment Scheduled"
249
+ msg_therapist["From"] = GMAIL_ADDRESS
250
+ msg_therapist["To"] = therapist_email
251
+
252
+ # Send email to user
253
+ msg_user = EmailMessage()
254
+ msg_user.set_content(f"""
255
+ Dear User,
256
+
257
+ Your appointment has been booked:
258
+ - Therapist: {therapist}
259
+ - Date: {date}
260
+ - Time: {time_slot}
261
+
262
+ You will receive a confirmation from {therapist} soon.
263
+
264
+ Best regards,
265
+ Mental Health Chatbot
266
+ """)
267
+ msg_user["Subject"] = "Appointment Confirmation"
268
+ msg_user["From"] = GMAIL_ADDRESS
269
+ msg_user["To"] = user_email
270
+
271
+ # Send emails
272
+ try:
273
+ with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
274
+ server.login(GMAIL_ADDRESS, GMAIL_APP_PASSWORD)
275
+ server.send_message(msg_therapist)
276
+ server.send_message(msg_user)
277
+ return f"Appointment booked with {therapist} on {date} at {time_slot}. Confirmation emails sent!", state
278
+ except Exception as e:
279
+ return f"Failed to send emails: {str(e)}. Appointment stored but emails not sent.", state
280
+
281
+ # Gradio Interface
282
+ with gr.Blocks(title="Mental Health Support Chatbot") as demo:
283
  # Initialize state
284
+ state = gr.State({"chat_history": [], "mood_journal": [], "feedback": [], "appointments": []})
 
 
 
 
 
 
 
 
 
 
285
 
286
  gr.Markdown("# Mental Health Support Chatbot")
287
  gr.Markdown("I'm here to listen and support you. Feel free to share how you're feeling.")
 
341
  feedback_btn = gr.Button("Submit Feedback")
342
  feedback_output = gr.Textbox(label="Feedback Status", interactive=False)
343
 
344
+ # Appointment Scheduling
345
+ with gr.Accordion("Schedule Appointment"):
346
+ therapist = gr.Dropdown(
347
+ choices=list(therapists.keys()),
348
+ label="Select a Therapist"
349
+ )
350
+ time_slot = gr.Dropdown(
351
+ choices=[],
352
+ label="Select a Time Slot",
353
+ interactive=True
354
+ )
355
+ date = gr.Textbox(
356
+ label="Appointment Date (YYYY-MM-DD)",
357
+ placeholder="e.g., 2025-04-20"
358
+ )
359
+ user_email = gr.Textbox(
360
+ label="Your Email Address",
361
+ placeholder="e.g., [email protected]"
362
+ )
363
+ schedule_btn = gr.Button("Book Appointment")
364
+ schedule_output = gr.Textbox(label="Booking Status", interactive=False)
365
+
366
  # Event Handlers
367
  submit_btn.click(
368
  fn=chatbot_function,
369
+ inputs=[user_input, mood, conversation_mode, region, state],
370
+ outputs=[chatbot, state]
371
  )
372
  user_input.submit(
373
  fn=chatbot_function,
374
+ inputs=[user_input, mood, conversation_mode, region, state],
375
+ outputs=[chatbot, state]
376
  )
377
  clear_btn.click(
378
+ fn=clear_chat,
379
+ inputs=[state],
380
+ outputs=[chatbot, state]
381
  )
382
  emergency_btn.click(
383
  fn=show_emergency_resources,
 
399
  inputs=[feedback_text, feedback_rating, state],
400
  outputs=[feedback_output, state]
401
  )
402
+ therapist.change(
403
+ fn=get_available_times,
404
+ inputs=therapist,
405
+ outputs=[time_slot, schedule_output]
406
+ )
407
+ schedule_btn.click(
408
+ fn=schedule_appointment,
409
+ inputs=[therapist, time_slot, date, user_email, state],
410
+ outputs=[schedule_output, state]
411
+ )
412
 
413
  # Resource Links
414
  gr.Markdown("""