Downloads · 30 days
15
0% of all-time downloads
openchs/cls-gbv-distilbert-v1
cls-gbv-distilbert-v1 is a text classification model from openchs. Use it when you need a label for a piece of text. It is set up for transformers. The card lists the license as apache-2.0.
This is a fine-tuned DistilBERT-base-uncased model designed for multi-task classification of child helpline and call center transcripts. Developed by BITZ IT Consulting as part of the OpenCHS AI pipeline for child hel…
Downloads · 30 days
15
0% of all-time downloads
All-time downloads
3.4K
Public
Parameters
67M
1.1 GB on disk
Likes
2
Public
Click a slice to open those files.
.safetensors268 MB · 99%
From the Hugging Face model README
This is a fine-tuned DistilBERT-base-uncased model designed for multi-task classification of child helpline and call center transcripts. Developed by BITZ IT Consulting as part of the OpenCHS AI pipeline for child helplines and crisis support services in East Africa. Speed and accuracy at resolving and reporting the cases matters, this finetuned model offers both.
The model performs simultaneous classification across four critical dimensions:
| Task | Classes | Count | Purpose |
|---|---|---|---|
| Main Category | Advice & Counselling, Child Custody, Disability, GBV, VANE, Nutrition, Information | 6 | High-level case categorization |
| Sub Category | Adoption, Albinism, Balanced Diet, Birth Registration, Child Abuse, etc. | 43 | Detailed topic identification |
| Intervention | Referred, Counselling, Signposting, Awareness/Information | 4 | Recommended action type |
| Priority | Low (1), Medium (2), High (3) | 3 | Urgency level for escalation |
| Metric | Value |
|---|---|
| Epoch | 12.0 |
| Eval Avg Acc | 0.6536885245901639 |
| Eval Interv Acc | 0.6953551912568307 |
| Eval Priority Acc | 0.639344262295082 |
| Eval Runtime | 3.9171 |
| Eval Samples Per Second | 186.872 |
| Eval Steps Per Second | 11.743 |
| Eval Sub Acc | 0.5806010928961749 |
| Task | Accuracy | Precision | Recall | F1-Score | Performance Level |
|---|---|---|---|---|---|
| Main Category | 69.94% | High | High | 0.69 | Good |
| Priority | 63.93% | 0.575 | Variable | 0.58 | Needs Improvemeent |
| Intervention | 69.53% | Variable | Variable | 0.67 | Good |
| Sub Category | 58.06% | Low | Variable | 0.57 | Needs Improvement |
Main Category Performance:
Sub Category Performance:
Priority Classification:
Intervention Recommendations:
pip install transformers torch numpy
import torch
import torch.nn as nn
from transformers import DistilBertModel, DistilBertPreTrainedModel, AutoTokenizer
import json
import re
import numpy as np
class MultiTaskDistilBert(DistilBertPreTrainedModel):
"""
Multi-task DistilBERT classifier for child helpline case management.
Performs simultaneous classification across 4 tasks:
- Main category classification
- Sub-category classification
- Intervention recommendation
- Priority assignment
"""
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)
# Task-specific classification heads
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,
main_category_id=None, sub_category_id=None,
intervention_id=None, priority_id=None):
# Shared DistilBERT encoder
distilbert_output = self.distilbert(
input_ids=input_ids,
attention_mask=attention_mask,
return_dict=True
)
# Feature extraction and processing
hidden_state = distilbert_output.last_hidden_state
pooled_output = hidden_state[:, 0] # [CLS] token
pooled_output = self.pre_classifier(pooled_output)
pooled_output = nn.ReLU()(pooled_output)
pooled_output = self.dropout(pooled_output)
# Multi-task predictions
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)
# Multi-task loss calculation (training only)
loss = None
if main_category_id is not None:
loss_fct = nn.CrossEntropyLoss()
loss_main = loss_fct(logits_main, main_category_id)
loss_sub = loss_fct(logits_sub, sub_category_id)
loss_interv = loss_fct(logits_interv, intervention_id)
loss_priority = loss_fct(logits_priority, priority_id)
loss = loss_main + loss_sub + loss_interv + loss_priority
# Return format compatible with Trainer
if loss is not None:
return (loss, logits_main, logits_sub, logits_interv, logits_priority)
else:
return (logits_main, logits_sub, logits_interv, logits_priority)
from transformers import AutoTokenizer
from huggingface_hub import hf_hub_download
import torch
import json
import re
import numpy as np
# Model setup
MODEL_NAME = "openchs/cls-gbv-distilbert-v1"
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
# Load label mappings
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")))
# Initialize model
model = MultiTaskDistilBert.from_pretrained(
MODEL_NAME,
num_main=len(main_categories),
num_sub=len(sub_categories),
num_interv=len(interventions),
num_priority=len(priorities)
)
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
model.eval()
def classify_multitask_case(narrative: str):
"""
Classify a helpline case narrative across all task dimensions.
Args:
narrative (str): The case narrative/transcript text
Returns:
dict: Classifications for all four tasks with confidence scores
"""
# Text preprocessing
text = narrative.lower().strip()
text = re.sub(r'[^a-z0-9\s]', '', text) # Remove special characters
# Tokenization
inputs = tokenizer(
text,
truncation=True,
padding="max_length",
max_length=256,
return_tensors="pt"
).to(device)
# Inference
with torch.no_grad():
logits_main, logits_sub, logits_interv, logits_priority = model(**inputs)
# Convert logits to probabilities
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 predictions (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": {
"label": main_categories[pred_main],
"confidence": float(probs_main[pred_main])
},
"sub_category": {
"label": sub_categories[pred_sub],
"confidence": float(probs_sub[pred_sub])
},
"intervention": {
"label": interventions[pred_interv],
"confidence": float(probs_interv[pred_interv])
},
"priority": {
"label": priorities[pred_priority],
"confidence": float(probs_priority[pred_priority])
}
}
# Example usage
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, 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. I can't bear to see my child suffer like this.
"""
result = classify_multitask_case(narrative)
print(json.dumps(result, indent=2))
Expected Output:
{
"main_category": {
"label": "Advice and Counselling",
"confidence": 0.85
},
"sub_category": {
"label": "School Related Issues",
"confidence": 0.72
},
"intervention": {
"label": "Counselling",
"confidence": 0.68
},
"priority": {
"label": 2,
"confidence": 0.91
}
}
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import time
app = FastAPI(title="Child Helpline Case Classification API")
class CaseInput(BaseModel):
narrative: str
include_confidence: Optional[bool] = True
@app.post("/classify")
async def classify_case(input_data: CaseInput):
try:
start_time = time.time()
result = classify_multitask_case(input_data.narrative)
processing_time = time.time() - start_time
response = {
"success": True,
"classification": result,
"processing_time_seconds": round(processing_time, 4)
}
if not input_data.include_confidence:
# Remove confidence scores if not requested
for task in result:
if isinstance(result[task], dict):
result[task] = result[task]["label"]
return response
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/health")
async def health_check():
return {"status": "healthy", "model": MODEL_NAME}
The model is designed to integrate seamlessly into larger AI pipelines:
ASR (Whisper) → Transcribes call audio to text
Text Preprocessing → Cleans and normalizes transcript
MultiTask Classification → Categorizes and prioritizes case
NER → Extracts Entities
Case Management System → Routes to appropriate classes
Quality Assurance → Tracks outcomes and model performance
@software{chs_distilbert_multitask_2025,
title={DistilBERT Multi-Task Classifier for Child Helpline Case Management},
author={BITZ IT Consulting Team},
year={2025},
publisher={Hugging Face},
journal={Hugging Face Model Hub},
howpublished={\url{https://huggingface.co/openchs/cls-gbv-distilbert-v1}},
note={AI for Social Impact: Automated Case Classification for Child Protection Services}
}
The model's multi-task architecture allows for analysis of shared vs. task-specific representations:
Common misclassification patterns:
Carbon emissions estimated using the Machine Learning Impact calculator:
Training was conducted locally to minimize environmental impact and ensure data privacy for sensitive helpline transcripts.
Evaluation disaggregated by:
Main Category: High-level case classification (6 classes) used for initial routing and reporting
Sub Category: Detailed topic identification (43 classes) for specific issue targeting and resource allocation
Intervention: Recommended action type (22 classes) guiding case worker response and follow-up procedures
Priority: Urgency level (3 levels) determining response timeframe and resource allocation
Multi-task Learning: Training approach where model learns multiple related tasks simultaneously using shared representations
PII: Personally Identifiable Information - any data that could identify specific individuals, systematically removed from training data
Case Routing: Automated process of directing cases to appropriate teams based on classification results
This model is part of a larger AI pipeline including:
@model{qa_helpline_distilbert_2025,
title={QA Multi-Head DistilBERT for Helpline Quality Assessment},
author={BITZ IT Consulting Team},
year={2025},
publisher={Hugging Face},
journal={Hugging Face Model Hub},
howpublished={\url{https://huggingface.co/openchs/cls-gbv-distilbert-v1}},
note={AI for Social Impact: Child Helplines and Crisis Support in East Africa}
}
Organization: BITZ IT Consulting
Support: Technical questions and collaboratifzon inquiries welcome
Repository Issues: https://huggingface.co/openchs/cls-gbv-distilbert-v1/discussions
Technology for Child Protection and Crisis Support