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a9
98ff0b6
 
 
 
 
 
cfc30a9
98ff0b6
cfc30a9
 
98ff0b6
cfc30a9
98ff0b6
 
 
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
 
 
cfc30a9
 
 
98ff0b6
 
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
 
 
 
 
 
 
 
 
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
 
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
 
 
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
cfc30a9
98ff0b6
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
---
library_name: transformers
tags: ["distilbert", "multi-label-classification", "call-center-analytics", "nlp", "multi-task-learning"]
---

# DistilBERT Multi-Label Classification Model

This repository hosts a fine-tuned **DistilBERT-base-uncased** model for **multi-label classification of call center transcripts**.  
It is designed for real-time **case categorization**, **urgency detection**, and **intervention recommendations** in helpline and child protection contexts.

---

## Model Details

- **Developed by:** BITZ IT CONSULTING 
- **Funded by [optional]:**   
- **Shared by:** Internal ML team  
- **Model type:** Multi-label text classifier (4 tasks, multi-task heads)  
- **Language(s):** English   
- **License:**  
- **Finetuned from:** `distilbert-base-uncased`  

### Sources

- **Repository:** [This Hugging Face Repo](https://huggingface.co/openchlsystem/CHS_tz_classifier_distilbert)  
- **Paper [optional]:** N/A  
- **Demo [optional]:** Coming soon  

---

## Uses

### Direct Use
- Real-time classification of call transcripts  
- Case categorization for reporting and dashboards  

### Downstream Use
- Fine-tuning on other multi-label customer service or support datasets  
- Integration in larger NLP pipelines (chatbots, QA systems, ASR + NLP pipelines)  

### Out-of-Scope Use
- Not intended for medical, legal, or financial advice without human oversight  
- Not reliable for domains outside call center/customer service transcripts  

---

## Bias, Risks, and Limitations

- The dataset includes **anonymized transcripts** but may reflect biases in annotation.
- Part of the Dataset was synthetically generated.  
- Performance may degrade on **languages other than English/Swahili**.  
- Urgency detection relies on limited data → risk of false negatives for critical cases.  

### Recommendations
- Use **confidence thresholds** wisely (see section below).  
- Keep a **human-in-the-loop** for critical interventions.  
- Retrain periodically with fresh data to reduce drift.  

---

### Label Files
label mappings are alongside models, and are used to map the prediction and classification logits against class labels defined in the json files.

- [main_categories.json](./main_categories.json)  
- [sub_categories.json](./sub_categories.json)  
- [interventions.json](./interventions.json)  
- [priorities.json](./priorities.json)

## How to Get Started with the Model

```python
import torch
import json
import re
import numpy as np
from transformers import AutoTokenizer, AutoConfig, AutoModel

# Repo name on Hugging Face
model_name = "openchlsystem/CHS_tz_classifier_distilbert"
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Load config
config = AutoConfig.from_pretrained(model_name)

#  We re-define the distilbert Custom model class used in training
import torch.nn as nn
from transformers import DistilBertModel, DistilBertPreTrainedModel

class MultiTaskDistilBert(DistilBertPreTrainedModel):
    def __init__(self, config, num_main, num_sub, num_interv, num_priority):
        super().__init__(config)
        self.distilbert = DistilBertModel(config)
        self.pre_classifier = nn.Linear(config.dim, config.dim)
        self.classifier_main = nn.Linear(config.dim, num_main)
        self.classifier_sub = nn.Linear(config.dim, num_sub)
        self.classifier_interv = nn.Linear(config.dim, num_interv)
        self.classifier_priority = nn.Linear(config.dim, num_priority)
        self.dropout = nn.Dropout(config.dropout)
        self.init_weights()

    def forward(self, input_ids=None, attention_mask=None, **kwargs):
        distilbert_output = self.distilbert(
            input_ids=input_ids,
            attention_mask=attention_mask,
            return_dict=True
        )
        hidden_state = distilbert_output.last_hidden_state
        pooled_output = hidden_state[:, 0]
        pooled_output = self.pre_classifier(pooled_output)
        pooled_output = nn.ReLU()(pooled_output)
        pooled_output = self.dropout(pooled_output)

        logits_main = self.classifier_main(pooled_output)
        logits_sub = self.classifier_sub(pooled_output)
        logits_interv = self.classifier_interv(pooled_output)
        logits_priority = self.classifier_priority(pooled_output)

        return logits_main, logits_sub, logits_interv, logits_priority
    
# Downloading the class labels  for mapping 
from huggingface_hub import hf_hub_download

main_categories = json.load(open(hf_hub_download(model_name, "main_categories.json")))
sub_categories = json.load(open(hf_hub_download(model_name, "sub_categories.json")))
interventions = json.load(open(hf_hub_download(model_name, "interventions.json")))
priorities = json.load(open(hf_hub_download(model_name, "priorities.json")))

model = MultiTaskDistilBert.from_pretrained(
    model_name,
    num_main=len(main_categories),
    num_sub=len(sub_categories),
    num_interv=len(interventions),
    num_priority=len(priorities)
)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)


# inference
def classify_multitask_case(narrative: str):
    """
      Classifies a given narrative text into multiple categories using a multitask model.

      Args:
        narrative (str): The input text to be classified.

      Returns:
        dict: A dictionary containing the predicted labels for each task:
          - "main_category": Predicted main category label.
          - "sub_category": Predicted sub-category label.
          - "intervention": Predicted intervention label.
          - "priority": Predicted priority label.

      Notes:
        - The function preprocesses the input text by lowercasing and removing non-alphanumeric characters.
        - It uses a tokenizer and a multitask classification model to generate predictions.
        - Probabilities for each class are computed using softmax, and the label with the highest probability is selected for each task.
      """
    text = narrative.lower().strip()
    text = re.sub(r'[^a-z0-9\s]', '', text)

    inputs = tokenizer(
        text,
        truncation=True,
        padding="max_length",
        max_length=256,
        return_tensors="pt"
    ).to(device)

    with torch.no_grad():
        logits_main, logits_sub, logits_interv, logits_priority = model(**inputs)

    # Convert to probabilities (softmax per task)
    probs_main = torch.softmax(logits_main, dim=1).cpu().numpy()[0]
    probs_sub = torch.softmax(logits_sub, dim=1).cpu().numpy()[0]
    probs_interv = torch.softmax(logits_interv, dim=1).cpu().numpy()[0]
    probs_priority = torch.softmax(logits_priority, dim=1).cpu().numpy()[0]

    # Get predicted labels (argmax)
    pred_main = int(np.argmax(probs_main))
    pred_sub = int(np.argmax(probs_sub))
    pred_interv = int(np.argmax(probs_interv))
    pred_priority = int(np.argmax(probs_priority))

    return {
        "main_category": {
            main_categories[pred_main],
            # "probabilities": dict(zip(main_categories, probs_main.tolist()))
        },
        "sub_category": {
            sub_categories[pred_sub],
            # "probabilities": dict(zip(sub_categories, probs_sub.tolist()))
        },
        "intervention": {
            interventions[pred_interv],
            # "probabilities": dict(zip(interventions, probs_interv.tolist()))
        },
        "priority": {
            priorities[pred_priority],
            # "probabilities": dict(zip(priorities, probs_priority.tolist()))
        },
    }

# test
narrative= " Hello, I've been trying to find help for my son Ken. He's only ten years old and... he's been going through a terrible time at school. There's this boy, James Kibet, who keeps harassing him. It started with name-calling and teasing, but it's escalated to physical violence. I don't know what to do, Sarah. I can't bear to see my child suffer like this. I'm truly sorry to hear about your situation, Mary. It's never easy when our children are in pain. Can you tell me more about the school Ken attends and its location? We might be able to reach out to them for help. The school is Unknown Landmark, Muthambi Ward, Unknown Subcounty, Tharaka-Nithi County. I... I didn't want to burden anyone with this problem. But it seems like things are only getting worse. I don't know who else to turn to. Don't worry, Mary. You've taken the right step by reaching out to us today. We can help guide you through this difficult time. Let me first assure you that your call will be kept confidential. Now, I need to gather more information about the incidents. Can you describe any specific instances where Ken has been hurt or bullied? Oh, there have been so many times... one instance stands out though. About a week ago, James punched Ken during recess. He was left with a bloody lip and a black eye. The school officials were informed but they didn't seem to take any action against James.That sounds very serious, Mary. I'm afraid we may need to escalate this matter to the authorities if the school doesn't take appropriate action. We can provide you with resources and guidance on how to report this case to the police or child welfare services. Would that be alright? Yes, please. I'm willing to do whatever it takes to protect Ken. I just want him to feel safe again. Thank you for your help, Sarah"

print(classify_multitask_case(narrative))

````
Expected output 
```
{'main_category':  {'Advice and Counselling'}, 'sub_category': {'School Related Issues'}, 'intervention': {'Counselling'}, 'priority': {2}}
```
---

## Training Details

### Training Data

The model was fine-tuned on a proprietary dataset of over 11,000 call transcripts (1,000+ anonymized real calls and 10,000+ synthetic calls). The data was annotated for four multi-label tasks:

Main Topic: 7 classes (e.g., GBV, Nutrition)
Sub-Topic: 50+ classes (e.g., Albinism, Birth Registration)
Intervention: 4 classes (e.g., Referred, Counselling)
Priority: 3 classes (Low, Medium, High)

The dataset was stratified and balanced to minimize bias and maximize generalization.

### Training Procedure

#### Preprocessing

Text was tokenized using the DistilBERT tokenizer (distilbert-base-uncased) with a maximum sequence length of 512 tokens. Standard normalization (lowercasing) was applied.

Training Hyperparameters

Training regime: fp16 mixed precision
Learning Rate: 2e-5
Train Batch Size: 16
Epochs: 12
Optimizer: AdamW
Weight Decay: 0.01
Loss Function: Combined Cross-Entropy Loss (Multi-Task Learning)
Evaluation

## Testing Data, Factors & Metrics

### Testing Data

Model evaluation was performed on a held-out validation set (10% of the total data), stratified by sub-category to ensure representative distribution.

### Metrics

**Primary Metric:** Micro F1-Score (aggregated across all labels)

**Secondary Metrics:** Precision, Recall, and F1-score for each individual class and task.

**Overall Metric:** eval_avg_acc (average accuracy across all four tasks) was used for model selection.

## Results

The model achieves strong performance across all tasks, with a high Micro F1-Score. Performance is consistently high on majority classes. Continuous learning cycles are used to improve performance on minority classes.


| Task                 | Micro F1-Score                                                                             | Notes                         |
| -------------------- | ---------------------------------------------------------------------------------- | ------------------------------- |
| **Main Topic**     | High (e.g., >0.90)        | Robust performance on primary categorization. |
| **Sub-Topic** | Good (e.g., >0.80)                                                                  | Performance varies; higher on frequent sub-topics.    |
| **Intervention**    | High (e.g., >0.85) | Accurate prediction of recommended actions.      |
| **Priority**     | High (e.g., >0.88)                         | Critical for effective routing and escalation.          |

---


### Training Procedure

* **Loss Function:** Binary Cross-Entropy with logits (multi-label)
* **Optimizer:** AdamW
* **Scheduler:** Warm-up + linear decay
* **Epochs:** 12
* **Batch Size:** 16
* **Learning Rate:** 2e-5

---

## Classification Tasks

| Task                 | Labels                                                                             | Purpose                         |
| -------------------- | ---------------------------------------------------------------------------------- | ------------------------------- |
| **Sub-Category**     | Adoption, Albinism, Balanced Diet, Birth Registration, Breast Feeding, etc.        | Identifies detailed case topics |
| **Priority/Urgency** | Low, Medium, High                                                                  | Flags urgency for escalation    |
| **Main Category**    | Advice & Counselling, Child Custody, Disability, GBV, VANE, Nutrition, Information | High-level categorization       |
| **Intervention**     | Referred, Counselling, Signposting, Awareness/Information                          | Suggests next action            |

---


## Integration Guide: NLP Pipeline

1. **ASR (Whisper)** → transcribes call audio
2. **DistilBERT Classifier** → assigns categories, urgency, interventions
3. **Case Management** → routes to appropriate queues & dashboards

---

## Technical Specifications

### Model Architecture

* **Base:** DistilBERT-base-uncased
* **Custom heads:** 4 classification heads (main category, sub-category, priority, intervention)
* **Loss Function:** Multi-task weighted Cross-Entropy

### Compute Infrastructure

* **Hardware:** NVIDIA GPUs (training), CPU/GPU (inference)
* **Software:** PyTorch, Hugging Face Transformers, MLflow for tracking, Label Studio for data annotation and labeling and DVC for versioning the training data.

---

## Citation

If you use this model, please cite:

```bibtex
@software{chs_distilbert_multilabel,
  author = {Bitz AI Team},
  title = {DistilBERT Multi-Label Classifier for Call Center Transcripts},
  year = {2025},
  publisher = {Hugging Face},
  url = {https://huggingface.co/openchlsystem/CHS_tz_classifier_distilbert}
}
```

---

## Contact

* **Maintainer:** Bitz AI Team
* **Email:** \[[peter.rogendo@bitz-itc.com](mailto:peter.rogendo@bitz-itc.com)]

---

### Model Sources [optional]

<!-- Provide the basic links for the model. -->

- **Repository:** [https://huggingface.co/openchlsystem/CHS_tz_classifier_distilbert]
- **Paper [optional]:** [More Information Needed]
- **Demo [optional]:** [More Information Needed]

## Environmental Impact

<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->

Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).

- **Hardware Type:** NVIDIA GeForce RTX 4060
- **Hours used:** [More Information Needed]
- **Cloud Provider:** N/A
- **Compute Region:** N/A
- **Carbon Emitted:** N/As