Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,8 @@
|
|
1 |
import os
|
2 |
import streamlit as st
|
3 |
import pandas as pd
|
|
|
|
|
4 |
import requests
|
5 |
|
6 |
news_api_key = "fe1e6bcbbf384b3e9220a7a1138805e0" # Replace with your News API key
|
@@ -10,48 +12,70 @@ def load_data(file):
|
|
10 |
return pd.read_csv(file)
|
11 |
|
12 |
def fetch_health_articles(query):
|
13 |
-
# Fetch mental health articles related to the query
|
14 |
url = f"https://newsapi.org/v2/everything?q={query}&apiKey={news_api_key}"
|
15 |
response = requests.get(url)
|
16 |
if response.status_code == 200:
|
17 |
articles = response.json().get('articles', [])
|
18 |
-
return articles[:5]
|
19 |
else:
|
20 |
st.error("Failed to fetch news articles. Please check your API key or try again later.")
|
21 |
return []
|
22 |
|
23 |
def provide_advice_from_articles(data):
|
24 |
advice = []
|
25 |
-
|
26 |
-
# Use user data to fetch relevant health advice based on depression, anxiety, stress, etc.
|
27 |
if data['depression'] > 7:
|
28 |
advice.append("Searching for articles related to high depression...")
|
29 |
articles = fetch_health_articles("high depression")
|
30 |
for article in articles:
|
31 |
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
|
32 |
-
|
33 |
elif data['anxiety_level'] > 7:
|
34 |
advice.append("Searching for articles related to high anxiety...")
|
35 |
articles = fetch_health_articles("high anxiety")
|
36 |
for article in articles:
|
37 |
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
|
38 |
-
|
39 |
elif data['stress_level'] > 7:
|
40 |
advice.append("Searching for articles related to high stress...")
|
41 |
articles = fetch_health_articles("high stress")
|
42 |
for article in articles:
|
43 |
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
|
44 |
-
|
45 |
else:
|
46 |
advice.append("Searching for general health advice articles...")
|
47 |
articles = fetch_health_articles("mental health")
|
48 |
for article in articles:
|
49 |
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
|
50 |
-
|
51 |
return advice
|
52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
def main():
|
54 |
-
# Set page config for a professional look
|
55 |
st.set_page_config(
|
56 |
page_title="Student Well-being Advisor",
|
57 |
page_icon="π",
|
@@ -59,7 +83,6 @@ def main():
|
|
59 |
initial_sidebar_state="expanded",
|
60 |
)
|
61 |
|
62 |
-
# Sidebar
|
63 |
st.sidebar.title("Navigation")
|
64 |
st.sidebar.write("Use the sidebar to navigate through the app.")
|
65 |
st.sidebar.markdown("### π Upload Data")
|
@@ -67,16 +90,12 @@ def main():
|
|
67 |
st.sidebar.markdown("### π Analysis & Advice")
|
68 |
st.sidebar.write("Get detailed insights and personalized advice.")
|
69 |
|
70 |
-
# Main Content
|
71 |
st.title("π Student Well-being Advisor")
|
72 |
st.subheader("Analyze data and provide professional mental health recommendations.")
|
73 |
-
st.write(
|
74 |
-
"""
|
75 |
This app helps identify areas of concern in students' well-being and provides personalized advice based on their responses.
|
76 |
-
|
77 |
-
)
|
78 |
|
79 |
-
# File Upload
|
80 |
st.markdown("## π Upload Your Dataset")
|
81 |
uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
|
82 |
if uploaded_file:
|
@@ -85,13 +104,12 @@ def main():
|
|
85 |
st.write("### Dataset Preview:")
|
86 |
st.dataframe(df.head())
|
87 |
|
88 |
-
# Validate dataset columns
|
89 |
required_columns = [
|
90 |
-
'anxiety_level', 'self_esteem', 'mental_health_history', 'depression',
|
91 |
-
'headache', 'blood_pressure', 'sleep_quality', 'breathing_problem',
|
92 |
-
'noise_level', 'living_conditions', 'safety', 'basic_needs',
|
93 |
-
'academic_performance', 'study_load', 'teacher_student_relationship',
|
94 |
-
'future_career_concerns', 'social_support', 'peer_pressure',
|
95 |
'extracurricular_activities', 'bullying', 'stress_level'
|
96 |
]
|
97 |
missing_columns = [col for col in required_columns if col not in df.columns]
|
@@ -99,21 +117,17 @@ def main():
|
|
99 |
if missing_columns:
|
100 |
st.error(f"The uploaded dataset is missing the following required columns: {', '.join(missing_columns)}")
|
101 |
else:
|
102 |
-
# Handle missing values in the dataset
|
103 |
if df.isnull().values.any():
|
104 |
st.warning("The dataset contains missing values. Rows with missing values will be skipped.")
|
105 |
df = df.dropna()
|
106 |
|
107 |
-
# Tabs for better organization
|
108 |
tab1, tab2, tab3 = st.tabs(["π Home", "π Analysis", "π° Resources"])
|
109 |
|
110 |
with tab1:
|
111 |
st.write("### Welcome to the Well-being Advisor!")
|
112 |
-
st.write(
|
113 |
-
"""
|
114 |
Use the tabs to explore data, generate advice, and access mental health resources.
|
115 |
-
|
116 |
-
)
|
117 |
|
118 |
with tab2:
|
119 |
st.markdown("### π Select a Row for Analysis")
|
@@ -122,15 +136,10 @@ def main():
|
|
122 |
options=df.index,
|
123 |
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']})",
|
124 |
)
|
125 |
-
|
126 |
-
# Extract data for the selected row
|
127 |
row_data = df.loc[selected_row].to_dict()
|
128 |
-
|
129 |
-
# Show extracted details
|
130 |
st.write("### Selected User Details:")
|
131 |
st.json(row_data)
|
132 |
|
133 |
-
# Fetch and display health advice from articles
|
134 |
st.subheader("π Health Advice Based on Articles")
|
135 |
advice = provide_advice_from_articles(row_data)
|
136 |
if advice:
|
@@ -139,8 +148,10 @@ def main():
|
|
139 |
else:
|
140 |
st.warning("No specific advice available based on this user's data.")
|
141 |
|
|
|
|
|
|
|
142 |
with tab3:
|
143 |
-
# Fetch and display mental health articles
|
144 |
st.subheader("π° Mental Health Resources")
|
145 |
articles = fetch_health_articles("mental health")
|
146 |
if articles:
|
|
|
1 |
import os
|
2 |
import streamlit as st
|
3 |
import pandas as pd
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
import seaborn as sns
|
6 |
import requests
|
7 |
|
8 |
news_api_key = "fe1e6bcbbf384b3e9220a7a1138805e0" # Replace with your News API key
|
|
|
12 |
return pd.read_csv(file)
|
13 |
|
14 |
def fetch_health_articles(query):
|
|
|
15 |
url = f"https://newsapi.org/v2/everything?q={query}&apiKey={news_api_key}"
|
16 |
response = requests.get(url)
|
17 |
if response.status_code == 200:
|
18 |
articles = response.json().get('articles', [])
|
19 |
+
return articles[:5]
|
20 |
else:
|
21 |
st.error("Failed to fetch news articles. Please check your API key or try again later.")
|
22 |
return []
|
23 |
|
24 |
def provide_advice_from_articles(data):
|
25 |
advice = []
|
|
|
|
|
26 |
if data['depression'] > 7:
|
27 |
advice.append("Searching for articles related to high depression...")
|
28 |
articles = fetch_health_articles("high depression")
|
29 |
for article in articles:
|
30 |
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
|
|
|
31 |
elif data['anxiety_level'] > 7:
|
32 |
advice.append("Searching for articles related to high anxiety...")
|
33 |
articles = fetch_health_articles("high anxiety")
|
34 |
for article in articles:
|
35 |
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
|
|
|
36 |
elif data['stress_level'] > 7:
|
37 |
advice.append("Searching for articles related to high stress...")
|
38 |
articles = fetch_health_articles("high stress")
|
39 |
for article in articles:
|
40 |
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
|
|
|
41 |
else:
|
42 |
advice.append("Searching for general health advice articles...")
|
43 |
articles = fetch_health_articles("mental health")
|
44 |
for article in articles:
|
45 |
advice.append(f"**{article['title']}**\n{article['description']}\n[Read more]({article['url']})")
|
|
|
46 |
return advice
|
47 |
|
48 |
+
def plot_graphs(data):
|
49 |
+
# Create subplots for visualization
|
50 |
+
st.markdown("### π Data Visualizations")
|
51 |
+
st.write("Explore key insights through visualizations.")
|
52 |
+
|
53 |
+
# Histogram for depression
|
54 |
+
st.markdown("#### Histogram of Depression Levels")
|
55 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
56 |
+
ax.hist(data['depression'], bins=20, color='skyblue', edgecolor='black')
|
57 |
+
ax.set_title("Histogram of Depression Levels")
|
58 |
+
ax.set_xlabel("Depression Level")
|
59 |
+
ax.set_ylabel("Frequency")
|
60 |
+
st.pyplot(fig)
|
61 |
+
|
62 |
+
# Scatter plot for anxiety vs. depression
|
63 |
+
st.markdown("#### Scatter Plot: Anxiety vs Depression")
|
64 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
65 |
+
sns.scatterplot(x=data['anxiety_level'], y=data['depression'], ax=ax, color='blue')
|
66 |
+
ax.set_title("Anxiety Level vs Depression")
|
67 |
+
ax.set_xlabel("Anxiety Level")
|
68 |
+
ax.set_ylabel("Depression")
|
69 |
+
st.pyplot(fig)
|
70 |
+
|
71 |
+
# Correlation heatmap
|
72 |
+
st.markdown("#### Correlation Heatmap")
|
73 |
+
fig, ax = plt.subplots(figsize=(10, 8))
|
74 |
+
sns.heatmap(data.corr(), annot=True, cmap="coolwarm", ax=ax)
|
75 |
+
ax.set_title("Correlation Heatmap")
|
76 |
+
st.pyplot(fig)
|
77 |
+
|
78 |
def main():
|
|
|
79 |
st.set_page_config(
|
80 |
page_title="Student Well-being Advisor",
|
81 |
page_icon="π",
|
|
|
83 |
initial_sidebar_state="expanded",
|
84 |
)
|
85 |
|
|
|
86 |
st.sidebar.title("Navigation")
|
87 |
st.sidebar.write("Use the sidebar to navigate through the app.")
|
88 |
st.sidebar.markdown("### π Upload Data")
|
|
|
90 |
st.sidebar.markdown("### π Analysis & Advice")
|
91 |
st.sidebar.write("Get detailed insights and personalized advice.")
|
92 |
|
|
|
93 |
st.title("π Student Well-being Advisor")
|
94 |
st.subheader("Analyze data and provide professional mental health recommendations.")
|
95 |
+
st.write("""
|
|
|
96 |
This app helps identify areas of concern in students' well-being and provides personalized advice based on their responses.
|
97 |
+
""")
|
|
|
98 |
|
|
|
99 |
st.markdown("## π Upload Your Dataset")
|
100 |
uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
|
101 |
if uploaded_file:
|
|
|
104 |
st.write("### Dataset Preview:")
|
105 |
st.dataframe(df.head())
|
106 |
|
|
|
107 |
required_columns = [
|
108 |
+
'anxiety_level', 'self_esteem', 'mental_health_history', 'depression',
|
109 |
+
'headache', 'blood_pressure', 'sleep_quality', 'breathing_problem',
|
110 |
+
'noise_level', 'living_conditions', 'safety', 'basic_needs',
|
111 |
+
'academic_performance', 'study_load', 'teacher_student_relationship',
|
112 |
+
'future_career_concerns', 'social_support', 'peer_pressure',
|
113 |
'extracurricular_activities', 'bullying', 'stress_level'
|
114 |
]
|
115 |
missing_columns = [col for col in required_columns if col not in df.columns]
|
|
|
117 |
if missing_columns:
|
118 |
st.error(f"The uploaded dataset is missing the following required columns: {', '.join(missing_columns)}")
|
119 |
else:
|
|
|
120 |
if df.isnull().values.any():
|
121 |
st.warning("The dataset contains missing values. Rows with missing values will be skipped.")
|
122 |
df = df.dropna()
|
123 |
|
|
|
124 |
tab1, tab2, tab3 = st.tabs(["π Home", "π Analysis", "π° Resources"])
|
125 |
|
126 |
with tab1:
|
127 |
st.write("### Welcome to the Well-being Advisor!")
|
128 |
+
st.write("""
|
|
|
129 |
Use the tabs to explore data, generate advice, and access mental health resources.
|
130 |
+
""")
|
|
|
131 |
|
132 |
with tab2:
|
133 |
st.markdown("### π Select a Row for Analysis")
|
|
|
136 |
options=df.index,
|
137 |
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']})",
|
138 |
)
|
|
|
|
|
139 |
row_data = df.loc[selected_row].to_dict()
|
|
|
|
|
140 |
st.write("### Selected User Details:")
|
141 |
st.json(row_data)
|
142 |
|
|
|
143 |
st.subheader("π Health Advice Based on Articles")
|
144 |
advice = provide_advice_from_articles(row_data)
|
145 |
if advice:
|
|
|
148 |
else:
|
149 |
st.warning("No specific advice available based on this user's data.")
|
150 |
|
151 |
+
# Include graphs in analysis tab
|
152 |
+
plot_graphs(df)
|
153 |
+
|
154 |
with tab3:
|
|
|
155 |
st.subheader("π° Mental Health Resources")
|
156 |
articles = fetch_health_articles("mental health")
|
157 |
if articles:
|