File size: 8,140 Bytes
1fc3fa2 688bec7 ee53389 688bec7 0f2d1b8 688bec7 5d60a81 688bec7 70cb1c4 688bec7 ce8797c 688bec7 c6b6aa5 688bec7 0f2d1b8 688bec7 0f2d1b8 688bec7 0f2d1b8 688bec7 c331fe1 b126a5e 4fbcb0c 2383a48 b126a5e b760249 b7da766 b07fea4 b7da766 688bec7 c331fe1 b7da766 b760249 36cd25e c898630 |
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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from datetime import date
import os
from groq import Groq
from gtts import gTTS
import tempfile
import requests
# Set your API keys here
api_key = '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'
news_api_key = '11a477927da6466ca67f7fc512a2d8f2' # Add your News API key
# Initialize Groq client
client = Groq(api_key=api_key)
# Function for MedBot
def query_groq(prompt):
try:
response = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama3-8b-8192"
)
return response.choices[0].message.content
except Exception as e:
return f"Error interacting with Groq API: {e}"
def text_to_speech(text):
try:
tts = gTTS(text=text, lang='en')
temp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
tts.save(temp_audio.name)
return temp_audio.name
except Exception as e:
return f"Error generating speech: {e}"
def med_chatbot(user_input):
llm_response = query_groq(user_input)
if "Error" in llm_response:
return llm_response, None
audio_path = text_to_speech(llm_response)
return llm_response, audio_path
# Function to fetch latest healthcare/therapist news
def get_healthcare_news():
url = f'https://newsapi.org/v2/everything?q=healthcare OR therapy&apiKey={news_api_key}'
try:
response = requests.get(url)
news_data = response.json()
articles = news_data.get('articles', [])
news_list = []
for article in articles[:5]: # Get the top 5 articles
title = article.get('title', 'No Title')
description = article.get('description', 'No Description')
url = article.get('url', '')
news_list.append(f"**{title}**\n{description}\n[Read more]({url})\n\n")
return news_list
except Exception as e:
return [f"Error fetching news: {e}"]
# Streamlit Page Configuration
st.set_page_config(page_title="Healthcare Application", layout="wide")
# Add a logo at the top of your app
logo_path = 'https://huggingface.co/spaces/King-Afridi/MediTherapist-Your-Complete-Health-Wellness-Companion/resolve/main/pexels-totalshape-2383010.jpg' # Path to your uploaded logo
st.image(logo_path, width=200)
# Add healthcare-themed background image
st.markdown("""
<style>
body {
background-image: url(background_url = 'https://huggingface.co/spaces/your-space-name/resolve/main/your-image.jpg'
); /* Path to your uploaded background image */
background-size: cover;
font-family: 'Arial', sans-serif;
}
</style>
""", unsafe_allow_html=True)
# Sidebar Navigation
menu = st.sidebar.radio("Navigation", ["MedBot", "Therapist Dashboard", "Healthcare News"])
# MedBot Interface
if menu == "MedBot":
st.title("MedBot", anchor="medbot")
st.write("A real-time medical chatbot with text-to-speech capabilities. Ask your questions below.")
user_input = st.text_input("Ask your medical question:")
if st.button("Submit"):
response, audio_path = med_chatbot(user_input)
st.text("Response:")
st.write(response)
if audio_path:
st.audio(audio_path, format="audio/mp3")
# Therapist Dashboard Interface
elif menu == "Therapist Dashboard":
# Updated therapist interface
# Utility functions for persistent storage
def load_data(file_name):
if os.path.exists(file_name):
return pd.read_csv(file_name)
else:
return pd.DataFrame()
def save_data(file_name, data):
data.to_csv(file_name, index=False)
# Load stored data
sessions_file = "sessions.csv"
moods_file = "moods.csv"
sessions_data = load_data(sessions_file)
moods_data = load_data(moods_file)
# Ensure necessary columns exist in loaded data
if not sessions_data.empty and "Patient" not in sessions_data.columns:
sessions_data["Patient"] = ""
if not moods_data.empty and "Patient" not in moods_data.columns:
moods_data["Patient"] = ""
# Title
st.title("Therapist Dashboard", anchor="dashboard")
st.write("A comprehensive tool for therapists to manage sessions, track progress, and analyze patient data.")
# Sidebar Navigation
dashboard_menu = st.sidebar.radio("Dashboard Menu", ["Home", "Session Tracker", "Mood Tracker", "Patient Analytics"])
if dashboard_menu == "Home":
st.header("Welcome to the Therapist Dashboard")
st.write("This application provides tools to enhance your therapy practice. Navigate through the sidebar to explore features.")
elif dashboard_menu == "Session Tracker":
st.header("Session Tracker")
# Log session
st.write("### Log New Session")
session_date = st.date_input("Session Date", value=date.today())
session_time = st.time_input("Session Time")
patient_name = st.text_input("Patient Name")
session_notes = st.text_area("Session Notes")
if st.button("Save Session"):
new_session = pd.DataFrame({
"Date": [session_date],
"Time": [session_time],
"Patient": [patient_name],
"Notes": [session_notes]
})
sessions_data = pd.concat([sessions_data, new_session], ignore_index=True)
save_data(sessions_file, sessions_data)
st.success(f"Session for {patient_name} on {session_date} saved successfully!")
# Display session logs
st.write("### Recent Sessions")
if not sessions_data.empty:
st.table(sessions_data.tail(10))
else:
st.write("No sessions logged yet.")
elif dashboard_menu == "Mood Tracker":
st.header("Mood Tracker")
# Log mood
st.write("### Log Mood")
mood_date = st.date_input("Date", value=date.today(), key="mood_date")
mood_level = st.slider("Mood Level (1-10)", 1, 10, 5)
patient_name = st.text_input("Patient Name (for Mood Tracker)", key="mood_patient")
mood_notes = st.text_area("Notes", key="mood_notes")
if st.button("Save Mood Entry"):
new_mood = pd.DataFrame({
"Date": [mood_date],
"Mood Level": [mood_level],
"Patient": [patient_name],
"Notes": [mood_notes]
})
moods_data = pd.concat([moods_data, new_mood], ignore_index=True)
save_data(moods_file, moods_data)
st.success("Mood entry saved!")
# Display mood trends
st.write("### Mood Trends")
if not moods_data.empty:
moods_data["Date"] = pd.to_datetime(moods_data["Date"])
fig, ax = plt.subplots()
ax.plot(moods_data["Date"], moods_data["Mood Level"], marker="o")
ax.set_title("Mood Trends")
ax.set_xlabel("Date")
ax.set_ylabel("Mood Level")
st.pyplot(fig)
else:
st.write("No mood entries logged yet.")
elif dashboard_menu == "Patient Analytics":
st.header("Patient Analytics")
if not sessions_data.empty:
st.write("### Session Analytics")
analytics_data = sessions_data.groupby("Patient").size().reset_index(name="Sessions Conducted")
if not moods_data.empty:
avg_mood = moods_data.groupby("Patient")["Mood Level"].mean().reset_index()
avg_mood.rename(columns={"Mood Level": "Average Mood"}, inplace=True)
analytics_data = pd.merge(analytics_data, avg_mood, on="Patient", how="left")
st.bar_chart(analytics_data.set_index("Patient"))
# Detailed patient reports
selected_patient = st.selectbox("Select a patient for detailed analytics", analytics_data["Patient"].unique())
patient_data = sessions_data[sessions_data["Patient"] == selected_patient]
st.write(f"### Detailed Report for {selected_patient}")
st.table(patient_data)
|