File size: 19,136 Bytes
d40eb53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import os
import json
import joblib
import numpy as np
from utils import clean_text, LABEL_COLS

# torch et transformers sont optionnels โ€” uniquement requis pour le Teacher XLM-R
try:
    import torch
    import torch.nn as nn
    from transformers import AutoTokenizer, AutoModel
    TORCH_AVAILABLE = True
except ImportError:
    TORCH_AVAILABLE = False


# โ”€โ”€ HuggingFace Hub โ€” fallback si fichiers absents en local โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
HF_REPO_ID = 'BHM03/amane-models'

def _resolve(local_path: str, hf_filename: str) -> str:
    """Retourne le chemin local si le fichier existe, sinon tรฉlรฉcharge depuis HF Hub."""
    if os.path.exists(local_path):
        return local_path
    try:
        from huggingface_hub import hf_hub_download
        return hf_hub_download(
            repo_id=HF_REPO_ID,
            filename=hf_filename,
            token=os.environ.get('HF_TOKEN'),
        )
    except Exception as e:
        raise FileNotFoundError(
            f'Fichier introuvable localement ({local_path}) '
            f'et tรฉlรฉchargement HF Hub รฉchouรฉ : {e}'
        )


# โ”€โ”€ Chemins modรจles โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
BENCHMARK_MODEL_PATH    = 'models/ovr_balanced.joblib'
BENCHMARK_TFIDF_PATH    = 'models/tfidf_vectorizer.joblib'
TEACHER_CKPT_PATH       = 'models/teacher/teacher_best.pt'
TEACHER_TOKENIZER_PATH  = 'models/teacher/tokenizer'
TEACHER_THRESH_PATH     = 'models/teacher/thresholds.json'
TEACHER_STAR_CKPT_PATH  = 'models/teacher_star/teacher_star.pt'
TEACHER_STAR_THRESH_PATH= 'models/teacher_star/threshold_darija.json'
STUDENT_CKPT_PATH       = 'models/student/student_best.pt'
STUDENT_THRESH_PATH     = 'models/student/threshold_student.json'

