import streamlit as st from transformers import AutoModelForSequenceClassification, AutoTokenizer import torch import pandas as pd import numpy as np import plotly.express as px import time # Try to import streamlit_lottie, but provide fallback if it fails try: from streamlit_lottie import st_lottie import requests def load_lottie_url(url: str): try: r = requests.get(url) if r.status_code != 200: return None return r.json() except: return None LOTTIE_AVAILABLE = True except ImportError: LOTTIE_AVAILABLE = False # Page configuration st.set_page_config( page_title="MindBERT - Mental Health Analysis", page_icon="🧠", layout="wide", initial_sidebar_state="expanded" ) # Custom CSS st.markdown(""" """, unsafe_allow_html=True) # Create sidebar with st.sidebar: # Use either Lottie or a simple icon if LOTTIE_AVAILABLE: # Fixed Lottie URLs that are reliable brain_animation = load_lottie_url("https://lottie.host/2eb12c32-787a-46f7-ac20-34c166d1a285/UcEEbJlFVH.json") if brain_animation: st_lottie(brain_animation, height=200, key="brain_animation") else: st.markdown("
🧠
", unsafe_allow_html=True) else: st.markdown("
🧠
", unsafe_allow_html=True) st.markdown("## About MindBERT") st.info( "MindBERT is a fine-tuned BERT model specifically designed to detect " "mental health states from text. It has been trained on a diverse dataset " "of mental health-related content to identify patterns associated with " "various mental health conditions." ) st.markdown("## Disclaimer") st.warning( "This app is for educational and research purposes only. " "It is not a substitute for professional medical advice, " "diagnosis, or treatment. Always seek the advice of a qualified " "health provider for any medical condition." ) st.markdown("## How it works") st.markdown( "1. Enter text in the provided area\n" "2. Click 'Analyze Mental State'\n" "3. The model will process the text and predict the writer's mental state\n" "4. Results are displayed with confidence levels" ) # Main content st.markdown("

MindBERT - Mental Health Analysis

", unsafe_allow_html=True) # Custom tabs tab1, tab2, tab3 = st.tabs(["Mental Health Analyzer", "Understanding Categories", "Resources"]) with tab1: st.markdown("

Enter text to analyze the mental state of the writer.

