Health_advisor / app.py
saherPervaiz's picture
Update app.py
67efa1b verified
raw
history blame
8.99 kB
import os
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import requests
news_api_key = "fe1e6bcbbf384b3e9220a7a1138805e0" # Replace with your News API key
@st.cache_data
def load_data(file):
return pd.read_csv(file)
def fetch_health_articles(query):
url = f"https://newsapi.org/v2/everything?q={query}&apiKey={news_api_key}"
response = requests.get(url)
if response.status_code == 200:
articles = response.json().get('articles', [])
return articles[:5]
else:
st.error("Failed to fetch news articles. Please check your API key or try again later.")
return []
def provide_advice_from_articles(data):
advice = []
# High depression
if data['depression'] > 7:
advice.append("πŸ”΄ **High Depression Levels Detected**")
advice.append("""
Depression is a serious condition that affects many aspects of life. If you are experiencing high levels of depression, it is important to seek professional help.
Here are some key steps that might help:
- **Consider therapy**: Cognitive Behavioral Therapy (CBT) is proven to be effective for managing depression.
- **Stay active**: Exercise can boost your mood and reduce stress.
- **Reach out to loved ones**: Isolation can worsen depression, so staying connected with friends and family is crucial.
- **Practice mindfulness**: Techniques such as deep breathing and meditation can be effective in managing depressive symptoms.
""")
articles = fetch_health_articles("high depression")
for article in articles:
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
# High anxiety
elif data['anxiety_level'] > 7:
advice.append("🟠 **High Anxiety Levels Detected**")
advice.append("""
Anxiety can cause significant distress and impact daily life. Addressing anxiety early can help you regain control over your well-being.
Here's how you can manage anxiety:
- **Breathing exercises**: Slow, deep breaths can help calm the mind and body.
- **Progressive muscle relaxation**: Tense and then relax different muscle groups to reduce physical tension.
- **Limit stimulants**: Reduce caffeine and sugar, which can increase anxiety.
- **Journaling**: Writing down your thoughts can help process feelings of anxiety.
""")
articles = fetch_health_articles("high anxiety")
for article in articles:
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
# High stress
elif data['stress_level'] > 7:
advice.append("🟑 **High Stress Levels Detected**")
advice.append("""
Prolonged stress can have adverse effects on both mental and physical health. Managing stress is crucial for maintaining balance and well-being.
Consider these strategies:
- **Time management**: Prioritize tasks and break them down into manageable steps to avoid feeling overwhelmed.
- **Physical activity**: Exercise can act as a natural stress reliever.
- **Relaxation techniques**: Meditation, yoga, or simply taking breaks during the day can reduce stress.
- **Sleep hygiene**: Ensure you're getting enough restful sleep by maintaining a regular sleep schedule.
""")
articles = fetch_health_articles("high stress")
for article in articles:
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
# General mental health advice
else:
advice.append("🟒 **General Health Advice**")
advice.append("""
Maintaining mental health is an ongoing process, and it’s important to integrate healthy habits into daily life. Here are some general tips:
- **Exercise regularly**: Physical activity can significantly boost mood and mental clarity.
- **Eat a balanced diet**: Nutrition plays a vital role in mental well-being.
- **Practice gratitude**: Reflecting on things you’re grateful for can shift your focus from stress to positivity.
- **Social support**: Stay connected with family and friends for emotional support.
""")
articles = fetch_health_articles("mental health")
for article in articles:
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
return advice
def plot_graphs(data):
# Create subplots for visualization
st.markdown("### πŸ“Š Data Visualizations")
st.write("Explore key insights through visualizations.")
# Correlation heatmap
st.markdown("#### Correlation Heatmap")
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(data.corr(), annot=True, cmap="coolwarm", ax=ax)
ax.set_title("Correlation Heatmap")
st.pyplot(fig)
def main():
st.set_page_config(
page_title="Student Well-being Advisor",
page_icon="πŸ“Š",
layout="wide",
initial_sidebar_state="expanded",
)
st.sidebar.title("Navigation")
st.sidebar.write("Use the sidebar to navigate through the app.")
st.sidebar.markdown("### πŸ“‚ Upload Data")
st.sidebar.write("Start by uploading your dataset for analysis.")
st.sidebar.markdown("### πŸ“Š Analysis & Advice")
st.sidebar.write("Get detailed insights and personalized advice.")
st.title("πŸŽ“ Student Well-being Advisor")
st.subheader("Analyze data and provide professional mental health recommendations.")
st.write("""
This app helps identify areas of concern in students' well-being and provides personalized advice based on their responses.
""")
st.markdown("## πŸ“‚ Upload Your Dataset")
uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
if uploaded_file:
df = load_data(uploaded_file)
st.success("Dataset uploaded successfully!")
st.write("### Dataset Preview:")
st.dataframe(df.head())
required_columns = [
'anxiety_level', 'self_esteem', 'mental_health_history', 'depression',
'headache', 'blood_pressure', 'sleep_quality', 'breathing_problem',
'noise_level', 'living_conditions', 'safety', 'basic_needs',
'academic_performance', 'study_load', 'teacher_student_relationship',
'future_career_concerns', 'social_support', 'peer_pressure',
'extracurricular_activities', 'bullying', 'stress_level'
]
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
st.error(f"The uploaded dataset is missing the following required columns: {', '.join(missing_columns)}")
else:
if df.isnull().values.any():
st.warning("The dataset contains missing values. Rows with missing values will be skipped.")
df = df.dropna()
tab1, tab2, tab3 = st.tabs(["🏠 Home", "πŸ“Š Analysis", "πŸ“° Resources"])
with tab1:
st.write("### Welcome to the Well-being Advisor!")
st.write("""
Use the tabs to explore data, generate advice, and access mental health resources.
""")
with tab2:
st.markdown("### πŸ“Š Select a Row for Analysis")
selected_row = st.selectbox(
"Select a row (based on index) to analyze:",
options=df.index,
format_func=lambda x: f"Row {x} - Stress Level: {df.loc[x, 'stress_level']}, Anxiety: {df.loc[x, 'anxiety_level']} (Depression: {df.loc[x, 'depression']})",
)
row_data = df.loc[selected_row].to_dict()
st.write("### Selected User Details:")
st.json(row_data)
st.subheader("πŸ”” Health Advice Based on Articles")
advice = provide_advice_from_articles(row_data)
if advice:
for i, tip in enumerate(advice, 1):
st.write(f"πŸ“Œ **{i}.** {tip}")
else:
st.warning("No specific advice available based on this user's data.")
# Include graphs in analysis tab
plot_graphs(df)
with tab3:
st.subheader("πŸ“° Mental Health Resources")
articles = fetch_health_articles("mental health")
if articles:
for article in articles:
st.write(f"**{article['title']}**")
st.write(f"{article['description']}")
st.write(f"[Read more]({article['url']})")
else:
st.write("No articles available at the moment.")
if __name__ == "__main__":
main()