saherPervaiz commited on
Commit
61d5bc4
Β·
verified Β·
1 Parent(s): c110a72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -89
app.py CHANGED
@@ -21,97 +21,81 @@ def load_data(file):
21
  # Function to provide detailed health advice based on user data
22
  def provide_observed_advice(data):
23
  advice = []
24
-
25
- # High depression and anxiety with low stress-relief activities
26
  if data['depression'] > 7 and data['anxiety'] > 7:
27
- advice.append("You seem to be experiencing high levels of both depression and anxiety. It's important to consider professional mental health support. You might also benefit from engaging in calming activities like deep breathing, mindfulness, or yoga.")
28
-
29
- # Moderate depression or anxiety
30
- elif data['depression'] > 5 or data['anxiety'] > 5:
31
- advice.append("You are showing moderate levels of depression or anxiety. It would be helpful to develop healthy coping strategies like maintaining a regular sleep schedule, engaging in physical activity, and reaching out to friends or family for support.")
32
-
33
- # High isolation and low stress-relief activities
34
  if data['isolation'] > 7 and data['stress_relief_activities'] < 5:
35
- advice.append("It seems you are feeling isolated, and your engagement in stress-relief activities is low. It's important to connect with friends or join community groups. Incorporate activities that help alleviate stress, such as walking, journaling, or meditation.")
36
-
37
- # High future insecurity
38
  if data['future_insecurity'] > 7:
39
- advice.append("You are feeling a significant amount of insecurity about the future. It can be helpful to break down your larger goals into smaller, manageable tasks. Seeking career counseling or mentorship could provide valuable guidance and reduce anxiety about the future.")
40
-
41
- # Overall low engagement in stress-relief activities
42
  if data['stress_relief_activities'] < 5:
43
- advice.append("Your engagement in stress-relief activities is quite low. It's essential to engage in activities that reduce stress and promote mental wellness, such as hobbies, physical exercise, and relaxation techniques like deep breathing or yoga.")
44
-
 
45
  return advice
46
 
47
  # Function to fetch health articles from News API based on the query
48
  def get_health_articles(query):
49
  url = f"https://newsapi.org/v2/everything?q={query}&apiKey={news_api_key}"
50
-
51
  try:
52
  response = requests.get(url)
53
- response.raise_for_status() # This will raise an HTTPError for bad responses
54
- data = response.json() # Assuming the API returns JSON
55
- if 'articles' in data:
56
- articles = [{"title": item["title"], "url": item["url"]} for item in data['articles']]
57
- else:
58
- articles = []
59
  return articles
60
- except requests.exceptions.HTTPError as http_err:
61
- st.error(f"HTTP error occurred: {http_err}. Please check your API key and the endpoint.")
62
- st.error(f"Response content: {response.text}")
63
- return []
64
  except requests.exceptions.RequestException as err:
65
  st.error(f"Error fetching articles: {err}. Please check your internet connection.")
66
  return []
67
 
68
  # Streamlit app layout
69
  def main():
70
- # Set a background color and style
71
- st.markdown(
72
- """
73
- <style>
74
- .stApp {
75
- background-color: #F4F4F9;
76
- }
77
- .stButton>button {
78
- background-color: #6200EE;
79
- color: white;
80
- font-size: 18px;
81
- }
82
- .stSlider>div>div>span {
83
- color: #6200EE;
84
- }
85
- .stTextInput>div>div>input {
86
- background-color: #E0E0E0;
87
- }
88
- </style>
89
- """,
90
- unsafe_allow_html=True
91
- )
92
-
93
- # Title and header
94
- st.title("🌟 **Student Health Advisory Assistant** 🌟")
95
- st.markdown("### **Analyze your well-being and get personalized advice**")
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- # File upload
98
- uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
99
- if uploaded_file:
100
- df = load_data(uploaded_file)
101
- st.write("### Dataset Preview:")
102
- st.dataframe(df.head())
103
-
104
- # User input for analysis
105
- st.markdown("### **Input Your Details**")
106
- gender = st.selectbox("πŸ”Ή Gender", ["Male", "Female"], help="Select your gender.")
107
- age = st.slider("πŸ”Ή Age", 18, 35, step=1)
108
- depression = st.slider("πŸ”Ή Depression Level (1-10)", 1, 10)
109
- anxiety = st.slider("πŸ”Ή Anxiety Level (1-10)", 1, 10)
110
- isolation = st.slider("πŸ”Ή Isolation Level (1-10)", 1, 10)
111
- future_insecurity = st.slider("πŸ”Ή Future Insecurity Level (1-10)", 1, 10)
112
- stress_relief_activities = st.slider("πŸ”Ή Stress Relief Activities Level (1-10)", 1, 10)
113
-
114
- # Data dictionary for advice
115
  user_data = {
116
  "gender": gender,
117
  "age": age,
@@ -122,25 +106,20 @@ def main():
122
  "stress_relief_activities": stress_relief_activities,
123
  }
124
 
125
- # Provide advice based on user inputs
126
- if st.button("πŸ” Get Observed Advice", key="advice_btn"):
127
- st.subheader("πŸ”” **Health Advice Based on Observations** πŸ””")
128
  advice = provide_observed_advice(user_data)
