saherPervaiz commited on
Commit
b873bf2
Β·
verified Β·
1 Parent(s): d69c798

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -110
app.py CHANGED
@@ -1,77 +1,54 @@
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():
@@ -99,56 +76,18 @@ def main():
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()
 
1
  import os
2
+ import logging
3
  import pandas as pd
4
+ import streamlit as st
5
  import requests
6
+ from dotenv import load_dotenv
7
+ from transformers import pipeline
8
+
9
+ # Set up logging
10
+ logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger(__name__)
12
 
13
+ # Load environment variables from .env file
14
+ load_dotenv()
15
 
16
+ # Get the Hugging Face API key from environment variables
17
+ hf_api_key = os.getenv("HUGGINGFACE_API_KEY")
18
+ if not hf_api_key:
19
+ raise ValueError("HUGGINGFACE_API_KEY is not set. Please provide a valid API key.")
20
 
21
+ # Hugging Face API URL
22
+ hf_api_url = "https://api-inference.huggingface.co/models/{model_name}"
 
 
 
 
23
 
24
  # Function to load and preprocess data
25
  @st.cache_data
26
  def load_data(file):
27
+ try:
28
+ df = pd.read_csv(file)
29
+ return df
30
+ except Exception as e:
31
+ logger.error(f"Error loading CSV file: {e}")
32
+ st.error("There was an issue loading the file. Please try again.")
33
+ return pd.DataFrame() # Return an empty DataFrame in case of error
34
+
35
+ # Function to call Hugging Face API for text generation
36
+ def generate_text_from_model(model_name, text_input):
37
+ headers = {"Authorization": f"Bearer {hf_api_key}"}
38
+ data = {"inputs": text_input}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  try:
41
+ response = requests.post(hf_api_url.format(model_name=model_name), headers=headers, json=data)
42
+ response.raise_for_status()
43
+ result = response.json()
44
+ if 'generated_text' in result:
45
+ return result['generated_text']
46
  else:
47
+ return "No result from model. Please try again."
 
 
 
 
 
48
  except requests.exceptions.RequestException as err:
49
+ logger.error(f"Error interacting with Hugging Face API: {err}")
50
+ st.error(f"Error interacting with Hugging Face API: {err}")
51
+ return ""
52
 
53
  # Streamlit app layout
54
  def main():
 
76
  )
77
 
78
  # Title and header
79
+ st.title("🌟 **Hugging Face Text Generation** 🌟")
80
+ st.markdown("### **Generate text using Hugging Face Models**")
81
+
82
+ # User input for text generation
83
+ model_name = st.selectbox("πŸ”Ή Select Hugging Face Model", ["gpt2", "distilgpt2", "t5-small"])
84
+ text_input = st.text_area("πŸ”Ή Input Text", "Once upon a time...")
85
+
86
+ # Generate text based on input
87
+ if st.button("πŸ” Generate Text"):
88
+ st.subheader("πŸ”” **Generated Text** πŸ””")
89
+ generated_text = generate_text_from_model(model_name, text_input)
90
+ st.write(f"πŸ“œ {generated_text}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  if __name__ == "__main__":
93
  main()