# โ”€โ”€ Hyperparamรจtres d'infรฉrence Teacher (cohรฉrents avec l'entraรฎnement) โ”€โ”€โ”€โ”€โ”€
TEACHER_MAX_LEN      = 256
TEACHER_STAR_MAX_LEN = 128
STUDENT_MAX_LEN      = 128
TEACHER_MODEL_HF     = 'xlm-roberta-base'
STUDENT_MODEL_HF     = 'distilbert-base-multilingual-cased'


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# BENCHMARK โ€” OneVsRest + LogisticRegression
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
class BenchmarkPredictor:
    def __init__(self):
        self.model    = None
        self.tfidf    = None
        self.loaded   = False
        self.error    = None

    def load(self):
        try:
            self.model  = joblib.load(_resolve(BENCHMARK_MODEL_PATH, 'ovr_balanced.joblib'))
            self.tfidf  = joblib.load(_resolve(BENCHMARK_TFIDF_PATH, 'tfidf_vectorizer.joblib'))
            self.loaded = True
        except Exception as e:
            self.error  = str(e)
            self.loaded = False

    def predict(self, text: str) -> dict:
        if not self.loaded:
            raise RuntimeError(f'Benchmark non chargรฉ : {self.error}')
        cleaned  = clean_text(text).lower()
        vec      = self.tfidf.transform([cleaned])
        probs    = self.model.predict_proba(vec)[0]
        return {col: float(round(p, 4)) for col, p in zip(LABEL_COLS, probs)}

    def predict_batch(self, texts: list) -> list[dict]:
        if not self.loaded:
            raise RuntimeError(f'Benchmark non chargรฉ : {self.error}')
        cleaned = [clean_text(t).lower() for t in texts]
        vecs    = self.tfidf.transform(cleaned)
        probs   = self.model.predict_proba(vecs)
        return [
            {col: float(round(p, 4)) for col, p in zip(LABEL_COLS, row)}
            for row in probs
        ]


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# XLM-R TEACHER
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
class TeacherPredictor:
    def __init__(self):
        self.model      = None
        self.tokenizer  = None
        self.thresholds = None
        self.loaded     = False
        self.error      = None
        self.device     = None

    def load(self):
        if not TORCH_AVAILABLE:
            self.error  = (
                'PyTorch / Transformers non installรฉs. '
                'Lance : pip install torch transformers sentencepiece'
            )
            self.loaded = False
            return

        try:
            self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

            # 2. Charger le tokenizer โ€” on utilise directement 'xlm-roberta-base'
            # car le tokenizer ne change pas lors du fine-tuning, et les fichiers
            # locaux sont incomplets (sentencepiece.bpe.model manquant).
            self.tokenizer = AutoTokenizer.from_pretrained(TEACHER_MODEL_HF)

            # 3. Reconstruire l'architecture (identique au notebook d'entraรฎnement)
            class TeacherModel(nn.Module):
                def __init__(self, model_name: str, num_labels: int = 6, dropout: float = 0.1):
                    super().__init__()
                    self.encoder    = AutoModel.from_pretrained(model_name)
                    hidden_size     = self.encoder.config.hidden_size
                    self.dropout    = nn.Dropout(dropout)
                    self.classifier = nn.Linear(hidden_size, num_labels)

                def mean_pool(self, token_embeds, attention_mask):
                    mask   = attention_mask.unsqueeze(-1).expand(token_embeds.size()).float()
                    summed = (token_embeds * mask).sum(dim=1)
                    counts = mask.sum(dim=1).clamp(min=1e-9)
                    return summed / counts

                def forward(self, input_ids, attention_mask):
                    outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
                    pooled  = self.mean_pool(outputs.last_hidden_state, attention_mask)
                    pooled  = self.dropout(pooled)
                    return self.classifier(pooled)

            # 4. Charger le checkpoint
            ckpt  = torch.load(_resolve(TEACHER_CKPT_PATH, 'teacher_best.pt'), map_location=self.device, weights_only=False)
            model = TeacherModel(TEACHER_MODEL_HF, num_labels=len(LABEL_COLS))
            model.load_state_dict(ckpt['model_state'])
            model.to(self.device)
            model.eval()
            self.model = model

            # 5. Charger les seuils tunรฉs
            if os.path.exists(TEACHER_THRESH_PATH):
                with open(TEACHER_THRESH_PATH) as f:
                    self.thresholds = json.load(f)
            else:
                # Fallback : seuil 0.5 par dรฉfaut
                self.thresholds = {col: 0.5 for col in LABEL_COLS}

            self.loaded = True

        except Exception as e:
            self.error  = f'{type(e).__name__}: {e}'
            self.loaded = False

    # โ”€โ”€ Infรฉrence : probabilitรฉs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    def predict(self, text: str) -> dict:
        """Retourne les probabilitรฉs sigmoรฏdes par label."""
        if not self.loaded:
            raise RuntimeError(f'Teacher non chargรฉ : {self.error}')

        cleaned  = clean_text(text)
        encoding = self.tokenizer(
            cleaned,
            max_length=TEACHER_MAX_LEN,
            padding='max_length',
            truncation=True,
            return_tensors='pt',
        )
        input_ids = encoding['input_ids'].to(self.device)
        attn_mask = encoding['attention_mask'].to(self.device)

        with torch.no_grad():
            logits = self.model(input_ids, attn_mask)
            probs  = torch.sigmoid(logits).cpu().numpy()[0]

        return {col: float(round(p, 4)) for col, p in zip(LABEL_COLS, probs)}

    # โ”€โ”€ Infรฉrence : labels binaires (avec seuils tunรฉs) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    def predict_with_labels(self, text: str) -> dict:
        """
        Retourne probabilitรฉs + labels binaires selon les seuils tunรฉs.
        Format : {'probs': {...}, 'labels': {...}, 'thresholds': {...}}
        """
        probs  = self.predict(text)
        labels = {col: int(probs[col] >= self.thresholds[col]) for col in LABEL_COLS}
        return {
            'probs'      : probs,
            'labels'     : labels,
            'thresholds' : self.thresholds,
        }

    # โ”€โ”€ Infรฉrence : batch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    def predict_batch(self, texts: list) -> list[dict]:
        """Infรฉrence batch โ€” plus efficace que predict() en boucle."""
        if not self.loaded:
            raise RuntimeError(f'Teacher non chargรฉ : {self.error}')

        cleaned = [clean_text(t) for t in texts]
        encoding = self.tokenizer(
            cleaned,
            max_length=TEACHER_MAX_LEN,
            padding='max_length',
            truncation=True,
            return_tensors='pt',
        )
        input_ids = encoding['input_ids'].to(self.device)
        attn_mask = encoding['attention_mask'].to(self.device)

        with torch.no_grad():
            logits = self.model(input_ids, attn_mask)
            probs  = torch.sigmoid(logits).cpu().numpy()

        return [
            {col: float(round(p, 4)) for col, p in zip(LABEL_COLS, row)}
            for row in probs
        ]


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# XLM-R TEACHER* โ€” adaptรฉ Darija (fine-tunรฉ sur DarLoad, loss masquรฉe)
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
class TeacherStarPredictor:
    def __init__(self):
        self.model          = None
        self.tokenizer      = None
        self.threshold      = 0.45   # seuil tunรฉe sur DarLoad
        self.loaded         = False
        self.error          = None
        self.device         = None

    def load(self):
        if not TORCH_AVAILABLE:
            self.error  = 'PyTorch / Transformers non installรฉs.'
            self.loaded = False
            return

        try:
            self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
            self.tokenizer = AutoTokenizer.from_pretrained(TEACHER_MODEL_HF)

            class TeacherModel(nn.Module):
                def __init__(self, model_name, num_labels=6, dropout=0.1):
                    super().__init__()
                    self.encoder    = AutoModel.from_pretrained(model_name)
                    self.dropout    = nn.Dropout(dropout)
                    self.classifier = nn.Linear(self.encoder.config.hidden_size, num_labels)

                def mean_pool(self, token_embeds, attention_mask):
                    mask   = attention_mask.unsqueeze(-1).expand(token_embeds.size()).float()
                    summed = (token_embeds * mask).sum(dim=1)
                    return summed / mask.sum(dim=1).clamp(min=1e-9)

                def forward(self, input_ids, attention_mask):
                    out    = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
                    pooled = self.mean_pool(out.last_hidden_state, attention_mask)
                    return self.classifier(self.dropout(pooled))

            ckpt  = torch.load(_resolve(TEACHER_STAR_CKPT_PATH, 'teacher_star.pt'), map_location=self.device, weights_only=False)
            model = TeacherModel(TEACHER_MODEL_HF, num_labels=len(LABEL_COLS))
            model.load_state_dict(ckpt['model_state'])
            model.to(self.device)
            model.eval()
            self.model = model

            if os.path.exists(TEACHER_STAR_THRESH_PATH):
                with open(TEACHER_STAR_THRESH_PATH) as f:
                    self.threshold = json.load(f).get('toxic_darija', 0.45)

            self.loaded = True

        except Exception as e:
            self.error  = f'{type(e).__name__}: {e}'
            self.loaded = False

    def predict(self, text: str) -> dict:
        if not self.loaded:
            raise RuntimeError(f'Teacher* non chargรฉ : {self.error}')
        cleaned  = clean_text(text)
        encoding = self.tokenizer(
            cleaned, max_length=TEACHER_STAR_MAX_LEN,
            padding='max_length', truncation=True, return_tensors='pt',
        )
        with torch.no_grad():
            logits = self.model(
                encoding['input_ids'].to(self.device),
                encoding['attention_mask'].to(self.device),
            )
            probs = torch.sigmoid(logits).cpu().numpy()[0]
        return {col: float(round(p, 4)) for col, p in zip(LABEL_COLS, probs)}

    def predict_batch(self, texts: list) -> list[dict]:
        if not self.loaded:
            raise RuntimeError(f'Teacher* non chargรฉ : {self.error}')
        cleaned  = [clean_text(t) for t in texts]
        encoding = self.tokenizer(
            cleaned, max_length=TEACHER_STAR_MAX_LEN,
            padding='max_length', truncation=True, return_tensors='pt',
        )
        with torch.no_grad():
            logits = self.model(
                encoding['input_ids'].to(self.device),
                encoding['attention_mask'].to(self.device),
            )
            probs = torch.sigmoid(logits).cpu().numpy()
        return [{col: float(round(p, 4)) for col, p in zip(LABEL_COLS, row)} for row in probs]


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# FACTORY โ€” chargement unique via st.cache_resource
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
def load_benchmark() -> BenchmarkPredictor:
    p = BenchmarkPredictor()
    p.load()
    return p

