avtak commited on
Commit
62cc3b5
Β·
verified Β·
1 Parent(s): b79a240

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -136
app.py CHANGED
@@ -1,101 +1,123 @@
1
  import gradio as gr
2
- import torch
3
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
  import os
5
 
6
- # Load model and tokenizer
7
- MODEL_NAME = "mental/mental-longformer-depression"
8
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
9
- model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
10
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
- model.to(device)
12
- model.eval()
13
-
14
- def predict_depression(text):
15
- """Predict depression risk from user text"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- # Check text length
18
- word_count = len(text.split())
 
 
 
 
19
 
20
- if word_count < 88:
21
- warning = f"⚠️ Warning: Text Too Short ({word_count} words)"
22
- message = (
23
- "This model requires extensive text (300+ words recommended) for accurate analysis. "
24
- "Short inputs will produce unreliable results.\n\n"
25
- "Please provide:\n"
26
- "β€’ Multiple social media posts (10-15 posts)\n"
27
- "β€’ Extended writing samples\n"
28
- "β€’ Long-form personal narratives\n\n"
29
- "Use the examples below to see proper input format."
30
- )
31
- return warning, message, ""
 
 
32
 
33
- # Tokenize and predict
34
- inputs = tokenizer(
35
- text,
36
- return_tensors="pt",
37
- truncation=True,
38
- max_length=4096,
39
- padding=True
40
- ).to(device)
41
 
42
- with torch.no_grad():
43
- outputs = model(**inputs)
44
- probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
45
- depression_prob = probs[0][1].item() * 100
46
 
47
- # Determine risk level
48
- if depression_prob >= 60:
49
- risk_level = "πŸ”΄ Depression Risk Assessment: High Risk"
50
- risk_color = "#ff4444"
51
- interpretation = (
52
- "Strong linguistic patterns associated with depression detected. "
53
- "Multiple markers of depressive language present."
54
- )
55
- recommendation = (
56
- "Strongly recommend speaking with a mental health professional. "
57
- "Immediate support resources provided below."
58
- )
59
- elif depression_prob >= 30:
60
- risk_level = "🟑 Depression Risk Assessment: Moderate Risk"
61
- risk_color = "#ffaa00"
62
- interpretation = (
63
- "Some concerning patterns detected. Monitoring recommended."
64
- )
65
- recommendation = (
66
- "Consider reaching out to a mental health professional for guidance. "
67
- "Early intervention can be helpful."
68
- )
69
- else:
70
- risk_level = "🟒 Depression Risk Assessment: Low Risk"
71
- risk_color = "#44ff44"
72
- interpretation = (
73
- "Typical language patterns, no significant depression markers detected."
74
- )
75
- recommendation = (
76
- "Continue maintaining mental wellness. If concerns arise, "
77
- "don't hesitate to seek professional support."
78
- )
79
-
80
- # Format output
81
- output = f"""
82
- {risk_level}
83
- Depression Probability: {depression_prob:.1f}%
84
- Text Length: {word_count} words
85
 
86
  ## Risk Interpretation
87
 
88
- {interpretation}
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- ## Recommended Action
 
 
 
 
 
 
 
91
 
92
- {recommendation}
 
 
 
 
 
 
 
 
93
  """
94
-
95
- return risk_level, output, f"Depression Probability: {depression_prob:.1f}%"
96
 
97
- # Example texts (no post numbers or separators)
98
- LOW_RISK_EXAMPLE = """I'm thinking of expanding my garden to include some tomatoes next. I've been watching a bunch of videos on how to build a small planter box. Feeling excited about the new project.
99
 
100
  It's been a good week. Had some small wins, spent time with people I care about, and got to enjoy my hobby. Feeling content and looking forward to what next week brings.
101
 
@@ -107,7 +129,7 @@ Finally tried that new recipe I've been meaning to make. It turned out better th
107
 
