saherPervaiz commited on
Commit
a88b37a
Β·
verified Β·
1 Parent(s): c811eb0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -50
app.py CHANGED
@@ -1,53 +1,67 @@
1
- import os
2
- import logging
3
- import pandas as pd
4
  import streamlit as st
 
5
  import requests
6
- from transformers import pipeline
7
-
8
- # Set up logging
9
- logging.basicConfig(level=logging.INFO)
10
- logger = logging.getLogger(__name__)
11
 
12
- # Load environment variables from .env file
13
- load_dotenv()
14
 
15
- # Get the Hugging Face API key from environment variables
16
- hf_api_key = os.getenv("HUGGINGFACE_API_KEY")
17
- if not hf_api_key:
18
- raise ValueError("HUGGINGFACE_API_KEY is not set. Please provide a valid API key.")
19
-
20
- # Hugging Face API URL
21
- hf_api_url = "https://api-inference.huggingface.co/models/{model_name}"
22
 
23
  # Function to load and preprocess data
24
  @st.cache_data
25
  def load_data(file):
26
- try:
27
- df = pd.read_csv(file)
28
- return df
29
- except Exception as e:
30
- logger.error(f"Error loading CSV file: {e}")
31
- st.error("There was an issue loading the file. Please try again.")
32
- return pd.DataFrame() # Return an empty DataFrame in case of error
33
-
34
- # Function to call Hugging Face API for text generation
35
- def generate_text_from_model(model_name, text_input):
36
- headers = {"Authorization": f"Bearer {hf_api_key}"}
37
- data = {"inputs": text_input}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  try:
40
- response = requests.post(hf_api_url.format(model_name=model_name), headers=headers, json=data)
41
- response.raise_for_status()
42
- result = response.json()
43
- if 'generated_text' in result:
44
- return result['generated_text']
45
  else:
46
- return "No result from model. Please try again."
 
 
 
 
 
47
  except requests.exceptions.RequestException as err:
48
- logger.error(f"Error interacting with Hugging Face API: {err}")
49
- st.error(f"Error interacting with Hugging Face API: {err}")
50
- return ""
51
 
52
  # Streamlit app layout
53
  def main():
@@ -75,18 +89,56 @@ def main():
75
  )
76
 
77
  # Title and header
78
- st.title("🌟 **Hugging Face Text Generation** 🌟")
79
- st.markdown("### **Generate text using Hugging Face Models**")
80
-
81
- # User input for text generation
82
- model_name = st.selectbox("πŸ”Ή Select Hugging Face Model", ["gpt2", "distilgpt2", "t5-small"])
83
- text_input = st.text_area("πŸ”Ή Input Text", "Once upon a time...")
84
-
85
- # Generate text based on input
86
- if st.button("πŸ” Generate Text"):
87
- st.subheader("πŸ”” **Generated Text** πŸ””")
88
- generated_text = generate_text_from_model(model_name, text_input)
89
- st.write(f"πŸ“œ {generated_text}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  if __name__ == "__main__":
92
  main()
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
  import requests
4
+ from groq import Groq
 
 
 
 
5
 
6
+ # Set the API key directly or from environment variable
7
+ api_key = "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" # Replace with your actual demo API key
8
 
9
+ # Initialize the Groq client with the API key
10
+ client = Groq(api_key=api_key)
 
 
 
 
 
11
 
12
  # Function to load and preprocess data
13
  @st.cache_data
14
  def load_data(file):
15
+ df = pd.read_csv(file)
16
+ return df
17
+
18
+ # Function to provide detailed health advice based on user data
19
+ def provide_observed_advice(data):
20
+ advice = []
21
+
22
+ # High depression and anxiety with low stress-relief activities
23
+ if data['depression'] > 7 and data['anxiety'] > 7:
24
+ 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.")
25
+
26
+ # Moderate depression or anxiety
27
+ elif data['depression'] > 5 or data['anxiety'] > 5:
28
+ 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.")
29
+
30
+ # High isolation and low stress-relief activities
31
+ if data['isolation'] > 7 and data['stress_relief_activities'] < 5:
32
+ 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.")
33
+
34
+ # High future insecurity
35
+ if data['future_insecurity'] > 7:
36
+ 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.")
37
+
38
+ # Overall low engagement in stress-relief activities
39
+ if data['stress_relief_activities'] < 5:
40
+ 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.")
41
+
42
+ return advice
43
+
44
+ # Function to fetch health articles from the GROC API based on the query
45
+ def get_health_articles(query):
46
+ url = f"https://api.groc.com/search?q={query}"
47
+ headers = {"Authorization": f"Bearer {api_key}"} # Use the demo API key in the header
48
 
49
  try:
50
+ response = requests.get(url, headers=headers)
51
+ response.raise_for_status() # This will raise an HTTPError for bad responses
52
+ data = response.json() # Assuming the API returns JSON
53
+ if 'results' in data:
54
+ articles = [{"title": item["title"], "url": item["url"]} for item in data['results']]
55
  else:
56
+ articles = []
57
+ return articles
58
+ except requests.exceptions.HTTPError as http_err:
59
+ st.error(f"HTTP error occurred: {http_err}. Please check your API key and the endpoint.")
60
+ st.error(f"Response content: {response.text}")
61
+ return []
62
  except requests.exceptions.RequestException as err:
63
+ st.error(f"Error fetching articles: {err}. Please check your internet connection.")
64
+ return []
 
65
 
66
  # Streamlit app layout
67
  def main():
 
89
  )
