chrisaldikaraharja commited on
Commit
5645b28
·
verified ·
1 Parent(s): ff10db9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -80
app.py CHANGED
@@ -1,134 +1,128 @@
1
  import os
2
  import pandas as pd
3
  import requests
4
- import json
5
  import textwrap
6
  from datetime import datetime, timedelta
7
  import streamlit as st
8
 
9
- # Set your API key
 
 
10
  OPENROUTER_API_KEY = "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"
 
 
11
 
12
- # Load your patient data
 
 
13
  dataset_url = "https://huggingface.co/spaces/chrisaldikaraharja/AutomatedFollowUpSystem/resolve/main/PatientData%20-%20Sheet1.csv"
14
- data = pd.read_csv(dataset_url) # Loading the patient data from the URL
15
- st.write("Patient data loaded successfully.")
16
- st.write(data.head()) # Displaying the first few rows of the dataset
17
 
18
- # Mailjet API credentials
19
- MAILJET_API_KEY = 'f746efdd7af5c96a033ddb90a78a5704'
20
- MAILJET_SECRET_KEY = '5ee6955f792909206669fb10e9910b57'
21
-
22
- # Function to send email using Mailjet
23
  def send_email(recipient_email, follow_up_message):
24
- # Mailjet API endpoint
25
- url = 'https://api.mailjet.com/v3.1/send'
26
-
27
- # Sender email and details
28
- from_email = 'christ10aldika@gmail.com' # Sender email
29
- subject = 'Appointment Reminder'
30
 
31
- # Email payload
32
  payload = {
33
  "Messages": [
34
  {
35
- "From": {"Email": from_email, "Name": "Christ Aldika"}, # Sender name and email
36
- "To": [{"Email": recipient_email, "Name": recipient_email}], # Recipient email
37
  "Subject": subject,
38
- "TextPart": follow_up_message, # Use the generated follow-up message
39
  }
40
  ]
41
  }
42
 
43
- # Send the email request
44
  response = requests.post(url, json=payload, auth=(MAILJET_API_KEY, MAILJET_SECRET_KEY))
45
-
46
  if response.status_code == 200:
47
- print("Email sent successfully via Mailjet!")
48
- print("Response:", response.json())
49
  else:
50
- print(f"Failed to send email. Status Code: {response.status_code}")
51
- print("Response:", response.text)
52
 
 
 
 
53
  def generate_follow_up_message(patient_name):
 
54
  try:
55
- # Filter data by patient name
56
- patient_data = data[data['Patient Name'].str.contains(patient_name, case=False, na=False)]
57
-
58
- if patient_data.empty:
59
- return f"Patient with name {patient_name} not found.", None, None
60
-
61
- patient_data = patient_data.iloc[0]
62
 
63
- patient_id = patient_data['Patient ID']
64
- health_condition = patient_data['Health Condition']
65
- last_visit_date = patient_data['Last Visit Date']
66
- patient_email = patient_data['Email']
67
 
68
- # Convert last visit date to a datetime object
69
- last_visit_date_obj = datetime.strptime(last_visit_date, '%Y-%m-%d')
 
 
 
70
 
71
- # Add 7 days to the last visit date to calculate the next appointment date
 
72
  next_appointment_date = last_visit_date_obj + timedelta(days=7)
 
 
 
 
 
 
 
 
 
73
 