108
  Work has been busy but manageable. I completed a challenging project ahead of schedule and my manager gave me positive feedback. Feeling accomplished and motivated."""
109
 
110
- MODERATE_RISK_EXAMPLE = """Been feeling a bit off lately. Not sure what it is, but I just don't have the same energy I used to have. Maybe I'm just tired from work.
111
 
112
  My sleep schedule has been all over the place. Some nights I can't fall asleep, other nights I sleep too much. Either way, I wake up feeling drained.
113
 
@@ -119,7 +141,7 @@ I've been spending a lot of time scrolling through my phone. I know it's not pro
119
 
120
  Haven't been eating as healthy as I should. Skipping meals or just grabbing whatever is convenient. Cooking feels like too much effort right now."""
121
 
122
- HIGH_RISK_EXAMPLE = """I woke up feeling exhausted even after sleeping for 10 hours. The thought of getting out of bed feels overwhelming. I don't even know why I bother anymore.
123
 
124
  My apartment is a mess. I know I should clean it but I just can't find the energy or motivation. I look around and it just makes me feel worse, like the mess on the outside matches the mess on the inside.
125
 
@@ -133,7 +155,7 @@ I feel like I'm drowning in quicksand. The more I struggle, the faster I sink. W
133
 
134
  I just want it to stop. The noise in my head. The constant feeling of dread. I'm so tired of fighting. I just want to feel okay again, but I've forgotten what that even feels like."""
135
 
136
- # Build Gradio interface
137
  with gr.Blocks(theme=gr.themes.Soft(), title="Early Depression Detection") as demo:
138
 
139
  # Header
@@ -155,42 +177,42 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Early Depression Detection") as de
155
  )
156
 
157
  with gr.Row():
158
- gr.Markdown("[πŸ“„ Model Card](https://huggingface.co/mental/mental-longformer-depression)")
159
- gr.Markdown("[πŸ‘€ Author LinkedIn](https://www.linkedin.com/in/yourprofile)")
160
 
161
- # Examples Section at Top
162
  gr.Markdown("## πŸ“‹ Example Inputs")
163
  gr.Markdown(
164
  "Click an example below to see how the model works. "
165
  "Each category shows different risk levels based on linguistic patterns."
166
  )
167
 
168
- with gr.Row():
169
- user_input = gr.Textbox(
170
- label="πŸ“ Enter User Text History (300+ words recommended)",
171
- placeholder="Paste multiple social media posts, journal entries, or extended writing samples here...",
172
- lines=15,
173
- max_lines=20
174
- )
175
 
176
- # Three categories of examples
177
  with gr.Accordion("🟒 Low Risk Examples", open=False):
178
  gr.Examples(
179
- examples=[[LOW_RISK_EXAMPLE]],
180
  inputs=user_input,
181
  label="Positive, engaged content"
182
  )
183
 
184
  with gr.Accordion("🟑 Moderate Risk Examples", open=False):
185
  gr.Examples(
186
- examples=[[MODERATE_RISK_EXAMPLE]],
187
  inputs=user_input,
188
  label="Some concerning patterns"
189
  )
190
 
191
  with gr.Accordion("πŸ”΄ High Risk Examples", open=True):
192
  gr.Examples(
193
- examples=[[HIGH_RISK_EXAMPLE]],
194
  inputs=user_input,
195
  label="Strong depression markers"
196
  )
@@ -201,20 +223,10 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Early Depression Detection") as de
201
  submit_btn = gr.Button("Submit", variant="primary", size="lg")
202
 
203
  # Output Section
204
- risk_title = gr.Markdown("## Assessment Result")
205
- output_text = gr.Markdown()
206
 
207
  # Model Technical Details
208
- with gr.Accordion("πŸ“Š Model Technical Details", open=False):
209
- gr.Markdown("""
210
- - **Score Breakdown:** Depression: 89.8% | Non-Depression: 10.2%
211
- - **Decision Threshold:** 60% (optimal from training)
212
- - **Model Context:** 4,096 tokens
213
- - **Validation F1-Score:** 0.7668
214
- """)
215
-
216
- # Risk Scale Info
217
- with gr.Accordion("ℹ️ About the Risk Scale", open=False):
218
  gr.Markdown("""
219
  This model uses research-validated thresholds:
220
 
@@ -234,20 +246,11 @@ This tool is for **research and screening purposes only**. It should never be us
234
  - To make clinical decisions without human oversight
235
  - For surveillance or discrimination
236
  - Without informed consent
237
-
238
- **May produce false positives/negatives**
239
  """)
