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)