chrisaldikaraharja's picture
Update app.py
634353f verified
import os
import pandas as pd
import requests
import json
import textwrap
from datetime import datetime, timedelta
import streamlit as st
# Set your API key
OPENROUTER_API_KEY = "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"
# Load your patient data
dataset_url = "https://huggingface.co/spaces/chrisaldikaraharja/AutomatedFollowUpSystem/resolve/main/PatientData%20-%20Sheet1.csv"
data = pd.read_csv(dataset_url) # Loading the patient data from the URL
st.write("Patient data loaded successfully.")
st.write(data.head()) # Displaying the first few rows of the dataset
# Mailjet API credentials
MAILJET_API_KEY = 'f746efdd7af5c96a033ddb90a78a5704'
MAILJET_SECRET_KEY = '5ee6955f792909206669fb10e9910b57'
# Function to send email using Mailjet
def send_email(recipient_email, follow_up_message):
# Mailjet API endpoint
url = 'https://api.mailjet.com/v3.1/send'
# Sender email and details
from_email = 'christ10aldika@gmail.com' # Sender email
subject = 'Appointment Reminder'
# Email payload
payload = {
"Messages": [
{
"From": {"Email": from_email, "Name": "Christ Aldika"}, # Sender name and email
"To": [{"Email": recipient_email, "Name": recipient_email}], # Recipient email
"Subject": subject,
"TextPart": follow_up_message, # Use the generated follow-up message
}
]
}
# Send the email request
response = requests.post(url, json=payload, auth=(MAILJET_API_KEY, MAILJET_SECRET_KEY))
if response.status_code == 200:
print("Email sent successfully via Mailjet!")
print("Response:", response.json())
else:
print(f"Failed to send email. Status Code: {response.status_code}")
print("Response:", response.text)
def generate_follow_up_message(patient_name):
try:
# Filter data by patient name
patient_data = data[data['Patient Name'].str.contains(patient_name, case=False, na=False)]
if patient_data.empty:
return f"Patient with name {patient_name} not found.", None, None
patient_data = patient_data.iloc[0]
patient_id = patient_data['Patient ID']
health_condition = patient_data['Health Condition']
last_visit_date = patient_data['Last Visit Date']
patient_email = patient_data['Email']
# Convert last visit date to a datetime object
last_visit_date_obj = datetime.strptime(last_visit_date, '%Y-%m-%d')
# Add 7 days to the last visit date to calculate the next appointment date
next_appointment_date = last_visit_date_obj + timedelta(days=7)
# Format the next appointment date
next_appointment_date_str = next_appointment_date.strftime('%Y-%m-%d')
# Replace the placeholders in the prompt
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."
# Make a POST request to the DeepSeek API
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"Content-Type": "application/json",
"HTTP-Referer": "<YOUR_SITE_URL>", # Optional. Site URL for rankings
"X-Title": "<YOUR_SITE_NAME>", # Optional. Site title for rankings
},
data=json.dumps({
"model": "deepseek/deepseek-chat:free",
"messages": [
{
"role": "user",
"content": prompt
}
],
})
)
# Check if the request was successful
if response.status_code == 200:
follow_up_message = response.json()['choices'][0]['message']['content']
formatted_message = "\n".join(textwrap.wrap(follow_up_message, width=80))
return formatted_message, patient_email, patient_id
else:
return f"Failed to generate message. Error: {response.status_code}", None, None
except Exception as e:
return f"An error occurred: {e}", None, None
# Streamlit UI for patient search and message sending
st.title("Patient Follow-Up Reminder System")
# Input box for patient name
patient_name_input = st.text_input("Enter Patient Name")
if patient_name_input:
# Generate the follow-up message based on the input
follow_up_message, patient_email, patient_id = generate_follow_up_message(patient_name_input)
if "Patient not found" not in follow_up_message:
st.write("**Generated Message:**")
st.write(follow_up_message)
st.write(f"**Patient ID:** {patient_id}")
if st.button("Send Reminder"):
# Send the email using Mailjet
try:
send_email(patient_email, follow_up_message)
st.success("Message sent successfully!")
except Exception as e:
st.error(f"Failed to send email: {e}")
else:
st.warning(follow_up_message)