240
 
241
  # Important Disclaimers
242
- gr.Markdown("## ⚠️ Important Disclaimers")
243
  gr.Markdown("""
244
- **This is NOT a diagnostic tool.** This model:
245
-
246
- - Detects statistical patterns in language, not clinical depression
247
- - Requires professional interpretation
248
- - Cannot replace mental health assessment by qualified professionals
249
- - May produce false positives/negatives
250
-
251
  **If you're in crisis, help is available NOW:**
252
 
253
  - πŸ†˜ **Crisis Text Line:** Text HOME to 741741 (US)
@@ -255,27 +258,19 @@ This tool is for **research and screening purposes only**. It should never be us
255
  - 🌍 **International:** [befrienders.org](https://www.befrienders.org)
256
  """)
257
 
258
- gr.Markdown(
259
- "*Analysis based on linguistic patterns from eRisk datasets. "
260
- "Consult healthcare professionals for mental health concerns.*"
261
- )
262
-
263
- with gr.Row():
264
- gr.Button("πŸ”— Share via Link", link="https://huggingface.co/spaces/avtak/depression-detection-mcp-agent")
265
-
266
  # Event handlers
267
  submit_btn.click(
268
- fn=predict_depression,
269
  inputs=user_input,
270
- outputs=[risk_title, output_text, gr.Textbox(visible=False)]
271
  )
272
 
273
  clear_btn.click(
274
- fn=lambda: ("", "## Assessment Result", ""),
275
  inputs=None,
276
- outputs=[user_input, risk_title, output_text]
277
  )
278
 
279
- # Launch
280
  if __name__ == "__main__":
281
- demo.launch()
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
+ from huggingface_hub import login
4
  import os
5
 
6
+ # Authenticate with HuggingFace for private model access
7
+ token = os.getenv("HF_TOKEN")
8
+ if token:
9
+ login(token=token)
10
+
11
+ # Load your private model (CORRECT MODEL NAME!)
12
+ model_name = "avtak/erisk-longformer-depression-v1"
13
+ classifier = pipeline("text-classification", model=model_name, truncation=True, max_length=4096, top_k=None)
14
+
15
+ def get_risk_interpretation(depression_score):
16
+ """
17
+ Interprets depression risk score using research-based thresholds.
18
+ Optimal threshold from training: 0.6
19
+ """
20
+ if depression_score < 0.30:
21
+ return {
22
+ "level": "Low Risk",
23
+ "color": "🟒",
24
+ "interpretation": "Linguistic patterns consistent with non-depressed users. No significant markers of depression detected.",
25
+ "recommendation": "Continue monitoring mental wellness. Maintain healthy habits."
26
+ }
27
+ elif 0.30 <= depression_score < 0.60:
28
+ return {
29
+ "level": "Moderate Risk",
30
+ "color": "🟑",
31
+ "interpretation": "Some linguistic markers associated with depression detected. May indicate early signs or temporary mood changes.",
32
+ "recommendation": "Consider monitoring over time. Seek support if feelings persist. Talk to someone you trust."
33
+ }
34
+ else: # >= 0.60 (optimal threshold from training)
35
+ return {
36
+ "level": "High Risk",
37
+ "color": "πŸ”΄",
38
+ "interpretation": "Strong linguistic patterns associated with depression detected. Multiple markers of depressive language present.",
39
+ "recommendation": "Strongly recommend speaking with a mental health professional. Immediate support resources provided below."
40
+ }
41
+
42
+ def analyze_text(user_text):
43
+ """
44
+ Analyzes text for linguistic markers of depression using Mental-Longformer.
45
 
46
+ This MCP tool provides depression risk assessment based on long-form user histories.
47
+ Trained on eRisk datasets (2017-2022) with F1-score of 0.7668.
48
+ Optimal decision threshold: 0.6
49
+ """
50
+ if not user_text.strip():
51
+ return "⚠️ Please provide text to analyze."
52
 
