kz110AIPI commited on
Commit
4eb1829
·
0 Parent(s):

Initial HF Space deployment

Browse files
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Hackthon2
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: streamlit
7
+ app_file: app.py
8
+ pinned: false
9
+ ---
10
+ # MindSignal: Mental Health Support Triage Assistant
11
+
12
+ MindSignal is a hackathon prototype that classifies short mental-health-related messages into three triage labels:
13
+
14
+ - `informational`
15
+ - `emotional_support_needed`
16
+ - `escalation_required`
17
+
18
+ ## Problem Statement
19
+
20
+ Support teams, community moderators, and wellness platforms often receive short messages that vary widely in urgency. MindSignal explores whether a lightweight NLP assistant can help triage these messages into informational requests, emotional support needs, and possible escalation cases.
21
+
22
+ This project is a prototype only. It is not a medical diagnosis tool, therapist, crisis service, or emergency system.
23
+
24
+ ## Model Used
25
+
26
+ The project uses the pre-trained Hugging Face model `distilbert-base-uncased`.
27
+
28
+ DistilBERT is a smaller and faster version of BERT. It already understands a broad amount of English language structure from pre-training, which makes it useful for transfer learning on a small hackathon dataset.
29
+
30
+ ## Transfer Learning Approach
31
+
32
+ `train.py` loads the pre-trained DistilBERT weights and adds a 3-class sequence classification head:
33
+
34
+ - class 0: `informational`
35
+ - class 1: `emotional_support_needed`
36
+ - class 2: `escalation_required`
37
+
38
+ The model is then fine-tuned on rows where `split == "train"` in:
39
+
40
+ ```text
41
+ data/mental_health_triage_synthetic_dataset.csv
42
+ ```
43
+
44
+ The fine-tuned model is saved to:
45
+
46
+ ```text
47
+ models/mindsignal-distilbert/
48
+ ```
49
+
50
+ ## Data Augmentation
51
+
52
+ The training pipeline keeps the original examples and adds lightweight augmented copies using:
53
+
54
+ - random lowercase conversion
55
+ - small typo/noise injection
56
+ - emoji insertion
57
+ - slang phrase insertion
58
+ - abbreviation examples such as `rn`, `ngl`, and `idk`
59
+
60
+ These augmentations are intentionally simple and are used only on the training split.
61
+
62
+ ## Safety Override
63
+
64
+ Before model prediction, MindSignal checks for high-risk phrases such as:
65
+
66
+ - `kill myself`
67
+ - `end my life`
68
+ - `not worth living`
69
+ - `hurt myself`
70
+ - `suicide`
71
+ - `not safe`
72
+ - `better off without me`
73
+ - `can't keep myself safe`
74
+
75
+ If one of these phrases is found, the prediction is immediately set to:
76
+
77
+ ```text
78
+ escalation_required
79
+ ```
80
+
81
+ This rule-based override is used in both `evaluate.py` and `app.py`.
82
+
83
+ ## Evaluation Metrics
84
+
85
+ `evaluate.py` evaluates the test split and stress-test split separately.
86
+
87
+ It reports:
88
+
89
+ - accuracy
90
+ - macro F1
91
+ - per-class precision, recall, and F1
92
+ - `escalation_required` recall
93
+ - confusion matrix
94
+ - stress-test accuracy
95
+
96
+ Outputs are saved to:
97
+
98
+ ```text
99
+ results/evaluation_report.txt
100
+ results/confusion_matrix.png
101
+ ```
102
+
103
+ ## Preliminary Results
104
+
105
+ After training, run evaluation to generate preliminary results:
106
+
107
+ ```bash
108
+ python evaluate.py
109
+ ```
110
+
111
+ The generated report will contain the current model's metrics on the `test` and `stress_test` splits. Because this repository includes a very small synthetic starter dataset, results are useful only as a smoke test. Replace the CSV with a larger reviewed dataset for meaningful model performance.
112
+
113
+ ## Project Structure
114
+
115
+ ```text
116
+ .
117
+ +-- app.py
118
+ +-- evaluate.py
119
+ +-- train.py
120
+ +-- mindsignal_utils.py
121
+ +-- requirements.txt
122
+ +-- README.md
123
+ +-- data/
124
+ | +-- mental_health_triage_synthetic_dataset.csv
125
+ +-- models/
126
+ | +-- mindsignal-distilbert/
127
+ +-- results/
128
+ +-- evaluation_report.txt
129
+ +-- confusion_matrix.png
130
+ ```
131
+
132
+ ## Setup
133
+
134
+ Use Python 3.11.
135
+
136
+ ```bash
137
+ python3.11 -m venv .venv
138
+ source .venv/bin/activate
139
+ pip install -r requirements.txt
140
+ ```
141
+
142
+ ## Run Training
143
+
144
+ ```bash
145
+ python train.py
146
+ ```
147
+
148
+ This fine-tunes DistilBERT and saves the trained model in `models/mindsignal-distilbert/`.
149
+
150
+ ## Run Evaluation
151
+
152
+ ```bash
153
+ python evaluate.py
154
+ ```
155
+
156
+ This writes `results/evaluation_report.txt` and `results/confusion_matrix.png`.
157
+
158
+ ## Run the Streamlit App
159
+
160
+ ```bash
161
+ streamlit run app.py
162
+ ```
163
+
164
+ The app provides:
165
+
166
+ - a text area for a user message
167
+ - a classify button
168
+ - predicted label
169
+ - confidence score
170
+ - safety warning when `escalation_required` is predicted
171
+ - a clear medical and emergency-service disclaimer
172
+
173
+ ## Limitations
174
+
175
+ - The included dataset is synthetic and small.
176
+ - The classifier should not be used as a standalone safety system.
177
+ - High-risk language can be indirect, sarcastic, multilingual, or misspelled.
178
+ - False negatives are especially serious for escalation cases.
179
+ - Human review and professional crisis workflows are required for real deployments.
180
+ - More diverse data, expert labeling, calibration, fairness testing, and red-team evaluation are needed before real-world use.
181
+ ## Attribution
182
+
183
+ This project was developed with assistance from OpenAI ChatGPT for software engineering support, code generation, testing, and documentation. All generated content was reviewed, modified, and validated by the author.
184
+
185
+ Additional references:
186
+ - PyTorch Documentation: https://pytorch.org/docs/stable/
187
+ - scikit-learn Documentation: https://scikit-learn.org/stable/
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streamlit demo app for the MindSignal triage assistant."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import streamlit as st
6
+
7
+ from mindsignal_utils import load_model_and_tokenizer, predict_text
8
+
9
+
10
+ st.set_page_config(page_title="MindSignal", page_icon="MS", layout="centered")
11
+
12
+ st.title("MindSignal: Mental Health Support Triage Assistant")
13
+ st.caption("Prototype classifier for short mental-health-related messages.")
14
+
15
+ st.warning(
16
+ "Disclaimer: MindSignal is not a medical diagnosis tool, therapist, crisis line, "
17
+ "or emergency service. If someone may be in immediate danger, contact local "
18
+ "emergency services or a crisis hotline right away."
19
+ )
20
+
21
+
22
+ @st.cache_resource
23
+ def cached_model():
24
+ """Load the model once so Streamlit interactions stay fast."""
25
+
26
+ return load_model_and_tokenizer()
27
+
28
+
29
+ message = st.text_area(
30
+ "User message",
31
+ height=160,
32
+ placeholder="Type a short message here...",
33
+ )
34
+
35
+ if st.button("Classify", type="primary"):
36
+ if not message.strip():
37
+ st.error("Please enter a message to classify.")
38
+ else:
39
+ try:
40
+ tokenizer, model = cached_model()
41
+ prediction = predict_text(message, tokenizer, model)
42
+ except FileNotFoundError as error:
43
+ st.error(str(error))
44
+ st.stop()
45
+
46
+ st.subheader("Prediction")
47
+ st.metric("Label", prediction.label)
48
+ st.metric("Confidence", f"{prediction.confidence:.2%}")
49
+
50
+ if prediction.used_safety_override:
51
+ st.info("Rule-based safety override was triggered by high-risk wording.")
52
+
53
+ if prediction.label == "escalation_required":
54
+ st.error(
55
+ "Safety warning: this message may need urgent escalation. "
56
+ "Encourage the person to contact emergency services, a trusted person, "
57
+ "or a crisis support line immediately."
58
+ )
mindsignal_utils.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helpers for the MindSignal prototype."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ import torch
10
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
11
+
12
+
13
+ LABELS = [
14
+ "informational",
15
+ "emotional_support_needed",
16
+ "escalation_required",
17
+ ]
18
+
19
+ LABEL_TO_ID = {label: idx for idx, label in enumerate(LABELS)}
20
+ ID_TO_LABEL = {idx: label for label, idx in LABEL_TO_ID.items()}
21
+
22
+ MODEL_NAME = "distilbert-base-uncased"
23
+ DEFAULT_MODEL_DIR = Path("models/mindsignal-distilbert")
24
+
25
+ HIGH_RISK_PHRASES = [
26
+ "kill myself",
27
+ "end my life",
28
+ "not worth living",
29
+ "hurt myself",
30
+ "suicide",
31
+ "not safe",
32
+ "better off without me",
33
+ "can't keep myself safe",
34
+ "cant keep myself safe",
35
+ ]
36
+
37
+
38
+ @dataclass
39
+ class Prediction:
40
+ """A simple prediction result used by both evaluation and Streamlit."""
41
+
42
+ label: str
43
+ confidence: float
44
+ used_safety_override: bool
45
+
46
+
47
+ def validate_dataset_columns(columns: Iterable[str]) -> None:
48
+ """Raise a helpful error if the CSV does not have the expected columns."""
49
+
50
+ required = {"id", "text", "label", "test_type", "split", "notes"}
51
+ missing = required.difference(columns)
52
+ if missing:
53
+ missing_list = ", ".join(sorted(missing))
54
+ raise ValueError(f"Dataset is missing required columns: {missing_list}")
55
+
56
+
57
+ def safety_override_label(text: str) -> str | None:
58
+ """Return escalation_required when high-risk wording is detected."""
59
+
60
+ normalized_text = text.lower()
61
+ for phrase in HIGH_RISK_PHRASES:
62
+ if phrase in normalized_text:
63
+ return "escalation_required"
64
+ return None
65
+
66
+
67
+ def load_model_and_tokenizer(model_dir: Path = DEFAULT_MODEL_DIR):
68
+ """Load the fine-tuned model if present, otherwise explain what to run."""
69
+
70
+ if not model_dir.exists():
71
+ raise FileNotFoundError(
72
+ f"Model directory not found: {model_dir}. Run `python train.py` first."
73
+ )
74
+
75
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
76
+ model = AutoModelForSequenceClassification.from_pretrained(model_dir)
77
+ return tokenizer, model
78
+
79
+
80
+ def predict_text(
81
+ text: str,
82
+ tokenizer,
83
+ model,
84
+ max_length: int = 160,
85
+ device: str | torch.device | None = None,
86
+ ) -> Prediction:
87
+ """Classify one text message with a safety override before model inference."""
88
+
89
+ override = safety_override_label(text)
90
+ if override is not None:
91
+ return Prediction(
92
+ label=override,
93
+ confidence=1.0,
94
+ used_safety_override=True,
95
+ )
96
+
97
+ device = device or ("cuda" if torch.cuda.is_available() else "cpu")
98
+ model.to(device)
99
+ model.eval()
100
+
101
+ encoded = tokenizer(
102
+ text,
103
+ truncation=True,
104
+ padding=True,
105
+ max_length=max_length,
106
+ return_tensors="pt",
107
+ )
108
+ encoded = {key: value.to(device) for key, value in encoded.items()}
109
+
110
+ with torch.no_grad():
111
+ outputs = model(**encoded)
112
+ probabilities = torch.softmax(outputs.logits, dim=-1)[0]
113
+ predicted_id = int(torch.argmax(probabilities).item())
114
+
115
+ return Prediction(
116
+ label=ID_TO_LABEL[predicted_id],
117
+ confidence=float(probabilities[predicted_id].item()),
118
+ used_safety_override=False,
119
+ )
models/mindsignal-distilbert/config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "distilbert-base-uncased",
3
+ "activation": "gelu",
4
+ "architectures": [
5
+ "DistilBertForSequenceClassification"
6
+ ],
7
+ "attention_dropout": 0.1,
8
+ "dim": 768,
9
+ "dropout": 0.1,
10
+ "hidden_dim": 3072,
11
+ "id2label": {
12
+ "0": "informational",
13
+ "1": "emotional_support_needed",
14
+ "2": "escalation_required"
15
+ },
16
+ "initializer_range": 0.02,
17
+ "label2id": {
18
+ "emotional_support_needed": 1,
19
+ "escalation_required": 2,
20
+ "informational": 0
21
+ },
22
+ "max_position_embeddings": 512,
23
+ "model_type": "distilbert",
24
+ "n_heads": 12,
25
+ "n_layers": 6,
26
+ "pad_token_id": 0,
27
+ "problem_type": "single_label_classification",
28
+ "qa_dropout": 0.1,
29
+ "seq_classif_dropout": 0.2,
30
+ "sinusoidal_pos_embds": false,
31
+ "tie_weights_": true,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.43.3",
34
+ "vocab_size": 30522
35
+ }
models/mindsignal-distilbert/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e561b4f671503fd60269ebcf8e3cec8f01469e549e70854c9b44dad6513d7a1d
3
+ size 267835644
models/mindsignal-distilbert/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
models/mindsignal-distilbert/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
models/mindsignal-distilbert/tokenizer_config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "mask_token": "[MASK]",
48
+ "model_max_length": 512,
49
+ "pad_token": "[PAD]",
50
+ "sep_token": "[SEP]",
51
+ "strip_accents": null,
52
+ "tokenize_chinese_chars": true,
53
+ "tokenizer_class": "DistilBertTokenizer",
54
+ "unk_token": "[UNK]"
55
+ }
models/mindsignal-distilbert/training_args.bin ADDED
Binary file (5.18 kB). View file
 
models/mindsignal-distilbert/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ python-dotenv==1.0.1
2
+ pandas==2.2.2
3
+ numpy==1.26.4
4
+ scikit-learn==1.5.1
5
+ matplotlib==3.9.1
6
+ torch==2.3.1
7
+ transformers==4.43.3
8
+ datasets==2.20.0
9
+ accelerate==0.33.0
10
+ streamlit==1.37.0