Health_advisor / app.py
saherPervaiz's picture
Update app.py
f0f32c2 verified
raw
history blame
8.61 kB
import os
import streamlit as st
import pandas as pd
import requests
# API Key for fetching mental health articles
news_api_key = "fe1e6bcbbf384b3e9220a7a1138805e0" # Replace with your News API key
@st.cache_data
def load_data(file):
return pd.read_csv(file)
def provide_observed_advice(data):
"""Generate detailed advice based on the user's data."""
advice = []
# Mental Health Advice
if data['depression'] > 7 or data['anxiety_level'] > 7:
advice.append(
"You are experiencing high levels of depression or anxiety. It’s critical to prioritize your mental health. "
"Please consider scheduling an appointment with a mental health professional. Additionally, practice mindfulness or meditation daily, "
"engage in hobbies you enjoy, and spend time in nature to help reduce negative emotions."
)
elif data['depression'] > 5 or data['anxiety_level'] > 5:
advice.append(
"You are showing moderate signs of depression or anxiety. Try incorporating regular physical activity into your routine, "
"such as walking, yoga, or light exercise. Build a support system by reaching out to trusted friends or family members. "
"Consider journaling your thoughts or keeping a gratitude diary to refocus your mind on positive aspects of your life."
)
if data['stress_level'] > 7:
advice.append(
"High stress levels detected. Stress can negatively affect your physical and mental health. To manage stress effectively, "
"practice relaxation techniques such as deep breathing, progressive muscle relaxation, or guided imagery. "
"Identify your stressors and try to address them one by one. Seek professional counseling if stress becomes overwhelming."
)
if data['mental_health_history'] > 5:
advice.append(
"Your mental health history indicates potential ongoing challenges. Consistent therapy or counseling might provide the support you need. "
"Stay proactive in tracking your mood changes and avoid isolating yourself when you're feeling low."
)
# Physical Health Advice
if data['headache'] > 5:
advice.append(
"Frequent headaches reported. Ensure you’re staying hydrated and maintaining a balanced diet. Avoid prolonged screen time "
"and practice proper posture to reduce physical strain. If headaches persist, consult a doctor to rule out underlying conditions."
)
if data['blood_pressure'] > 5:
advice.append(
"Elevated blood pressure detected. Reduce your salt intake and focus on a heart-healthy diet rich in fruits, vegetables, and lean proteins. "
"Engage in light exercises like walking or swimming, and monitor your blood pressure regularly. Consult a doctor for long-term management strategies."
)
if data['sleep_quality'] < 5:
advice.append(
"Poor sleep quality reported. Establish a consistent bedtime routine, avoid caffeine and heavy meals before sleeping, and create a dark, quiet sleeping environment. "
"Try relaxation techniques like reading or listening to soothing music before bed. Seek medical advice if sleep problems persist."
)
if data['breathing_problem'] > 5:
advice.append(
"Breathing problems reported. If this is linked to allergies or asthma, ensure you’re avoiding triggers and using prescribed medications. "
"Practice deep breathing exercises or try yoga to improve lung function. Consider consulting a pulmonologist for further evaluation."
)
# Environmental and Social Advice
if data['noise_level'] > 7:
advice.append(
"High noise levels detected in your environment. Use noise-canceling headphones or soundproofing techniques to create a quieter space. "
"Spend some time in peaceful locations, such as parks or libraries, to recharge mentally."
)
if data['living_conditions'] < 5 or data['safety'] < 5:
advice.append(
"Suboptimal living conditions or low safety levels detected. Seek resources or community support to improve your living environment. "
"Consider reaching out to local authorities or organizations for assistance in addressing safety concerns."
)
# Academic and Social Support Advice
if data['study_load'] > 7:
advice.append(
"High academic workload reported. Create a detailed study plan to prioritize tasks and allocate sufficient time for breaks. "
"Avoid multitasking and focus on one task at a time to improve efficiency. Consider seeking help from teachers or peers if you feel overwhelmed."
)
if data['future_career_concerns'] > 7:
advice.append(
"High concerns about future career prospects detected. Break down your career goals into smaller, actionable steps. "
"Research potential career paths, network with professionals, and consider attending career counseling for guidance."
)
if data['social_support'] < 5:
advice.append(
"Low social support detected. Building meaningful connections can significantly improve your well-being. "
"Join social groups, clubs, or community activities that align with your interests. Don’t hesitate to reach out to friends or family for emotional support."
)
if data['peer_pressure'] > 7:
advice.append(
"High peer pressure detected. Stay true to your values and goals. Politely decline requests that make you uncomfortable, "
"and remember that it's okay to say no. Surround yourself with individuals who respect your boundaries."
)
if data['extracurricular_activities'] < 5:
advice.append(
"Low engagement in extracurricular activities detected. Participating in activities such as sports, arts, or volunteering can help you develop new skills, "
"reduce stress, and expand your social circle. Consider trying out an activity that interests you."
)
return advice
def main():
st.set_page_config(page_title="Student Well-being Advisor", layout="wide")
st.title("🔍 Analyze Your Well-being")
# File uploader
uploaded_file = st.file_uploader("Upload your dataset (CSV)", type=["csv"])
if uploaded_file:
df = load_data(uploaded_file)
st.write("### Dataset Preview:")
st.dataframe(df.head())
# Validate dataset columns
required_columns = [
'anxiety_level', 'self_esteem', 'mental_health_history', 'depression',
'headache', 'blood_pressure', 'sleep_quality', 'breathing_problem',
'noise_level', 'living_conditions', 'safety', 'basic_needs',
'academic_performance', 'study_load', 'teacher_student_relationship',
'future_career_concerns', 'social_support', 'peer_pressure',
'extracurricular_activities', 'bullying', 'stress_level'
]
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
st.error(f"The uploaded dataset is missing the following required columns: {', '.join(missing_columns)}")
else:
# Handle missing values in the dataset
if df.isnull().values.any():
st.warning("The dataset contains missing values. Rows with missing values will be skipped.")
df = df.dropna()
st.markdown("### Select a Row for Analysis")
selected_row = st.selectbox(
"Select a row (based on index) to analyze:",
options=df.index,
format_func=lambda x: f"Row {x} - Depression: {df.loc[x, 'depression']}, Anxiety: {df.loc[x, 'anxiety_level']}, Stress: {df.loc[x, 'stress_level']}",
)
# Extract data for the selected row
row_data = df.loc[selected_row].to_dict()
# Show extracted details
st.write("### Selected User Details:")
st.json(row_data)
# Generate advice
st.subheader("🔔 Personalized Advice")
advice = provide_observed_advice(row_data)
if advice:
for i, tip in enumerate(advice, 1):
st.write(f"📌 **{i}.** {tip}")
else:
st.warning("No specific advice available based on this user's data.")
if __name__ == "__main__":
main()