129
- if advice:
130
- for i, tip in enumerate(advice, 1):
131
- st.write(f"πŸ“Œ {i}. {tip}")
132
- else:
133
- st.warning("No advice available based on your inputs.")
134
-
135
- # Fetch related health articles based on user input
136
- st.subheader("πŸ“° **Related Health Articles** πŸ“°")
137
- query = "mental health anxiety depression isolation stress relief"
138
  articles = get_health_articles(query)
139
- if articles:
140
- for article in articles:
141
- st.write(f"🌐 [{article['title']}]({article['url']})")
142
- else:
143
- st.write("No articles found. Please check your API key or internet connection.")
144
 
145
  if __name__ == "__main__":
146
  main()
 
21
  # Function to provide detailed health advice based on user data
22
  def provide_observed_advice(data):
23
  advice = []
 
 
24
  if data['depression'] > 7 and data['anxiety'] > 7:
25
+ advice.append(
26
+ "You seem to be experiencing high levels of both depression and anxiety. Consider professional mental health support and calming activities like deep breathing, mindfulness, or yoga."
27
+ )
28
+ if data['depression'] > 5 or data['anxiety'] > 5:
29
+ advice.append(
30
+ "Moderate levels of depression or anxiety detected. Maintain a regular sleep schedule, engage in physical activity, and reach out for support."
31
+ )
32
  if data['isolation'] > 7 and data['stress_relief_activities'] < 5:
33
+ advice.append(
34
+ "Feeling isolated with low stress-relief activities. Connect with friends or community groups and try journaling or meditation."
35
+ )
36
  if data['future_insecurity'] > 7:
37
+ advice.append(
38
+ "Significant insecurity about the future detected. Break down goals into smaller tasks, and consider career counseling or mentorship."
39
+ )
40
  if data['stress_relief_activities'] < 5:
41
+ advice.append(
42
+ "Low engagement in stress-relief activities. Try hobbies, physical exercise, or relaxation techniques like yoga."
43
+ )
44
  return advice
45
 
46
  # Function to fetch health articles from News API based on the query
47
  def get_health_articles(query):
48
  url = f"https://newsapi.org/v2/everything?q={query}&apiKey={news_api_key}"
 
49
  try:
50
  response = requests.get(url)
51
+ response.raise_for_status()
52
+ data = response.json()
53
+ articles = [{"title": item["title"], "url": item["url"]} for item in data.get("articles", [])]
 
 
 
54
  return articles
 
 
 
 
55
  except requests.exceptions.RequestException as err:
56
  st.error(f"Error fetching articles: {err}. Please check your internet connection.")
57
  return []
58
 
59
  # Streamlit app layout
60
  def main():
61
+ st.set_page_config(page_title="Student Health Advisory Assistant", layout="wide")
62
+
63
+ # Sidebar for navigation
64
+ with st.sidebar:
65
+ st.header("Navigation")
66
+ option = st.radio("Go to", ["Home", "Analyze Your Well-being", "Health Articles"])
67
+
68
+ # Home page
69
+ if option == "Home":
70
+ st.title("🌟 Welcome to the Student Health Advisory Assistant 🌟")
71
+ st.image("https://via.placeholder.com/800x300?text=Student+Health+Advisory", use_column_width=True)
72
+ st.markdown("### Helping you analyze your well-being and provide personalized advice for a healthier mind.")
73
+ st.markdown(
74
+ """
75
+ - Upload your dataset for in-depth analysis.
76
+ - Input your details to receive personalized advice.
77
+ - Browse the latest health-related articles.
78
+ """
79
+ )
80
+
81
+ # Well-being analysis
82
+ elif option == "Analyze Your Well-being":
83
+ st.title("πŸ” Analyze Your Well-being")
84
+ uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
85
+ if uploaded_file:
86
+ df = load_data(uploaded_file)
87
+ st.write("### Dataset Preview:")
88
+ st.dataframe(df.head())
89
+
90
+ with st.expander("Enter Your Details"):
91
+ gender = st.selectbox("πŸ”Ή Gender", ["Male", "Female"])
92
+ age = st.slider("πŸ”Ή Age", 18, 35, step=1)
93
+ depression = st.slider("πŸ”Ή Depression Level (1-10)", 1, 10)
94
+ anxiety = st.slider("πŸ”Ή Anxiety Level (1-10)", 1, 10)
95
+ isolation = st.slider("πŸ”Ή Isolation Level (1-10)", 1, 10)
96
+ future_insecurity = st.slider("πŸ”Ή Future Insecurity Level (1-10)", 1, 10)
97
+ stress_relief_activities = st.slider("πŸ”Ή Stress Relief Activities Level (1-10)", 1, 10)
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  user_data = {
100
  "gender": gender,
101
  "age": age,
 
106
  "stress_relief_activities": stress_relief_activities,
107
  }
108
 
109
+ if st.button("Get Observed Advice"):
110
+ st.subheader("πŸ”” Health Advice Based on Observations")
 
111
  advice = provide_observed_advice(user_data)
112
+ for i, tip in enumerate(advice, 1):
113
+ st.write(f"πŸ“Œ {i}. {tip}")
114
+
115
+ # Health articles
116
+ elif option == "Health Articles":
117
+ st.title("πŸ“° Browse Health Articles")
118
+ query = st.text_input("Search for health topics (e.g., anxiety, stress relief)")
119
+ if query and st.button("Search Articles"):
 
120
  articles = get_health_articles(query)
121
+ for article in articles:
122
+ st.write(f"🌐 [{article['title']}]({article['url']})")
 
 
 
123
 
124
  if __name__ == "__main__":
125
  main()