DrSyedFaizan commited on
Commit
e21d4fd
·
verified ·
1 Parent(s): 77a9d6a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +338 -39
app.py CHANGED
@@ -1,48 +1,347 @@
1
  import streamlit as st
2
  from transformers import AutoModelForSequenceClassification, AutoTokenizer
3
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  # Define model and tokenizer paths from Hugging Face
6
  MODEL_PATH = "DrSyedFaizan/mindBERT"
7
 
8
- # Load tokenizer and model from Hugging Face Hub
9
- tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
10
- model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH)
11
-
12
- # Streamlit UI setup
13
- st.title("MindBERT - Mental Health Analysis Chat")
14
- st.write("Enter a message, and the model will analyze the mental state of the writer.")
15
-
16
- user_input = st.text_area("Type your message here:")
17
-
18
- if st.button("Analyze Mental State"):
19
- if user_input.strip():
20
- # Tokenize input
21
- inputs = tokenizer(user_input, return_tensors="pt", truncation=True, padding=True)
22
-
23
- # Make prediction
24
- with torch.no_grad():
25
- outputs = model(**inputs)
26
- logits = outputs.logits
27
- predicted_class = torch.argmax(logits, dim=1).item()
28
-
29
- # Mapping predicted class to mental state
30
- label_map = {
31
- 0: "Anxiety",
32
- 1: "Bipolar",
33
- 2: "Depression",
34
- 3: "Normal",
35
- 4: "Personality Disorder",
36
- 5: "Stress",
37
- 6: "Suicidal"
38
- }
39
- mental_state = label_map.get(predicted_class, "Unknown")
40
-
41
- # Display results
42
- st.write(f"Predicted Mental State: **{mental_state}**")
43
- else:
44
- st.warning("Please enter some text for analysis.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  # Footer
47
- st.markdown("---")
48
- st.markdown("Developed by Dr. Syed Faizan using MindBERT on Hugging Face.")
 
1
  import streamlit as st
2
  from transformers import AutoModelForSequenceClassification, AutoTokenizer
3
  import torch
4
+ import pandas as pd
5
+ import numpy as np
6
+ import plotly.express as px
7
+ import time
8
+ from streamlit_lottie import st_lottie
9
+ import requests
10
+ import json
11
+
12
+ # Page configuration
13
+ st.set_page_config(
14
+ page_title="MindBERT - Mental Health Analysis",
15
+ page_icon="🧠",
16
+ layout="wide",
17
+ initial_sidebar_state="expanded"
18
+ )
19
+
20
+ # Custom CSS
21
+ st.markdown("""
22
+ <style>
23
+ .main-header {
24
+ font-size: 2.5rem;
25
+ color: #4527A0;
26
+ text-align: center;
27
+ margin-bottom: 1rem;
28
+ }
29
+ .sub-header {
30
+ font-size: 1.5rem;
31
+ color: #5E35B1;
32
+ margin-bottom: 1rem;
33
+ }
34
+ .result-box {
35
+ background-color: #F3F4F6;
36
+ border-radius: 10px;
37
+ padding: 20px;
38
+ margin: 10px 0px;
39
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
40
+ }
41
+ .footer {
42
+ text-align: center;
43
+ margin-top: 3rem;
44
+ padding: 1rem;
45
+ font-size: 0.8rem;
46
+ color: #666;
47
+ border-top: 1px solid #ddd;
48
+ }
49
+ .stTextArea textarea {
50
+ border-radius: 10px;
51
+ border: 1px solid #5E35B1;
52
+ }
53
+ .stButton button {
54
+ border-radius: 20px;
55
+ background-color: #5E35B1;
56
+ color: white;
57
+ font-weight: bold;
58
+ padding: 0.5rem 2rem;
59
+ transition: all 0.3s;
60
+ }
61
+ .stButton button:hover {
62
+ background-color: #4527A0;
63
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
64
+ }
65
+ .category-card {
66
+ padding: 10px;
67
+ border-radius: 5px;
68
+ margin-bottom: 10px;
69
+ }
70
+ .helper-text {
71
+ font-size: 0.9rem;
72
+ color: #666;
73
+ font-style: italic;
74
+ }
75
+ .metric-value {
76
+ font-size: 2.5rem;
77
+ font-weight: bold;
78
+ text-align: center;
79
+ }
80
+ .metric-label {
81
+ font-size: 1rem;
82
+ text-align: center;
83
+ color: #666;
84
+ }
85
+ </style>
86
+ """, unsafe_allow_html=True)
87
+
88
+ # Function to load Lottie animation
89
+ def load_lottie_url(url: str):
90
+ r = requests.get(url)
91
+ if r.status_code != 200:
92
+ return None
93
+ return r.json()
94
+
95
+ # Load animations
96
+ brain_animation = load_lottie_url("https://assets9.lottiefiles.com/packages/lf20_twdne5i2.json")
97
+ analyzing_animation = load_lottie_url("https://assets8.lottiefiles.com/private_files/lf30_p9aibxmu.json")
98
 
99
  # Define model and tokenizer paths from Hugging Face
100
  MODEL_PATH = "DrSyedFaizan/mindBERT"
101
 
102
+ # Create sidebar
103
+ with st.sidebar:
104
+ st_lottie(brain_animation, height=200, key="brain_animation")
105
+ st.markdown("## About MindBERT")
106
+ st.info(
107
+ "MindBERT is a fine-tuned BERT model specifically designed to detect "
108
+ "mental health states from text. It has been trained on a diverse dataset "
109
+ "of mental health-related content to identify patterns associated with "
110
+ "various mental health conditions."
111
+ )
112
+
113
+ st.markdown("## How it works")
114
+ st.markdown(
115
+ "1. Enter text in the provided area\n"
116
+ "2. Click 'Analyze Mental State'\n"
117
+ "3. The model will process the text and predict the writer's mental state\n"
118
+ "4. Results are displayed with confidence levels"
119
+ )
120
+
121
+ st.markdown("## Disclaimer")
122
+ st.warning(
123
+ "This app is for educational and research purposes only. "
124
+ "It is not a substitute for professional medical advice, "
125
+ "diagnosis, or treatment. Always seek the advice of a qualified "
126
+ "health provider for any medical condition."
127
+ )
128
+
129
+ # Main content
130
+ st.markdown("<h1 class='main-header'>MindBERT - Mental Health Analysis</h1>", unsafe_allow_html=True)
131
+
132
+ # Custom tabs
133
+ tab1, tab2, tab3 = st.tabs(["Mental Health Analyzer", "Understanding Categories", "Resources"])
134
+
135
+ with tab1:
136
+ st.markdown("<p class='helper-text'>Enter text to analyze the mental state of the writer.</p>", unsafe_allow_html=True)
137
+
138
+ # Text input area with placeholder
139
+ user_input = st.text_area(
140
+ "Type your message here:",
141
+ height=150,
142
+ 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.",
143
+ )
144
+
145
+ # Model loading feedback
146
+ @st.cache_resource
147
+ def load_model():
148
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
149
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH)
150
+ return tokenizer, model
151
+
152
+ with st.spinner("Loading model..."):
153
+ tokenizer, model = load_model()
154
+
155
+ # Analysis button
156
+ col1, col2, col3 = st.columns([1, 2, 1])
157
+ with col2:
158
+ analyze_button = st.button("Analyze Mental State")
159
+
160
+ # Prediction logic
161
+ if analyze_button:
162
+ if user_input.strip():
163
+ # Show analyzing animation
164
+ with st.spinner("Analyzing..."):
165
+ st_lottie(analyzing_animation, height=200, key="analyze_animation", speed=1.5)
166
+
167
+ # Tokenize input
168
+ inputs = tokenizer(user_input, return_tensors="pt", truncation=True, padding=True)
169
+
170
+ # Make prediction
171
+ with torch.no_grad():
172
+ outputs = model(**inputs)
173
+ logits = outputs.logits
174
+ probabilities = torch.nn.functional.softmax(logits, dim=1)[0]
175
+ predicted_class = torch.argmax(logits, dim=1).item()
176
+
177
+ # Mapping predicted class to mental state with descriptions
178
+ label_map = {
179
+ 0: {"name": "Anxiety", "color": "#FFD54F", "description": "Characterized by excessive worry, fear, or nervousness."},
180
+ 1: {"name": "Bipolar", "color": "#FF7043", "description": "Featuring alternating periods of depression and mania or elevated mood."},
181
+ 2: {"name": "Depression", "color": "#4FC3F7", "description": "Persistent feelings of sadness, hopelessness, and loss of interest."},
182
+ 3: {"name": "Normal", "color": "#81C784", "description": "Balanced emotional state without significant mental health concerns."},
183
+ 4: {"name": "Personality Disorder", "color": "#9575CD", "description": "Persistent patterns of thinking and behavior that deviate from social norms."},
184
+ 5: {"name": "Stress", "color": "#FF8A65", "description": "Physical or emotional tension due to challenging circumstances."},
185
+ 6: {"name": "Suicidal", "color": "#F44336", "description": "Thoughts or intentions of self-harm or taking one's own life."}
186
+ }
187
+
188
+ mental_state = label_map.get(predicted_class, {"name": "Unknown", "color": "#BDBDBD", "description": "Unable to classify the mental state."})
189
+
190
+ # Create data for visualization
191
+ all_probs = {label_map[i]["name"]: prob.item() * 100 for i, prob in enumerate(probabilities)}
192
+ probs_df = pd.DataFrame(list(all_probs.items()), columns=["Mental State", "Confidence (%)"])
193
+ probs_df = probs_df.sort_values("Confidence (%)", ascending=False)
194
+
195
+ # Display results
196
+ st.markdown("<div class='result-box'>", unsafe_allow_html=True)
197
+
198
+ # Primary result
199
+ col1, col2 = st.columns([1, 2])
200
+ with col1:
201
+ st.markdown(f"<div class='metric-value' style='color:{mental_state['color']}'>{mental_state['name']}</div>", unsafe_allow_html=True)
202
+ st.markdown("<div class='metric-label'>Primary Detection</div>", unsafe_allow_html=True)
203
+
204
+ with col2:
205
+ st.markdown(f"<div style='background-color:{mental_state['color']}20; padding:15px; border-radius:10px; border-left:5px solid {mental_state['color']}'>")
206
+ st.markdown(f"<b>{mental_state['name']}</b>: {mental_state['description']}")
207
+ st.markdown("</div>", unsafe_allow_html=True)
208
+
209
+ # Confidence scores visualization
210
+ st.markdown("<h3 class='sub-header'>Confidence Analysis</h3>", unsafe_allow_html=True)
211
+
212
+ # Create bar chart
213
+ fig = px.bar(
214
+ probs_df,
215
+ x="Confidence (%)",
216
+ y="Mental State",
217
+ orientation="h",
218
+ color="Mental State",
219
+ color_discrete_map={
220
+ "Anxiety": "#FFD54F",
221
+ "Bipolar": "#FF7043",
222
+ "Depression": "#4FC3F7",
223
+ "Normal": "#81C784",
224
+ "Personality Disorder": "#9575CD",
225
+ "Stress": "#FF8A65",
226
+ "Suicidal": "#F44336",
227
+ "Unknown": "#BDBDBD"
228
+ }
229
+ )
230
+ fig.update_layout(
231
+ height=350,
232
+ margin=dict(l=20, r=20, t=30, b=20),
233
+ xaxis_title="Confidence (%)",
234
+ yaxis_title="",
235
+ yaxis=dict(autorange="reversed"),
236
+ xaxis=dict(range=[0, 100])
237
+ )
238
+ st.plotly_chart(fig, use_container_width=True)
239
+
240
+ # Warning for high-risk categories
241
+ if mental_state["name"] in ["Suicidal", "Depression"] and all_probs[mental_state["name"]] > 50:
242
+ st.warning(
243
+ "⚠️ **High-risk mental state detected.** If you or someone you know is experiencing "
244
+ "suicidal thoughts, please seek immediate professional help or call the National "
245
+ "Suicide Prevention Lifeline at 988 or 1-800-273-8255."
246
+ )
247
+
248
+ st.markdown("</div>", unsafe_allow_html=True)
249
+
250
+ # Suggestion based on detected mental state
251
+ suggestion_map = {
252
+ "Anxiety": "Consider breathing exercises, meditation, or consulting with a mental health professional about anxiety management techniques.",
253
+ "Bipolar": "Regular sleep schedules and medication management with professional oversight can help stabilize mood swings.",
254
+ "Depression": "Regular physical activity, social connection, and professional therapy can be beneficial for managing depression.",
255
+ "Normal": "Continue maintaining a healthy lifestyle with regular exercise, good sleep habits, and social connections.",
256
+ "Personality Disorder": "Long-term psychotherapy with a specialist in personality disorders is often recommended.",
257
+ "Stress": "Stress reduction techniques such as mindfulness, time management, and setting boundaries can be helpful.",
258
+ "Suicidal": "Please seek immediate professional help. Call the National Suicide Prevention Lifeline at 988 or 1-800-273-8255."
259
+ }
260
+
261
+ st.markdown("<div class='result-box'>", unsafe_allow_html=True)
262
+ st.markdown("<h3 class='sub-header'>Suggestions</h3>", unsafe_allow_html=True)
263
+ st.info(suggestion_map.get(mental_state["name"], "Consider consulting with a mental health professional for personalized guidance."))
264
+ st.markdown("</div>", unsafe_allow_html=True)
265
+
266
+ else:
267
+ st.warning("Please enter some text for analysis.")
268
+
269
+ with tab2:
270
+ st.markdown("<h3 class='sub-header'>Mental Health Categories Explained</h3>", unsafe_allow_html=True)
271
+
272
+ categories = [
273
+ {"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."},
274
+ {"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."},
275
+ {"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."},
276
+ {"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."},
277
+ {"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."},
278
+ {"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."},
279
+ {"name": "Suicidal", "color": "#F44336", "description": "Thoughts about, planning, or intent to end one's life. This is a medical emergency requiring immediate professional intervention."}
280
+ ]
281
+
282
+ for category in categories:
283
+ st.markdown(
284
+ f"<div class='category-card' style='background-color:{category['color']}20; border-left:5px solid {category['color']}'>"+
285
+ f"<h4 style='color:{category['color']}DD'>{category['name']}</h4>"+
286
+ f"<p>{category['description']}</p>"+
287
+ "</div>",
288
+ unsafe_allow_html=True
289
+ )
290
+
291
+ st.markdown(
292
+ "<div class='helper-text'><b>Note:</b> These categories are simplified for educational purposes. "
293
+ "Mental health exists on a spectrum, and professional diagnosis involves comprehensive assessment "
294
+ "beyond text analysis.</div>",
295
+ unsafe_allow_html=True
296
+ )
297
+
298
+ with tab3:
299
+ st.markdown("<h3 class='sub-header'>Mental Health Resources</h3>", unsafe_allow_html=True)
300
+
301
+ col1, col2 = st.columns(2)
302
+
303
+ with col1:
304
+ st.markdown(
305
+ "<div class='result-box'>"+
306
+ "<h4>Crisis Resources</h4>"+
307
+ "<ul>"+
308
+ "<li><b>National Suicide Prevention Lifeline:</b> 988 or 1-800-273-8255</li>"+
309
+ "<li><b>Crisis Text Line:</b> Text HOME to 741741</li>"+
310
+ "<li><b>Veterans Crisis Line:</b> 1-800-273-8255 (Press 1)</li>"+
311
+ "<li><b>Disaster Distress Helpline:</b> 1-800-985-5990</li>"+
312
+ "</ul>"+
313
+ "</div>",
314
+ unsafe_allow_html=True
315
+ )
316
+
317
+ with col2:
318
+ st.markdown(
319
+ "<div class='result-box'>"+
320
+ "<h4>Online Resources</h4>"+
321
+ "<ul>"+
322
+ "<li><b>National Alliance on Mental Illness (NAMI):</b> nami.org</li>"+
323
+ "<li><b>Mental Health America:</b> mhanational.org</li>"+
324
+ "<li><b>Psychology Today Therapist Finder:</b> psychologytoday.com/us/therapists</li>"+
325
+ "<li><b>Substance Abuse and Mental Health Services Administration:</b> samhsa.gov</li>"+
326
+ "</ul>"+
327
+ "</div>",
328
+ unsafe_allow_html=True
329
+ )
330
+
331
+ st.markdown(
332
+ "<div class='result-box'>"+
333
+ "<h4>Self-Help Strategies</h4>"+
334
+ "<ul>"+
335
+ "<li><b>Mindfulness and Meditation:</b> Apps like Headspace, Calm, or Insight Timer</li>"+
336
+ "<li><b>Physical Activity:</b> Regular exercise can help reduce symptoms of depression and anxiety</li>"+
337
+ "<li><b>Sleep Hygiene:</b> Maintaining regular sleep patterns supports mental health</li>"+
338
+ "<li><b>Social Connection:</b> Staying connected with supportive people in your life</li>"+
339
+ "<li><b>Limiting Alcohol and Substances:</b> These can worsen mental health symptoms</li>"+
340
+ "<li><b>Setting Boundaries:</b> Learning to say no and protecting your mental space</li>"+
341
+ "</ul>"+
342
+ "</div>",
343
+ unsafe_allow_html=True
344
+ )
345
 
346
  # Footer
347
+ st.markdown("<div class='footer'>Developed by Dr. Syed Faizan using MindBERT on Hugging Face. This application is for educational and research purposes only.</div>", unsafe_allow_html=True)