Update app.py
Browse files
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 |
-
#
|
|
|
|
|
|
|
| 10 |
OPENROUTER_API_KEY = "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"
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
|
|
|
|
|
|
| 13 |
dataset_url = "https://huggingface.co/spaces/chrisaldikaraharja/AutomatedFollowUpSystem/resolve/main/PatientData%20-%20Sheet1.csv"
|
| 14 |
-
data = pd.read_csv(dataset_url)
|
| 15 |
-
st.write("Patient data loaded successfully.")
|
| 16 |
-
st.write(data.head())
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
# Function to send email using Mailjet
|
| 23 |
def send_email(recipient_email, follow_up_message):
|
| 24 |
-
|
| 25 |
-
url =
|
| 26 |
-
|
| 27 |
-
|
| 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"},
|
| 36 |
-
"To": [{"Email": recipient_email, "Name": recipient_email}],
|
| 37 |
"Subject": subject,
|
| 38 |
-
"TextPart": 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 |
-
|
| 48 |
-
print("Response:", response.json())
|
| 49 |
else:
|
| 50 |
-
|
| 51 |
-
print("Response:", response.text)
|
| 52 |
|
|
|
|
|
|
|
|
|
|
| 53 |
def generate_follow_up_message(patient_name):
|
|
|
|
| 54 |
try:
|
| 55 |
-
|
| 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 |
-
|
| 64 |
-
|
| 65 |
-
last_visit_date = patient_data['Last Visit Date']
|
| 66 |
-
patient_email = patient_data['Email']
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
#
|
|
|
|
| 72 |
next_appointment_date = last_visit_date_obj + timedelta(days=7)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
#
|
| 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": "
|
| 87 |
-
"X-Title": "
|
| 88 |
},
|
| 89 |
-
|
| 90 |
-
"model": "deepseek/deepseek-
|
| 91 |
-
"messages": [
|
| 92 |
-
|
| 93 |
-
"role": "user",
|
| 94 |
-
"content": prompt
|
| 95 |
-
}
|
| 96 |
-
],
|
| 97 |
-
})
|
| 98 |
)
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
| 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 |
-
#
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 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
|
| 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 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 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)
|