Ujeshhh commited on
Commit
536ea02
·
verified ·
1 Parent(s): b0c1f58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -46
app.py CHANGED
@@ -1,7 +1,7 @@
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
@@ -9,6 +9,7 @@ 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"))
@@ -201,82 +202,94 @@ def get_available_times(therapist):
201
  return gr.update(choices=therapists[therapist]["times"], value=None), f"Available times for {therapist} loaded."
202
  return gr.update(choices=[], value=None), "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 or time_slot not in therapists[therapist]["times"]:
209
- return "Please select a valid 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:
 
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
 
9
  import smtplib
10
  from email.message import EmailMessage
11
  import re
12
+ import time
13
 
14
  # Configure Gemini API (expects GEMINI_API_KEY in Hugging Face secrets)
15
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
 
202
  return gr.update(choices=therapists[therapist]["times"], value=None), f"Available times for {therapist} loaded."
203
  return gr.update(choices=[], value=None), "Please select a therapist."
204
 
205
+ # Send emails with retries
206
+ def send_emails(therapist, time_slot, date, user_email, therapist_email):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  msg_therapist = EmailMessage()
208
  msg_therapist.set_content(f"""
209
  Dear {therapist},
210
 
211
+ You have a new appointment:
212
  - Date: {date}
213
  - Time: {time_slot}
214
  - Client Email: {user_email}
215
 
216
  Please confirm with the client.
217
 
218
+ Best,
219
  Mental Health Chatbot
220
  """)
221
+ msg_therapist["Subject"] = "New Appointment"
222
  msg_therapist["From"] = GMAIL_ADDRESS
223
  msg_therapist["To"] = therapist_email
224
 
 
225
  msg_user = EmailMessage()
226
  msg_user.set_content(f"""
227
  Dear User,
228
 
229
+ Your appointment is booked:
230
  - Therapist: {therapist}
231
  - Date: {date}
232
  - Time: {time_slot}
233
 
234
+ Expect a confirmation from {therapist}.
235
 
236
+ Best,
237
  Mental Health Chatbot
238
  """)
239
  msg_user["Subject"] = "Appointment Confirmation"
240
  msg_user["From"] = GMAIL_ADDRESS
241
  msg_user["To"] = user_email
242
 
243
+ max_retries = 3
244
+ for attempt in range(max_retries):
245
+ try:
246
+ with smtplib.SMTP_SSL("smtp.gmail.com", 465, timeout=10) as server:
247
+ server.login(GMAIL_ADDRESS, GMAIL_APP_PASSWORD)
248
+ server.send_message(msg_therapist)
249
+ server.send_message(msg_user)
250
+ return True, ""
251
+ except (smtplib.SMTPException, ConnectionRefusedError, OSError) as e:
252
+ if attempt == max_retries - 1:
253
+ return False, str(e)
254
+ time.sleep(2) # Wait before retry
255
+ return False, "Max retries exceeded"
256
+
257
+ # Schedule appointment
258
+ def schedule_appointment(therapist, time_slot, date, user_email, state):
259
+ if not therapist or therapist not in therapists:
260
+ return "Please select a therapist.", state
261
+ if not time_slot or time_slot not in therapists[therapist]["times"]:
262
+ return "Please select a valid time slot.", state
263
+ if not date:
264
+ return "Please select a date.", state
265
+ if not user_email or not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
266
+ return "Please enter a valid email address.", state
267
+
268
  try:
269
+ appointment_date = datetime.strptime(date, "%Y-%m-%d")
270
+ if appointment_date < datetime.now():
271
+ return "Please select a future date.", state
272
+ except ValueError:
273
+ return "Invalid date format. Use YYYY-MM-DD.", state
274
+
275
+ # Store appointment
276
+ appointment = {
277
+ "therapist": therapist,
278
+ "time": time_slot,
279
+ "date": date,
280
+ "user_email": user_email,
281
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
282
+ }
283
+ state["appointments"].append(appointment)
284
+
285
+ # Send emails
286
+ therapist_email = therapists[therapist]["email"]
287
+ success, error_msg = send_emails(therapist, time_slot, date, user_email, therapist_email)
288
+ if success:
289
+ return f"Appointment booked with {therapist} on {date} at {time_slot}. Emails sent!", state
290
+ else:
291
+ return (f"Appointment booked with {therapist} on {date} at {time_slot}, but emails failed: {error_msg}. "
292
+ f"Please contact {therapist_email} manually with your appointment details."), state
293
 
294
  # Gradio Interface
295
  with gr.Blocks(title="Mental Health Support Chatbot") as demo: