Samdutse commited on
Commit
c830d31
Β·
verified Β·
1 Parent(s): 54cbc8e

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +128 -0
app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import torch
4
+ import joblib
5
+ import numpy as np
6
+ from transformers import DistilBertTokenizerFast, DistilBertForSequenceClassification
7
+ import re
8
+ import contractions
9
+
10
+ # Load model and tokenizer
11
+ tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert")
12
+ model = DistilBertForSequenceClassification.from_pretrained("distilbert")
13
+ model.eval()
14
+
15
+ le = joblib.load("label_encoder.pkl")
16
+ label_map = {i: cls for i, cls in enumerate(le.classes_)}
17
+
18
+ # Class display config
19
+ class_config = {
20
+ "Normal": {"emoji": "🟒", "color": "#2ecc71"},
21
+ "Anxiety": {"emoji": "🟑", "color": "#f39c12"},
22
+ "Stress": {"emoji": "🟠", "color": "#e67e22"},
23
+ "Depression": {"emoji": "πŸ”΅", "color": "#3498db"},
24
+ "Bipolar": {"emoji": "🟣", "color": "#9b59b6"},
25
+ "Personality disorder": {"emoji": "βšͺ", "color": "#95a5a6"},
26
+ "Suicidal": {"emoji": "πŸ”΄", "color": "#e74c3c"},
27
+ }
28
+
29
+ CRISIS_MESSAGE = """
30
+ ⚠️ CRISIS SUPPORT β€” You are not alone.
31
+
32
+ If you or someone you know is in crisis, please reach out immediately:
33
+ - International Association for Suicide Prevention: https://www.iasp.info/resources/Crisis_Centres/
34
+ - Crisis Text Line (US): Text HOME to 741741
35
+ - Nigeria: NEEM Foundation β€” +234 806 210 6493
36
+ - Befrienders Worldwide: https://www.befrienders.org
37
+ """
38
+
39
+ def clean_text(text):
40
+ if not isinstance(text, str):
41
+ return ""
42
+ text = contractions.fix(text)
43
+ text = text.lower()
44
+ text = re.sub(r"http\S+|www\S+", "", text)
45
+ text = re.sub(r"[^a-z\s]", "", text)
46
+ text = re.sub(r"\s+", " ", text).strip()
47
+ return text
48
+
49
+ def predict(statement):
50
+ if not statement.strip():
51
+ return "Please enter a statement.", "", ""
52
+
53
+ clean = clean_text(statement)
54
+
55
+ inputs = tokenizer(
56
+ clean,
57
+ return_tensors="pt",
58
+ truncation=True,
59
+ padding=True,
60
+ max_length=128
61
+ )
62
+
63
+ with torch.no_grad():
64
+ outputs = model(**inputs)
65
+ probs = torch.softmax(outputs.logits, dim=1).squeeze()
66
+
67
+ pred_idx = torch.argmax(probs).item()
68
+ pred_label = label_map[pred_idx]
69
+ confidence = round(probs[pred_idx].item() * 100, 1)
70
+
71
+ cfg = class_config[pred_label]
72
+ result = f"{cfg['emoji']} {pred_label} ({confidence}% confidence)"
73
+
74
+ # Top 3 probabilities
75
+ top3_idx = torch.argsort(probs, descending=True)[:3]
76
+ breakdown = "Probability breakdown:\n"
77
+ for idx in top3_idx:
78
+ lbl = label_map[idx.item()]
79
+ pct = round(probs[idx].item() * 100, 1)
80
+ breakdown += f" {class_config[lbl]['emoji']} {lbl}: {pct}%\n"
81
+
82
+ crisis = CRISIS_MESSAGE if pred_label == "Suicidal" else ""
83
+
84
+ return result, breakdown, crisis
85
+
86
+ # UI
87
+ with gr.Blocks(title="MentalPulse") as demo:
88
+ gr.Markdown("""
89
+ # 🧠 MentalPulse β€” Mental Health Signal Classifier
90
+ ### Detect mental health signals from text using fine-tuned DistilBERT
91
+ *Built by Samuel Yaula Dutse | Mental Health Awareness Month β€” June 2026*
92
+
93
+ > ⚠️ This tool is for research and educational purposes only.
94
+ > It is not a clinical diagnostic tool. If you are in crisis, please seek professional help.
95
+ """)
96
+
97
+ with gr.Row():
98
+ with gr.Column():
99
+ text_input = gr.Textbox(
100
+ label="Enter a statement",
101
+ placeholder="How are you feeling? Describe your thoughts or emotions...",
102
+ lines=5
103
+ )
104
+ submit_btn = gr.Button("Analyze", variant="primary")
105
+
106
+ with gr.Column():
107
+ pred_output = gr.Textbox(label="Detected Signal", interactive=False)
108
+ breakdown_output = gr.Textbox(label="Confidence Breakdown", lines=5, interactive=False)
109
+ crisis_output = gr.Textbox(label="Crisis Resources", lines=8, interactive=False, visible=True)
110
+
111
+ gr.Examples(
112
+ examples=[
113
+ ["I have been feeling so hopeless lately, nothing makes sense and I just want it to stop"],
114
+ ["My heart races constantly and I cannot stop worrying about everything"],
115
+ ["Today was actually a good day. I felt present and enjoyed time with my family"],
116
+ ["My mood swings are so extreme, one day I feel invincible and the next I cannot get out of bed"],
117
+ ["Work has been overwhelming and I feel like I am stretched too thin"],
118
+ ],
119
+ inputs=[text_input]
120
+ )
121
+
122
+ submit_btn.click(
123
+ fn=predict,
124
+ inputs=[text_input],
125
+ outputs=[pred_output, breakdown_output, crisis_output]
126
+ )
127
+
128
+ demo.launch()