File size: 5,010 Bytes
c202c07
 
 
 
 
 
 
5645b28
 
 
ff10db9
5645b28
 
c202c07
5645b28
 
 
57c4f85
5645b28
 
 
4dd0dfc
5645b28
 
 
634353f
5645b28
 
 
 
634353f
 
 
 
5645b28
 
634353f
5645b28
634353f
 
 
 
 
 
5645b28
634353f
5645b28
634353f
5645b28
 
 
4dd0dfc
5645b28
c202c07
5645b28
c202c07
5645b28
 
c202c07
5645b28
 
 
 
 
c202c07
5645b28
 
c202c07
5645b28
 
 
 
 
 
 
 
 
c202c07
5645b28
c202c07
 
 
 
 
5645b28
 
c202c07
5645b28
 
 
 
c202c07
 
5645b28
 
 
 
 
 
 
c202c07
5645b28
c202c07
 
4dd0dfc
c202c07
5645b28
 
 
 
c202c07
 
4dd0dfc
 
5645b28
 
c202c07
 
4dd0dfc
5645b28
c202c07
5645b28
 
 
 
 
c202c07
5645b28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import os
import pandas as pd
import requests
import textwrap
from datetime import datetime, timedelta
import streamlit as st

# -----------------------------
# API Keys
# -----------------------------
OPENROUTER_API_KEY = "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"
MAILJET_API_KEY = "f746efdd7af5c96a033ddb90a78a5704"
MAILJET_SECRET_KEY = "5ee6955f792909206669fb10e9910b57"

# -----------------------------
# Load Patient Data
# -----------------------------
dataset_url = "https://huggingface.co/spaces/chrisaldikaraharja/AutomatedFollowUpSystem/resolve/main/PatientData%20-%20Sheet1.csv"
data = pd.read_csv(dataset_url)
st.write("✅ Patient data loaded successfully.")
st.write(data.head())

# -----------------------------
# Mailjet Email Sender
# -----------------------------
def send_email(recipient_email, follow_up_message):
    """Send an email via Mailjet API."""
    url = "https://api.mailjet.com/v3.1/send"
    from_email = "christ10aldika@gmail.com"
    subject = "Appointment Reminder"

    payload = {
        "Messages": [
            {
                "From": {"Email": from_email, "Name": "Christ Aldika"},
                "To": [{"Email": recipient_email, "Name": recipient_email}],
                "Subject": subject,
                "TextPart": follow_up_message,
            }
        ]
    }

    response = requests.post(url, json=payload, auth=(MAILJET_API_KEY, MAILJET_SECRET_KEY))
    if response.status_code == 200:
        return True, "Email sent successfully!"
    else:
        return False, f"Failed to send email. Status: {response.status_code}, Response: {response.text}"

# -----------------------------
# Follow-Up Message Generator
# -----------------------------
def generate_follow_up_message(patient_name):
    """Generate a follow-up message for a patient using OpenRouter API."""
    try:
        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"]

        # Date calculations
        last_visit_date_obj = datetime.strptime(last_visit_date, "%Y-%m-%d")
        next_appointment_date = last_visit_date_obj + timedelta(days=7)
        next_appointment_date_str = next_appointment_date.strftime("%Y-%m-%d")

        # Prompt for AI
        prompt = (
            f"Write a polite, detailed follow-up message for {patient_name}, who has {health_condition} "
            f"and last visited the doctor on {last_visit_date}. Remind them of their next appointment "
            f"on {next_appointment_date_str} and encourage them to contact the clinic at sentramedika@gmail.com "
            f"if they have concerns. Keep the message polite and informative, around 2 sentences."
        )

        # API request to OpenRouter
        response = requests.post(
            url="https://openrouter.ai/api/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {OPENROUTER_API_KEY}",
                "Content-Type": "application/json",
                "HTTP-Referer": "https://your-site.com",  
                "X-Title": "Patient Follow-Up Reminder System",
            },
            json={
                "model": "deepseek/deepseek-r1:free",  # ✅ Correct model
                "messages": [{"role": "user", "content": prompt}]
            }
        )

        if response.ok:
            try:
                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
            except (KeyError, IndexError):
                return "Unexpected API response format.", None, None
        else:
            return f"Failed to generate message. Error: {response.status_code} - {response.text}", None, None

    except Exception as e:
        return f"An error occurred: {e}", None, None

# -----------------------------
# Streamlit UI
# -----------------------------
st.title("💌 Patient Follow-Up Reminder System")
patient_name_input = st.text_input("Enter Patient Name")

if patient_name_input:
    follow_up_message, patient_email, patient_id = generate_follow_up_message(patient_name_input)

    if patient_email:
        st.write("**Generated Message:**")
        st.write(follow_up_message)
        st.write(f"**Patient ID:** {patient_id}")

        if st.button("Send Reminder"):
            success, message = send_email(patient_email, follow_up_message)
            if success:
                st.success(message)
            else:
                st.error(message)
    else:
        st.warning(follow_up_message)