53
+ # Check text length
54
+ word_count = len(user_text.split())
55
+ if word_count < 100:
56
+ return f"""⚠️ **Warning: Text Too Short ({word_count} words)**
57
+
58
+ This model requires extensive text (300+ words recommended) for accurate analysis.
59
+ Short inputs will produce unreliable results.
60
+
61
+ Please provide:
62
+ - Multiple social media posts (10-15 posts)
63
+ - Extended writing samples
64
+ - Long-form personal narratives
65
+
66
+ Use the examples below to see proper input format."""
67
 
68
+ results = classifier(user_text)[0]
 
 
 
 
 
 
 
69
 
70
+ # Get depression probability (LABEL_1)
71
+ depression_prob = next((r['score'] for r in results if r['label'] == 'LABEL_1'), 0)
72
+ risk_info = get_risk_interpretation(depression_prob)
 
73
 
74
+ output = f"""# {risk_info['color']} Depression Risk Assessment: {risk_info['level']}
75
+
76
+ **Depression Probability:** {depression_prob*100:.1f}%
77
+ **Text Length:** {word_count} words
78
+
79
+ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  ## Risk Interpretation
82
 
83
+ **{risk_info['interpretation']}**
84
+
85
+ ### Recommended Action
86
+ {risk_info['recommendation']}
87
+
88
+ ---
89
+
90
+ ## Model Technical Details
91
+ - **Score Breakdown:** Depression: {depression_prob*100:.1f}% | Non-Depression: {(1-depression_prob)*100:.1f}%
92
+ - **Decision Threshold:** 60% (optimal from training)
93
+ - **Model Context:** 4,096 tokens
94
+ - **Validation F1-Score:** 0.7668
95
+
96
+ ---
97
 
98
+ ## ⚠️ Important Disclaimers
99
+
100
+ **This is NOT a diagnostic tool.** This model:
101
+
102
+ - Detects statistical patterns in language, not clinical depression
103
+ - Requires professional interpretation
104
+ - Cannot replace mental health assessment by qualified professionals
105
+ - May produce false positives/negatives
106
 
107
+ **If you're in crisis, help is available NOW:**
108
+
109
+ - πŸ†˜ **Crisis Text Line:** Text HOME to 741741 (US)
110
+ - πŸ“ž **National Suicide Prevention Lifeline:** 988 (US)
111
+ - 🌍 **International:** [befrienders.org](https://befrienders.org)
112
+
113
+ ---
114
+
115
+ *Analysis based on linguistic patterns from eRisk datasets. Consult healthcare professionals for mental health concerns.*
116
  """
117
+ return output
 
118
 
119
+ # Clean examples WITHOUT post numbers or separators
120
+ example_low_risk = """I'm thinking of expanding my garden to include some tomatoes next. I've been watching a bunch of videos on how to build a small planter box. Feeling excited about the new project.
121
 
122
  It's been a good week. Had some small wins, spent time with people I care about, and got to enjoy my hobby. Feeling content and looking forward to what next week brings.
123
 
 
129
 
130
  Work has been busy but manageable. I completed a challenging project ahead of schedule and my manager gave me positive feedback. Feeling accomplished and motivated."""
131
 
132
+ example_moderate_risk = """Been feeling a bit off lately. Not sure what it is, but I just don't have the same energy I used to have. Maybe I'm just tired from work.
133
 
134
  My sleep schedule has been all over the place. Some nights I can't fall asleep, other nights I sleep too much. Either way, I wake up feeling drained.
135
 
 
141
 
142
  Haven't been eating as healthy as I should. Skipping meals or just grabbing whatever is convenient. Cooking feels like too much effort right now."""
143
 