90
 
91
  # Title and header
92
+ st.title("🌟 **Student Health Advisory Assistant** 🌟")
93
+ st.markdown("### **Analyze your well-being and get personalized advice**")
94
+
95
+ # File upload
96
+ uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
97
+ if uploaded_file:
98
+ df = load_data(uploaded_file)
99
+ st.write("### Dataset Preview:")
100
+ st.dataframe(df.head())
101
+
102
+ # User input for analysis
103
+ st.markdown("### **Input Your Details**")
104
+ gender = st.selectbox("πŸ”Ή Gender", ["Male", "Female"], help="Select your gender.")
105
+ age = st.slider("πŸ”Ή Age", 18, 35, step=1)
106
+ depression = st.slider("πŸ”Ή Depression Level (1-10)", 1, 10)
107
+ anxiety = st.slider("πŸ”Ή Anxiety Level (1-10)", 1, 10)
108
+ isolation = st.slider("πŸ”Ή Isolation Level (1-10)", 1, 10)
109
+ future_insecurity = st.slider("πŸ”Ή Future Insecurity Level (1-10)", 1, 10)
110
+ stress_relief_activities = st.slider("πŸ”Ή Stress Relief Activities Level (1-10)", 1, 10)
111
+
112
+ # Data dictionary for advice
113
+ user_data = {
114
+ "gender": gender,
115
+ "age": age,
116
+ "depression": depression,
117
+ "anxiety": anxiety,
118
+ "isolation": isolation,
119
+ "future_insecurity": future_insecurity,
120
+ "stress_relief_activities": stress_relief_activities,
121
+ }
122
+
123
+ # Provide advice based on user inputs
124
+ if st.button("πŸ” Get Observed Advice", key="advice_btn"):
125
+ st.subheader("πŸ”” **Health Advice Based on Observations** πŸ””")
126
+ advice = provide_observed_advice(user_data)
127
+ if advice:
128
+ for i, tip in enumerate(advice, 1):
129
+ st.write(f"πŸ“Œ {i}. {tip}")
130
+ else:
131
+ st.warning("No advice available based on your inputs.")
132
+
133
+ # Fetch related health articles based on user input
134
+ st.subheader("πŸ“° **Related Health Articles** πŸ“°")
135
+ query = "mental health anxiety depression isolation stress relief"
136
+ articles = get_health_articles(query)
137
+ if articles:
138
+ for article in articles:
139
+ st.write(f"🌐 [{article['title']}]({article['url']})")
140
+ else:
141
+ st.write("No articles found. Please check your API key or internet connection.")
142
 
143
  if __name__ == "__main__":
144
  main()