", unsafe_allow_html=True) # Text input area with placeholder user_input = st.text_area( "Type your message here:", height=150, placeholder="Example: I've been feeling overwhelmed lately with all the pressure at work. I can't seem to focus and I'm constantly worried about deadlines.", ) # Model loading feedback @st.cache_resource def load_model(): try: tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH) return tokenizer, model, True except Exception as e: st.error(f"Error loading model: {str(e)}") return None, None, False # Define model and tokenizer paths from Hugging Face MODEL_PATH = "DrSyedFaizan/mindBERT" with st.spinner("Loading model..."): tokenizer, model, model_loaded = load_model() # Analysis button col1, col2, col3 = st.columns([1, 2, 1]) with col2: analyze_button = st.button("Analyze Mental State") # Prediction logic if analyze_button: if not model_loaded: st.error("Model failed to load. Please try again later.") elif not user_input.strip(): st.warning("Please enter some text for analysis.") else: # Show analyzing animation or spinner with st.spinner("Analyzing..."): if LOTTIE_AVAILABLE: analyzing_animation = load_lottie_url("https://lottie.host/16c400ec-7d59-4c0c-a84b-56c9134cd673/20XZXacKUS.json") if analyzing_animation: st_lottie(analyzing_animation, height=200, key="analyze_animation", speed=1.5) # Add a slight delay to show the animation time.sleep(1) try: # Tokenize input inputs = tokenizer(user_input, return_tensors="pt", truncation=True, padding=True) # Make prediction with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits probabilities = torch.nn.functional.softmax(logits, dim=1)[0] predicted_class = torch.argmax(logits, dim=1).item() # Mapping predicted class to mental state with descriptions label_map = { 0: {"name": "Anxiety", "color": "#FFD54F", "description": "Characterized by excessive worry, fear, or nervousness."}, 1: {"name": "Bipolar", "color": "#FF7043", "description": "Featuring alternating periods of depression and mania or elevated mood."}, 2: {"name": "Depression", "color": "#4FC3F7", "description": "Persistent feelings of sadness, hopelessness, and loss of interest."}, 3: {"name": "Normal", "color": "#81C784", "description": "Balanced emotional state without significant mental health concerns."}, 4: {"name": "Personality Disorder", "color": "#9575CD", "description": "Persistent patterns of thinking and behavior that deviate from social norms."}, 5: {"name": "Stress", "color": "#FF8A65", "description": "Physical or emotional tension due to challenging circumstances."}, 6: {"name": "Suicidal", "color": "#F44336", "description": "Thoughts or intentions of self-harm or taking one's own life."} } mental_state = label_map.get(predicted_class, {"name": "Unknown", "color": "#BDBDBD", "description": "Unable to classify the mental state."}) # Create data for visualization all_probs = {label_map[i]["name"]: prob.item() * 100 for i, prob in enumerate(probabilities)} probs_df = pd.DataFrame(list(all_probs.items()), columns=["Mental State", "Confidence (%)"]) probs_df = probs_df.sort_values("Confidence (%)", ascending=False) # Display results st.markdown("
", unsafe_allow_html=True) # Primary result col1, col2 = st.columns([1, 2]) with col1: st.markdown(f"
{mental_state['name']}
", unsafe_allow_html=True) st.markdown("
Primary Detection
", unsafe_allow_html=True) with col2: st.markdown( f"""
{mental_state['name']}: {mental_state['description']}
""", unsafe_allow_html=True ) # Confidence scores visualization st.markdown("

Confidence Analysis

", unsafe_allow_html=True) # Create bar chart fig = px.bar( probs_df, x="Confidence (%)", y="Mental State", orientation="h", color="Mental State", color_discrete_map={ "Anxiety": "#FFD54F", "Bipolar": "#FF7043", "Depression": "#4FC3F7", "Normal": "#81C784", "Personality Disorder": "#9575CD", "Stress": "#FF8A65", "Suicidal": "#F44336", "Unknown": "#BDBDBD" } ) fig.update_layout( height=350, margin=dict(l=20, r=20, t=30, b=20), xaxis_title="Confidence (%)", yaxis_title="", yaxis=dict(autorange="reversed"), xaxis=dict(range=[0, 100]) ) st.plotly_chart(fig, use_container_width=True) # Warning for high-risk categories if mental_state["name"] in ["Suicidal", "Depression"] and all_probs[mental_state["name"]] > 50: st.warning( "⚠️ **High-risk mental state detected.** If you or someone you know is experiencing " "suicidal thoughts, please seek immediate professional help or call the National " "Suicide Prevention Lifeline at 988 or 1-800-273-8255." ) st.markdown("
", unsafe_allow_html=True) # Suggestion based on detected mental state suggestion_map = { "Anxiety": "Consider breathing exercises, meditation, or consulting with a mental health professional about anxiety management techniques.", "Bipolar": "Regular sleep schedules and medication management with professional oversight can help stabilize mood swings.", "Depression": "Regular physical activity, social connection, and professional therapy can be beneficial for managing depression.", "Normal": "Continue maintaining a healthy lifestyle with regular exercise, good sleep habits, and social connections.", "Personality Disorder": "Long-term psychotherapy with a specialist in personality disorders is often recommended.", "Stress": "Stress reduction techniques such as mindfulness, time management, and setting boundaries can be helpful.", "Suicidal": "Please seek immediate professional help. Call the National Suicide Prevention Lifeline at 988 or 1-800-273-8255." } st.markdown("
", unsafe_allow_html=True) st.markdown("

Suggestions

", unsafe_allow_html=True) st.info(suggestion_map.get(mental_state["name"], "Consider consulting with a mental health professional for personalized guidance.")) st.markdown("
", unsafe_allow_html=True) except Exception as e: st.error(f"Error during analysis: {str(e)}") st.info("Please try again with different text or contact support if the issue persists.") with tab2: st.markdown("

Mental Health Categories Explained

", unsafe_allow_html=True) categories = [ {"name": "Anxiety", "color": "#FFD54F", "description": "Characterized by excessive worry, fear, and nervousness that may interfere with daily activities. May include physical symptoms like restlessness, fatigue, and difficulty concentrating."}, {"name": "Bipolar", "color": "#FF7043", "description": "Features alternating periods of depression and mania. During manic episodes, individuals may experience elevated mood, increased energy, and impulsive behavior. Depressive episodes involve symptoms similar to major depression."}, {"name": "Depression", "color": "#4FC3F7", "description": "Persistent feelings of sadness, hopelessness, and loss of interest in activities once enjoyed. May include changes in sleep, appetite, energy level, concentration, and self-worth."}, {"name": "Normal", "color": "#81C784", "description": "A balanced emotional state characterized by appropriate responses to life events, ability to manage stress effectively, and maintain healthy relationships and activities."}, {"name": "Personality Disorder", "color": "#9575CD", "description": "Long-term patterns of thoughts, feelings, and behaviors that deviate from cultural expectations, causing distress or problems functioning in social, work, or personal relationships."}, {"name": "Stress", "color": "#FF8A65", "description": "The body's response to demands or pressures. While acute stress can be motivating, chronic stress may lead to physical and mental health problems including headaches, sleep disturbances, and mood changes."}, {"name": "Suicidal", "color": "#F44336", "description": "Thoughts about, planning, or intent to end one's life. This is a medical emergency requiring immediate professional intervention."} ] for category in categories: st.markdown( f"
"+ f"

{category['name']}

"+ f"

{category['description']}

"+ "
", unsafe_allow_html=True ) st.markdown( "
Note: These categories are simplified for educational purposes. " "Mental health exists on a spectrum, and professional diagnosis involves comprehensive assessment " "beyond text analysis.
", unsafe_allow_html=True ) with tab3: st.markdown("

Mental Health Resources

", unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: st.markdown( "
"+ "

Crisis Resources

"+ ""+ "
", unsafe_allow_html=True ) with col2: st.markdown( "
"+ "

Online Resources

"+ ""+ "
", unsafe_allow_html=True ) st.markdown( "
"+ "

Self-Help Strategies

"+ ""+ "
", unsafe_allow_html=True ) # Footer st.markdown("", unsafe_allow_html=True)