144
+ example_high_risk = """I woke up feeling exhausted even after sleeping for 10 hours. The thought of getting out of bed feels overwhelming. I don't even know why I bother anymore.
145
 
146
  My apartment is a mess. I know I should clean it but I just can't find the energy or motivation. I look around and it just makes me feel worse, like the mess on the outside matches the mess on the inside.
147
 
 
155
 
156
  I just want it to stop. The noise in my head. The constant feeling of dread. I'm so tired of fighting. I just want to feel okay again, but I've forgotten what that even feels like."""
157
 
158
+ # Build Gradio interface with examples at TOP
159
  with gr.Blocks(theme=gr.themes.Soft(), title="Early Depression Detection") as demo:
160
 
161
  # Header
 
177
  )
178
 
179
  with gr.Row():
180
+ gr.Markdown("[πŸ“„ Model Card](https://huggingface.co/avtak/erisk-longformer-depression-v1)")
181
+ gr.Markdown("[πŸ‘€ Author LinkedIn](https://www.linkedin.com/in/hassanzh/)")
182
 
183
+ # Examples Section at Top (BEFORE input textbox)
184
  gr.Markdown("## πŸ“‹ Example Inputs")
185
  gr.Markdown(
186
  "Click an example below to see how the model works. "
187
  "Each category shows different risk levels based on linguistic patterns."
188
  )
189
 
190
+ # Create the input textbox first (but it will be referenced by examples)
191
+ user_input = gr.Textbox(
192
+ label="πŸ“ Enter User Text History (300+ words recommended)",
193
+ placeholder="Paste multiple social media posts, journal entries, or extended writing samples here...",
194
+ lines=15,
195
+ max_lines=20
196
+ )
197
 
198
+ # Three categories of examples ABOVE the textbox visually
199
  with gr.Accordion("🟒 Low Risk Examples", open=False):
200
  gr.Examples(
201
+ examples=[[example_low_risk]],
202
  inputs=user_input,
203
  label="Positive, engaged content"
204
  )
205
 
206
  with gr.Accordion("🟑 Moderate Risk Examples", open=False):
207
  gr.Examples(
208
+ examples=[[example_moderate_risk]],
209
  inputs=user_input,
210
  label="Some concerning patterns"
211
  )
212
 
213
  with gr.Accordion("πŸ”΄ High Risk Examples", open=True):
214
  gr.Examples(
215
+ examples=[[example_high_risk]],
216
  inputs=user_input,
217
  label="Strong depression markers"
218
  )
 
223
  submit_btn = gr.Button("Submit", variant="primary", size="lg")
224
 
225
  # Output Section
226
+ output_text = gr.Markdown(label="πŸ“Š Risk Assessment Results")
 
227
 
228
  # Model Technical Details
229
+ with gr.Accordion("πŸ“Š About the Risk Scale", open=False):
 
 
 
 
 
 
 
 
 
230
  gr.Markdown("""
231
  This model uses research-validated thresholds:
232
 
 
246
  - To make clinical decisions without human oversight
247
  - For surveillance or discrimination
248
  - Without informed consent
 
 
249
  """)
250
 
251
  # Important Disclaimers
252
+ gr.Markdown("## ⚠️ Crisis Resources")
253
  gr.Markdown("""
 
 
 
 
 
 
 
254
  **If you're in crisis, help is available NOW:**
255
 
256
  - πŸ†˜ **Crisis Text Line:** Text HOME to 741741 (US)
 
258
  - 🌍 **International:** [befrienders.org](https://www.befrienders.org)
259
  """)
260
 
 
 
 
 
 
 
 
 
261
  # Event handlers
262
  submit_btn.click(
263
+ fn=analyze_text,
264
  inputs=user_input,
265
+ outputs=output_text
266
  )
267
 
268
  clear_btn.click(
269
+ fn=lambda: "",
270
  inputs=None,
271
+ outputs=user_input
272
  )
273
 
274
+ # πŸ”₯ Enable MCP Server
275
  if __name__ == "__main__":
276
+ demo.launch(mcp_server=True)