Spaces:
Sleeping
Sleeping
import os | |
import logging | |
import pandas as pd | |
import streamlit as st | |
import requests | |
from dotenv import load_dotenv | |
from groq import Groq | |
# Set up logging | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
# Load environment variables from .env file | |
load_dotenv() | |
# Get the Groq API key from environment variables | |
groq_api_key = os.getenv("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") | |
if not groq_api_key: | |
raise ValueError("GROQ_API_KEY is not set. Please provide a valid API key.") | |
# Initialize Groq client | |
try: | |
groq_client = Groq(api_key=groq_api_key) | |
logger.info("Groq client initialized successfully.") | |
except Exception as e: | |
logger.error(f"Error initializing Groq client: {e}") | |
raise # Exit the program if client initialization fails | |
# Function to load and preprocess data | |
def load_data(file): | |
try: | |
df = pd.read_csv(file) | |
return df | |
except Exception as e: | |
logger.error(f"Error loading CSV file: {e}") | |
st.error("There was an issue loading the file. Please try again.") | |
return pd.DataFrame() # Return an empty DataFrame in case of error | |
# Function to provide detailed health advice based on user data | |
def provide_observed_advice(data): | |
advice = [] | |
# High depression and anxiety with low stress-relief activities | |
if data['depression'] > 7 and data['anxiety'] > 7: | |
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.") | |
# Moderate depression or anxiety | |
elif data['depression'] > 5 or data['anxiety'] > 5: | |
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.") | |
# High isolation and low stress-relief activities | |
if data['isolation'] > 7 and data['stress_relief_activities'] < 5: | |
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.") | |
# High future insecurity | |
if data['future_insecurity'] > 7: | |
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.") | |
# Overall low engagement in stress-relief activities | |
if data['stress_relief_activities'] < 5: | |
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.") | |
return advice | |
# Function to fetch health articles from the GROC API based on the query | |
def get_health_articles(query): | |
url = f"https://api.groc.com/search?q={query}" | |
headers = {"Authorization": f"Bearer {groq_api_key}"} # Use the demo API key in the header | |
try: | |
response = requests.get(url, headers=headers) | |
response.raise_for_status() # This will raise an HTTPError for bad responses | |
data = response.json() # Assuming the API returns JSON | |
if 'results' in data: | |
articles = [{"title": item["title"], "url": item["url"]} for item in data['results']] | |
else: | |
articles = [] | |
return articles | |
except requests.exceptions.HTTPError as http_err: | |
logger.error(f"HTTP error occurred: {http_err}") | |
st.error(f"HTTP error occurred: {http_err}. Please check your API key and the endpoint.") | |
return [] | |
except requests.exceptions.RequestException as err: | |
logger.error(f"Error fetching articles: {err}") | |
st.error(f"Error fetching articles: {err}. Please check your internet connection.") | |
return [] | |
# Streamlit app layout | |
def main(): | |
# Set a background color and style | |
st.markdown( | |
""" | |
<style> | |
.stApp { | |
background-color: #F4F4F9; | |
} | |
.stButton>button { | |
background-color: #6200EE; | |
color: white; | |
font-size: 18px; | |
} | |
.stSlider>div>div>span { | |
color: #6200EE; | |
} | |
.stTextInput>div>div>input { | |
background-color: #E0E0E0; | |
} | |
</style> | |
""", | |
unsafe_allow_html=True | |
) | |
# Title and header | |
st.title("π **Student Health Advisory Assistant** π") | |
st.markdown("### **Analyze your well-being and get personalized advice**") | |
# File upload | |
uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"]) | |
if uploaded_file: | |
df = load_data(uploaded_file) | |
if df.empty: | |
return | |
st.write("### Dataset Preview:") | |
st.dataframe(df.head()) | |
# User input for analysis | |
st.markdown("### **Input Your Details**") | |
gender = st.selectbox("πΉ Gender", ["Male", "Female"], help="Select your gender.") | |
age = st.slider("πΉ Age", 18, 35, step=1) | |
depression = st.slider("πΉ Depression Level (1-10)", 1, 10) | |
anxiety = st.slider("πΉ Anxiety Level (1-10)", 1, 10) | |
isolation = st.slider("πΉ Isolation Level (1-10)", 1, 10) | |
future_insecurity = st.slider("πΉ Future Insecurity Level (1-10)", 1, 10) | |
stress_relief_activities = st.slider("πΉ Stress Relief Activities Level (1-10)", 1, 10) | |
# Data dictionary for advice | |
user_data = { | |
"gender": gender, | |
"age": age, | |
"depression": depression, | |
"anxiety": anxiety, | |
"isolation": isolation, | |
"future_insecurity": future_insecurity, | |
"stress_relief_activities": stress_relief_activities, | |
} | |
# Provide advice based on user inputs | |
if st.button("π Get Observed Advice", key="advice_btn"): | |
st.subheader("π **Health Advice Based on Observations** π") | |
advice = provide_observed_advice(user_data) | |
if advice: | |
for i, tip in enumerate(advice, 1): | |
st.write(f"π {i}. {tip}") | |
else: | |
st.warning("No advice available based on your inputs.") | |
# Fetch related health articles based on user input | |
st.subheader("π° **Related Health Articles** π°") | |
query = "mental health anxiety depression isolation stress relief" | |
articles = get_health_articles(query) | |
if articles: | |
for article in articles: | |
st.write(f"π [{article['title']}]({article['url']})") | |
else: | |
st.write("No articles found. Please check your API key or internet connection.") | |
if __name__ == "__main__": | |
main() | |