saherPervaiz commited on
Commit
8e315dc
Β·
verified Β·
1 Parent(s): da031f4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -0
app.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
9
+
10
+ @st.cache_data
11
+ def load_data(file):
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
+ # Correlation heatmap
54
+ st.markdown("#### Correlation Heatmap")
55
+ fig, ax = plt.subplots(figsize=(10, 8))
56
+ sns.heatmap(data.corr(), annot=True, cmap="coolwarm", ax=ax)
57
+ ax.set_title("Correlation Heatmap")
58
+ st.pyplot(fig)
59
+
60
+ def main():
61
+ st.set_page_config(
62
+ page_title="Student Well-being Advisor",
63
+ page_icon="πŸ“Š",
64
+ layout="wide",
65
+ initial_sidebar_state="expanded",
66
+ )
67
+
68
+ st.sidebar.title("Navigation")
69
+ st.sidebar.write("Use the sidebar to navigate through the app.")
70
+ st.sidebar.markdown("### πŸ“‚ Upload Data")
71
+ st.sidebar.write("Start by uploading your dataset for analysis.")
72
+ st.sidebar.markdown("### πŸ“Š Analysis & Advice")
73
+ st.sidebar.write("Get detailed insights and personalized advice.")
74
+
75
+ st.title("πŸŽ“ Student Well-being Advisor")
76
+ st.subheader("Analyze data and provide professional mental health recommendations.")
77
+ st.write("""
78
+ This app helps identify areas of concern in students' well-being and provides personalized advice based on their responses.
79
+ """)
80
+
81
+ st.markdown("## πŸ“‚ Upload Your Dataset")
82
+ uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
83
+ if uploaded_file:
84
+ df = load_data(uploaded_file)
85
+ st.success("Dataset uploaded successfully!")
86
+ st.write("### Dataset Preview:")
87
+ st.dataframe(df.head())
88
+
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]
98
+
99
+ if missing_columns:
100
+ st.error(f"The uploaded dataset is missing the following required columns: {', '.join(missing_columns)}")
101
+ else:
102
+ if df.isnull().values.any():
103
+ st.warning("The dataset contains missing values. Rows with missing values will be skipped.")
104
+ df = df.dropna()
105
+
106
+ tab1, tab2, tab3 = st.tabs(["🏠 Home", "πŸ“Š Analysis", "πŸ“° Resources"])
107
+
108
+ with tab1:
109
+ st.write("### Welcome to the Well-being Advisor!")
110
+ st.write("""
111
+ Use the tabs to explore data, generate advice, and access mental health resources.
112
+ """)
113
+
114
+ with tab2:
115
+ st.markdown("### πŸ“Š Select a Row for Analysis")
116
+ selected_row = st.selectbox(
117
+ "Select a row (based on index) to analyze:",
118
+ options=df.index,
119
+ 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']})",
120
+ )
121
+ row_data = df.loc[selected_row].to_dict()
122
+ st.write("### Selected User Details:")
123
+ st.json(row_data)
124
+
125
+ st.subheader("πŸ”” Health Advice Based on Articles")
126
+ advice = provide_advice_from_articles(row_data)
127
+ if advice:
128
+ for i, tip in enumerate(advice, 1):
129
+ st.write(f"πŸ“Œ **{i}.** {tip}")
130
+ else:
131
+ st.warning("No specific advice available based on this user's data.")
132
+
133
+ # Include graphs in analysis tab
134
+ plot_graphs(df)
135
+
136
+ with tab3:
137
+ st.subheader("πŸ“° Mental Health Resources")
138
+ articles = fetch_health_articles("mental health")
139
+ if articles:
140
+ for article in articles:
141
+ st.write(f"**{article['title']}**")
142
+ st.write(f"{article['description']}")
143
+ st.write(f"[Read more]({article['url']})")
144
+ else:
145
+ st.write("No articles available at the moment.")
146
+
147
+ if __name__ == "__main__":
148
+ main()