Spaces:
Sleeping
Sleeping
File size: 6,435 Bytes
8e315dc 982b8ff 3ba658d 8e315dc 982b8ff 8e315dc 982b8ff 67efa1b 982b8ff 8e315dc 982b8ff 8e315dc 982b8ff a4b12c8 8e315dc 982b8ff 8e315dc 982b8ff 8e315dc 982b8ff 8e315dc 982b8ff 8e315dc 982b8ff 8e315dc 982b8ff 8e315dc 6331370 8e315dc 982b8ff 8e315dc 982b8ff 8e315dc 982b8ff 8e315dc |
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 |
import os
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import requests
# News API Key
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 stress_level_to_string(stress_level):
"""Convert numerical stress level (0, 1, 2) to a string representation."""
if stress_level == 0:
return "Low"
elif stress_level == 1:
return "Moderate"
else:
return "High"
def provide_advice_from_articles(data):
advice = []
stress_level = stress_level_to_string(data['stress_level'])
if stress_level == "High":
advice.append("Searching for articles related to high stress...")
articles = fetch_health_articles("high stress")
for article in articles:
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
elif stress_level == "Moderate":
advice.append("Searching for articles related to moderate stress...")
articles = fetch_health_articles("moderate stress")
for article in articles:
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
else:
advice.append("Searching for articles related to low stress...")
articles = fetch_health_articles("low stress")
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: {stress_level_to_string(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()
|