Views
No views yet
normalabusiveincitementincitement.csvCLS + mean pooling + max pooling| Metric | Value |
|---|---|
| Accuracy | 82.40% |
| F1 Macro | 0.8025 |
| F1 Incitement | 0.7752 |
| ID | Label |
|---|---|
| 0 | normal |
| 1 | abusive |
| 2 | incitement |

model.pt weights plus the MARBERTv2 encoder and tokenizer.1import torch
2import re
3import unicodedata
4from transformers import AutoTokenizer
5from huggingface_hub import hf_hub_download
6
7# --- 1. CONFIGURATION & SETUP ---
8DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9print('device:', DEVICE)
10MAX_LENGTH = 160
11USE_NORMALIZED_TEXT_FOR_MODEL = False
12REPO_ID = "amitca71/marbertv2-levantine-incitement-detector-cls-mean-max"
13ARABIC_DIACRITICS = re.compile(r'[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06ED]')
14
15def normalize_arabic(text: str) -> str:
16 text = unicodedata.normalize('NFKC', text or '').strip()
17 text = ARABIC_DIACRITICS.sub('', text)
18 text = text.replace('أ', 'ا').replace('إ', 'ا').replace('آ', 'ا')
19 text = text.replace('ى', 'ي').replace('ؤ', 'و').replace('ئ', 'ي').replace('ة', 'ه')
20 text = re.sub(r'[^\w\s#@/]', ' ', text)
21 text = re.sub(r'\s+', ' ', text)
22 return text.strip().lower()
23
24def text_for_model(text: str, use_normalized: bool = USE_NORMALIZED_TEXT_FOR_MODEL) -> str:
25 return normalize_arabic(text) if use_normalized else (text or '').strip()
26
27# --- 2. LOAD MODEL & TOKENIZER ---
28print("Loading model and tokenizer...")
29tokenizer = AutoTokenizer.from_pretrained("UBC-NLP/MARBERTv2")
30
31# Initialize custom model (Ensure MarbertMultiTask is defined in your script before this)
32model = MarbertMultiTask("UBC-NLP/MARBERTv2", pooling_strategy="cls_mean_max")
33
34# Download and load weights
35model_path = hf_hub_download(repo_id=REPO_ID, filename="model.pt")
36model.load_state_dict(torch.load(model_path, map_location=DEVICE, weights_only=True))
37model.to(DEVICE)
38model.eval()
39
40# Package everything into the bundle expected by the function
41bundle = {
42 "model": model,
43 "tokenizer": tokenizer,
44 "label_map": {0: "normal", 1: "abusive", 2: "incitement"}
45}
46
47# --- 3. PREDICTION FUNCTION ---
48def predict_one(bundle, text: str):
49 encoded = bundle["tokenizer"](
50 text_for_model(text),
51 truncation=True,
52 padding="max_length",
53 max_length=MAX_LENGTH,
54 return_tensors="pt"
55 ).to(DEVICE)
56
57 with torch.no_grad():
58 out = bundle["model"](**encoded)
59
60 # Handle different forward() return types
61 if isinstance(out, dict):
62 logits = out["logits"]
63 lexicon_logits = out.get("lexicon_logits", None)
64 elif isinstance(out, tuple):
65 logits = out[0]
66 lexicon_logits = out[1] if len(out) > 1 else None
67 else:
68 logits = out
69 lexicon_logits = None
70
71 probs = torch.softmax(logits, dim=-1).squeeze(0).tolist()
72 pred_id = probs.index(max(probs))
73
74 response = {
75 "pred_label": bundle["label_map"][pred_id],
76 "confidence": probs[pred_id],
77 "prob_normal": probs[0],
78 "prob_abusive": probs[1],
79 "prob_incitement": probs[2],
80 }
81
82 if lexicon_logits is not None:
83 response["lexicon_signal_prob"] = torch.sigmoid(lexicon_logits).squeeze(0).item()
84
85 return response
86
87# --- 4. EXECUTE ONE CALL ---
88sample_text = "انت يا عميل السفارات يا ابن الكلب حسابك عسير"
89response = predict_one(bundle, sample_text)
90
91print("\nPrediction Response:")
92print(response)