King-Afridi's picture
Update app.py
4fbcb0c verified
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)