74
- # Format the next appointment date
75
- next_appointment_date_str = next_appointment_date.strftime('%Y-%m-%d')
76
-
77
- # Replace the placeholders in the prompt
78
- prompt = f"Write a polite, detailed follow-up message for {patient_name}, who has {health_condition} and last visited the doctor on {last_visit_date}. Remind them of their next appointment on {next_appointment_date_str} and encourage them to contact the clinic at sentramedika@gmail.com if they have concerns. Keep the message polite and informative, around 2 sentences."
79
-
80
- # Make a POST request to the DeepSeek API
81
  response = requests.post(
82
  url="https://openrouter.ai/api/v1/chat/completions",
83
  headers={
84
  "Authorization": f"Bearer {OPENROUTER_API_KEY}",
85
  "Content-Type": "application/json",
86
- "HTTP-Referer": "<YOUR_SITE_URL>", # Optional. Site URL for rankings
87
- "X-Title": "<YOUR_SITE_NAME>", # Optional. Site title for rankings
88
  },
89
- data=json.dumps({
90
- "model": "deepseek/deepseek-chat:free",
91
- "messages": [
92
- {
93
- "role": "user",
94
- "content": prompt
95
- }
96
- ],
97
- })
98
  )
99
 
100
- # Check if the request was successful
101
- if response.status_code == 200:
102
- follow_up_message = response.json()['choices'][0]['message']['content']
103
- formatted_message = "\n".join(textwrap.wrap(follow_up_message, width=80))
104
- return formatted_message, patient_email, patient_id
 
 
105
  else:
106
- return f"Failed to generate message. Error: {response.status_code}", None, None
107
 
108
  except Exception as e:
109
  return f"An error occurred: {e}", None, None
110
 
111
- # Streamlit UI for patient search and message sending
112
- st.title("Patient Follow-Up Reminder System")
113
-
114
- # Input box for patient name
115
  patient_name_input = st.text_input("Enter Patient Name")
116
 
117
  if patient_name_input:
118
- # Generate the follow-up message based on the input
119
  follow_up_message, patient_email, patient_id = generate_follow_up_message(patient_name_input)
120
-
121
- if "Patient not found" not in follow_up_message:
122
  st.write("**Generated Message:**")
123
  st.write(follow_up_message)
124
  st.write(f"**Patient ID:** {patient_id}")
125
-
126
  if st.button("Send Reminder"):
127
- # Send the email using Mailjet
128
- try:
129
- send_email(patient_email, follow_up_message)
130
- st.success("Message sent successfully!")
131
- except Exception as e:
132
- st.error(f"Failed to send email: {e}")
133
  else:
134
- st.warning(follow_up_message)
 
1
  import os
2
  import pandas as pd
3
  import requests
 
4
  import textwrap
5
  from datetime import datetime, timedelta
6
  import streamlit as st
7
 
8
+ # -----------------------------
9
+ # API Keys
10
+ # -----------------------------
11
  OPENROUTER_API_KEY = "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"
12
+ MAILJET_API_KEY = "f746efdd7af5c96a033ddb90a78a5704"
13
+ MAILJET_SECRET_KEY = "5ee6955f792909206669fb10e9910b57"
14
 
15
+ # -----------------------------
16
+ # Load Patient Data
17
+ # -----------------------------
18
  dataset_url = "https://huggingface.co/spaces/chrisaldikaraharja/AutomatedFollowUpSystem/resolve/main/PatientData%20-%20Sheet1.csv"
19
+ data = pd.read_csv(dataset_url)
20
+ st.write("Patient data loaded successfully.")
21
+ st.write(data.head())
22
 
23
+ # -----------------------------
24
+ # Mailjet Email Sender
25
+ # -----------------------------
 
 
26
  def send_email(recipient_email, follow_up_message):
27
+ """Send an email via Mailjet API."""
28
+ url = "https://api.mailjet.com/v3.1/send"
29
+ from_email = "christ10aldika@gmail.com"
30
+ subject = "Appointment Reminder"
 
 
31
 
 
32
  payload = {
33
  "Messages": [
34
  {
35
+ "From": {"Email": from_email, "Name": "Christ Aldika"},
36
+ "To": [{"Email": recipient_email, "Name": recipient_email}],
37
  "Subject": subject,
38
+ "TextPart": follow_up_message,
39
  }
40
  ]
41
  }
42
 
 
43
  response = requests.post(url, json=payload, auth=(MAILJET_API_KEY, MAILJET_SECRET_KEY))
 
