import streamlit as st from dotenv import load_dotenv import os import random from datetime import datetime import warnings warnings.filterwarnings("ignore", category=FutureWarning) # ──────────────────────────────────────────────── # xAI SDK import # ──────────────────────────────────────────────── from xai_sdk import Client from xai_sdk.chat import system, user # Load environment variables load_dotenv(encoding="utf-8") XAI_API_KEY = os.getenv("XAI_API_KEY") # Page configuration st.set_page_config( page_title="Mental Health Companion", page_icon="🌱", layout="centered" ) # Custom CSS for better UI st.markdown(""" """, unsafe_allow_html=True) # Initialize session state if "messages" not in st.session_state: st.session_state.messages = [] # Simple default mood (handled by Grok instead of transformers) if "mood" not in st.session_state: st.session_state.mood = "neutral" st.session_state.confidence = 0.5 # Initialize xAI client if XAI_API_KEY: try: client = Client(api_key=XAI_API_KEY) except Exception as e: st.error(f"Error initializing xAI client: {e}") st.stop() else: st.error("⚠️ XAI_API_KEY not found. Please add it to your .env file.") st.stop() # Enhanced relaxation tips with categories relaxation_tips = { "breathing": [ "Box breathing: Inhale for 4 seconds, hold for 4, exhale for 4, hold for 4. Repeat 3-5 times.", "4-7-8 breathing: Breathe in for 4 counts, hold for 7, exhale slowly for 8.", ], "physical": [ "Try progressive muscle relaxation: Tense and relax each muscle group from toes to head.", "Do some gentle stretches or yoga poses for 5-10 minutes.", "Go for a short walk, even if it's just around your room or building.", ], "mindfulness": [ "Practice the 5-4-3-2-1 grounding technique: Name 5 things you see, 4 you can touch, 3 you hear, 2 you smell, 1 you taste.", "Spend 5 minutes on mindful breathing, focusing only on your breath.", "Try a brief guided meditation using a free app or YouTube.", ], "creative": [ "Journal your thoughts: Write freely for 5-10 minutes without editing.", "Listen to calming music or nature sounds.", "Color, draw, or engage in any creative activity you enjoy.", ], "social": [ "Reach out to a friend or family member for a quick chat.", "Join a study group or student organization to connect with peers.", "Consider talking to a counselor at your school's wellness center.", ] } # Crisis keywords detection crisis_keywords = [ "suicide", "kill myself", "end it all", "want to die", "no reason to live", "better off dead", "hurt myself" ] def detect_crisis(text): """Detect potential crisis situations""" text_lower = text.lower() return any(keyword in text_lower for keyword in crisis_keywords) def get_random_tips(num=2): """Get random relaxation tips from different categories""" tips = [] categories = random.sample(list(relaxation_tips.keys()), min(num, len(relaxation_tips))) for category in categories: tips.append(random.choice(relaxation_tips[category])) return tips # Header st.title("🌱 Mental Health Companion") st.markdown("*A supportive space for students navigating stress, anxiety, and life's challenges*") # Sidebar with resources with st.sidebar: st.header("📚 Resources") st.markdown(""" ### Crisis Support (24/7) - 🇮🇳 **Vandrevala Foundation**: 1860-2662-345 - 🇮🇳 **iCall**: 9152987821 - 🌍 **International**: Find local helplines ### Student Wellness Tips - Maintain a regular sleep schedule - Take study breaks every 45-60 minutes - Stay connected with friends and family - Exercise regularly, even if just 15 minutes - Seek help early from campus counseling ### About This Bot This chatbot uses AI to provide emotional support and coping strategies. It's not a replacement for professional mental health care. """) if st.button("🔄 Clear Chat History"): st.session_state.messages = [] st.rerun() # Display chat history for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # User input user_input = st.chat_input("Share what's on your mind...") if user_input: # Check for crisis situation if detect_crisis(user_input): st.markdown("""
I'm concerned about what you've shared. Please reach out to a crisis counselor immediately:
You don't have to face this alone. Professional help is available and things can get better.