saherPervaiz commited on
Commit
8b8745e
Β·
verified Β·
1 Parent(s): a721534

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -0
app.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import requests
5
+ from groq import Groq
6
+
7
+ # Fetch the GROQ API key from the environment variable
8
+ groq_api_key = os.getenv("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")
9
+
10
+ # Check if the API key is available, if not show an error and stop
11
+ if not groq_api_key:
12
+ st.error("GROQ_API_KEY is not set. Please provide a valid API key.")
13
+ st.stop()
14
+
15
+ # Initialize the GROQ client with the fetched API key
16
+ try:
17
+ groq_client = Groq(api_key=groq_api_key)
18
+ except Exception as e:
19
+ st.error(f"Error initializing GROQ client: {e}")
20
+ st.stop()
21
+
22
+ # Function to load and preprocess data
23
+ @st.cache_data
24
+ def load_data(file):
25
+ df = pd.read_csv(file)
26
+ return df
27
+
28
+ # Function to provide detailed health advice based on user data
29
+ def provide_observed_advice(data):
30
+ advice = []
31
+
32
+ # High depression and anxiety with low stress-relief activities
33
+ if data['depression'] > 7 and data['anxiety'] > 7:
34
+ 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.")
35
+
36
+ # Moderate depression or anxiety
37
+ elif data['depression'] > 5 or data['anxiety'] > 5:
38
+ 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.")
39
+
40
+ # High isolation and low stress-relief activities
41
+ if data['isolation'] > 7 and data['stress_relief_activities'] < 5:
42
+ 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.")
43
+
44
+ # High future insecurity
45
+ if data['future_insecurity'] > 7:
46
+ 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.")
47
+
48
+ # Overall low engagement in stress-relief activities
49
+ if data['stress_relief_activities'] < 5:
50
+ 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.")
51
+
52
+ return advice
53
+
54
+ # Function to fetch health articles from the GROC API based on the query
55
+ def get_health_articles(query):
56
+ url = f"https://api.groc.com/search?q={query}"
57
+ headers = {"Authorization": f"Bearer {groq_api_key}"} # Use the demo API key in the header
58
+
59
+ try:
60
+ response = requests.get(url, headers=headers)
61
+ response.raise_for_status() # This will raise an HTTPError for bad responses
62
+ data = response.json() # Assuming the API returns JSON
63
+ if 'results' in data:
64
+ articles = [{"title": item["title"], "url": item["url"]} for item in data['results']]
65
+ else:
66
+ articles = []
67
+ return articles
68
+ except requests.exceptions.HTTPError as http_err:
69
+ st.error(f"HTTP error occurred: {http_err}. Please check your API key and the endpoint.")
70
+ st.error(f"Response content: {response.text}")
71
+ return []
72
+ except requests.exceptions.RequestException as err:
73
+ st.error(f"Error fetching articles: {err}. Please check your internet connection.")
74
+ return []
75
+
76
+ # Streamlit app layout
77
+ def main():
78
+ # Set a background color and style
79
+ st.markdown(
80
+ """
81
+ <style>
82
+ .stApp {
83
+ background-color: #F4F4F9;
84
+ }
85
+ .stButton>button {
86
+ background-color: #6200EE;
87
+ color: white;
88
+ font-size: 18px;
89
+ }
90
+ .stSlider>div>div>span {
91
+ color: #6200EE;
92
+ }
93
+ .stTextInput>div>div>input {
94
+ background-color: #E0E0E0;
95
+ }
96
+ </style>
97
+ """,
98
+ unsafe_allow_html=True
99
+ )
100
+
101
+ # Title and header
102
+ st.title("🌟 **Student Health Advisory Assistant** 🌟")
103
+ st.markdown("### **Analyze your well-being and get personalized advice**")
104
+
105
+ # File upload
106
+ uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
107
+ if uploaded_file:
108
+ df = load_data(uploaded_file)
109
+ st.write("### Dataset Preview:")
110
+ st.dataframe(df.head())
111
+
112
+ # User input for analysis
113
+ st.markdown("### **Input Your Details**")
114
+ gender = st.selectbox("πŸ”Ή Gender", ["Male", "Female"], help="Select your gender.")
115
+ age = st.slider("πŸ”Ή Age", 18, 35, step=1)
116
+ depression = st.slider("πŸ”Ή Depression Level (1-10)", 1, 10)
117
+ anxiety = st.slider("πŸ”Ή Anxiety Level (1-10)", 1, 10)
118
+ isolation = st.slider("πŸ”Ή Isolation Level (1-10)", 1, 10)
119
+ future_insecurity = st.slider("πŸ”Ή Future Insecurity Level (1-10)", 1, 10)
120
+ stress_relief_activities = st.slider("πŸ”Ή Stress Relief Activities Level (1-10)", 1, 10)
121
+
122
+ # Data dictionary for advice
123
+ user_data = {
124
+ "gender": gender,
125
+ "age": age,
126
+ "depression": depression,
127
+ "anxiety": anxiety,
128
+ "isolation": isolation,
129
+ "future_insecurity": future_insecurity,
130
+ "stress_relief_activities": stress_relief_activities,
131
+ }
132
+
133
+ # Provide advice based on user inputs
134
+ if st.button("πŸ” Get Observed Advice", key="advice_btn"):
135
+ st.subheader("πŸ”” **Health Advice Based on Observations** πŸ””")
136
+ advice = provide_observed_advice(user_data)
137
+ if advice:
138
+ for i, tip in enumerate(advice, 1):
139
+ st.write(f"πŸ“Œ {i}. {tip}")
140
+ else:
141
+ st.warning("No advice available based on your inputs.")
142
+
143
+ # Fetch related health articles based on user input
144
+ st.subheader("πŸ“° **Related Health Articles** πŸ“°")
145
+ query = "mental health anxiety depression isolation stress relief"
146
+ articles = get_health_articles(query)
147
+ if articles:
148
+ for article in articles:
149
+ st.write(f"🌐 [{article['title']}]({article['url']})")
150
+ else:
151
+ st.write("No articles found. Please check your API key or internet connection.")
152
+
153
+ if __name__ == "__main__":
154
+ main()