44
  if response.status_code == 200:
45
+ return True, "Email sent successfully!"
 
46
  else:
47
+ return False, f"Failed to send email. Status: {response.status_code}, Response: {response.text}"
 
48
 
49
+ # -----------------------------
50
+ # Follow-Up Message Generator
51
+ # -----------------------------
52
  def generate_follow_up_message(patient_name):
53
+ """Generate a follow-up message for a patient using OpenRouter API."""
54
  try:
55
+ patient_data = data[data["Patient Name"].str.contains(patient_name, case=False, na=False)]
 
 
 
 
 
 
56
 
57
+ if patient_data.empty:
58
+ return f"Patient with name '{patient_name}' not found.", None, None
 
 
59
 
60
+ patient_data = patient_data.iloc[0]
61
+ patient_id = patient_data["Patient ID"]
62
+ health_condition = patient_data["Health Condition"]
63
+ last_visit_date = patient_data["Last Visit Date"]
64
+ patient_email = patient_data["Email"]
65
 
66
+ # Date calculations
67
+ last_visit_date_obj = datetime.strptime(last_visit_date, "%Y-%m-%d")
68
  next_appointment_date = last_visit_date_obj + timedelta(days=7)
69
+ next_appointment_date_str = next_appointment_date.strftime("%Y-%m-%d")
70
+
71
+ # Prompt for AI
72
+ prompt = (
73
+ f"Write a polite, detailed follow-up message for {patient_name}, who has {health_condition} "
74
+ f"and last visited the doctor on {last_visit_date}. Remind them of their next appointment "
75
+ f"on {next_appointment_date_str} and encourage them to contact the clinic at sentramedika@gmail.com "
76
+ f"if they have concerns. Keep the message polite and informative, around 2 sentences."
77
+ )
78
 
79
+ # API request to OpenRouter
 
 
 
 
 
 
80
  response = requests.post(
81
  url="https://openrouter.ai/api/v1/chat/completions",
82
  headers={
83
  "Authorization": f"Bearer {OPENROUTER_API_KEY}",
84
  "Content-Type": "application/json",
85
+ "HTTP-Referer": "https://your-site.com",
86
+ "X-Title": "Patient Follow-Up Reminder System",
87
  },
88
+ json={
89
+ "model": "deepseek/deepseek-r1:free", # ✅ Correct model
90
+ "messages": [{"role": "user", "content": prompt}]
91
+ }
 
 
 
 
 
92
  )
93
 
94
+ if response.ok:
95
+ try:
96
+ follow_up_message = response.json()["choices"][0]["message"]["content"]
97
+ formatted_message = "\n".join(textwrap.wrap(follow_up_message, width=80))
98
+ return formatted_message, patient_email, patient_id
99
+ except (KeyError, IndexError):
100
+ return "Unexpected API response format.", None, None
101
  else:
102
+ return f"Failed to generate message. Error: {response.status_code} - {response.text}", None, None
103
 
104
  except Exception as e:
105
  return f"An error occurred: {e}", None, None
106
 
107
+ # -----------------------------
108
+ # Streamlit UI
109
+ # -----------------------------
110
+ st.title("💌 Patient Follow-Up Reminder System")
111
  patient_name_input = st.text_input("Enter Patient Name")
112
 
113
  if patient_name_input:
 
114
  follow_up_message, patient_email, patient_id = generate_follow_up_message(patient_name_input)
115
+
116
+ if patient_email:
117
  st.write("**Generated Message:**")
118
  st.write(follow_up_message)
119
  st.write(f"**Patient ID:** {patient_id}")
120
+
121
  if st.button("Send Reminder"):
122
+ success, message = send_email(patient_email, follow_up_message)
123
+ if success:
124
+ st.success(message)
125
+ else:
126
+ st.error(message)
 
127
  else:
128
+ st.warning(follow_up_message)