def load_teacher() -> TeacherPredictor:
    p = TeacherPredictor()
    p.load()
    return p

def load_teacher_star() -> TeacherStarPredictor:
    p = TeacherStarPredictor()
    p.load()
    return p


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# STUDENT โ€” DistilBERT multilingue spรฉcialisรฉ Darija
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
class StudentPredictor:
    def __init__(self):
        self.model     = None
        self.tokenizer = None
        self.threshold = 0.6
        self.loaded    = False
        self.error     = None
        self.device    = None

    def load(self):
        if not TORCH_AVAILABLE:
            self.error  = 'PyTorch / Transformers non installรฉs.'
            self.loaded = False
            return

        try:
            self.device    = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
            self.tokenizer = AutoTokenizer.from_pretrained(STUDENT_MODEL_HF)

            class StudentModel(nn.Module):
                def __init__(self, model_name, num_labels=6, dropout=0.1):
                    super().__init__()
                    self.encoder    = AutoModel.from_pretrained(model_name)
                    self.dropout    = nn.Dropout(dropout)
                    self.classifier = nn.Linear(self.encoder.config.hidden_size, num_labels)

                def forward(self, input_ids, attention_mask):
                    out    = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
                    pooled = out.last_hidden_state[:, 0, :]  # token [CLS]
                    return self.classifier(self.dropout(pooled))

            ckpt  = torch.load(_resolve(STUDENT_CKPT_PATH, 'student_best.pt'), map_location=self.device, weights_only=False)
            model = StudentModel(STUDENT_MODEL_HF, num_labels=len(LABEL_COLS))
            model.load_state_dict(ckpt['model_state'])
            model.to(self.device)
            model.eval()
            self.model = model

            if os.path.exists(STUDENT_THRESH_PATH):
                with open(STUDENT_THRESH_PATH) as f:
                    self.threshold = json.load(f).get('toxic_darija', 0.35)

            self.loaded = True

        except Exception as e:
            self.error  = f'{type(e).__name__}: {e}'
            self.loaded = False

    def predict(self, text: str) -> dict:
        if not self.loaded:
            raise RuntimeError(f'Student non chargรฉ : {self.error}')
        cleaned  = clean_text(text)
        encoding = self.tokenizer(
            cleaned, max_length=STUDENT_MAX_LEN,
            padding='max_length', truncation=True, return_tensors='pt',
        )
        with torch.no_grad():
            logits = self.model(
                encoding['input_ids'].to(self.device),
                encoding['attention_mask'].to(self.device),
            )
            probs = torch.sigmoid(logits).cpu().numpy()[0]
        return {col: float(round(p, 4)) for col, p in zip(LABEL_COLS, probs)}

    def predict_batch(self, texts: list) -> list[dict]:
        if not self.loaded:
            raise RuntimeError(f'Student non chargรฉ : {self.error}')
        cleaned  = [clean_text(t) for t in texts]
        encoding = self.tokenizer(
            cleaned, max_length=STUDENT_MAX_LEN,
            padding='max_length', truncation=True, return_tensors='pt',
        )
        with torch.no_grad():
            logits = self.model(
                encoding['input_ids'].to(self.device),
                encoding['attention_mask'].to(self.device),
            )
            probs = torch.sigmoid(logits).cpu().numpy()
        return [{col: float(round(p, 4)) for col, p in zip(LABEL_COLS, row)} for row in probs]


def load_student() -> StudentPredictor:
    p = StudentPredictor()
    p.load()
    return p