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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# ============================================================
# TEST / INFERENCE RIÊNG
# Load toàn bộ model đã train và dự đoán dữ liệu mới
# ============================================================

!pip -q install -U transformers accelerate scikit-learn scipy joblib sentencepiece

import os
import re
import gc
import math
import joblib

import numpy as np
import pandas as pd
import torch

from pathlib import Path
from scipy import sparse
from scipy.special import softmax

from sklearn.feature_extraction.text import TfidfVectorizer

from transformers import (
    AutoTokenizer,
    AutoModelForSequenceClassification,
)

from torch.utils.data import Dataset, DataLoader


# ============================================================
# 1. PATH
# ============================================================

# Thư mục model đã train ở notebook trước
WORK_DIR = Path(
    "/content/drive/MyDrive/rvihsd_stacking_work"
)

# File dữ liệu MỚI cần dự đoán
TEST_CSV = "/content/drive/MyDrive/new_test.csv"

# File kết quả
OUTPUT_CSV = "/content/drive/MyDrive/new_test_prediction.csv"


# ============================================================
# 2. CONFIG
# ============================================================

MAX_LENGTH = 128
BATCH_SIZE = 64

LABELS = [
    "CLEAN",
    "OFFENSIVE",
    "HATE",
]

NOISE_LABELS = [
    "ORIGINAL",
    "NO_DIACRITICS",
    "TEENCODE",
    "CHAR_REPEAT",
    "PUNCT_NOISE",
    "OBFUSCATION",
    "MIXED",
]

id2label = {
    i: x
    for i, x in enumerate(LABELS)
}

id2noise = {
    i: x
    for i, x in enumerate(NOISE_LABELS)
}


# ============================================================
# 3. CLASS DualTfidf
#    PHẢI CÓ vì joblib cần class này khi load vectorizer
# ============================================================

class DualTfidf:

    def __init__(self):
        self.char = None
        self.word = None

    def transform(self, texts):

        texts = (
            pd.Series(texts)
            .fillna("")
            .astype(str)
            .tolist()
        )

        Xc = self.char.transform(texts)
        Xw = self.word.transform(texts)

        return sparse.hstack(
            [Xc, Xw],
            format="csr",
            dtype=np.float32,
        )


# ============================================================
# 4. SURFACE FEATURES
#    PHẢI GIỐNG HỆT LÚC TRAIN META-MODEL
# ============================================================

VI_DIACRITICS = set(
    "ăâđêôơưáàảãạắằẳẵặấầẩẫậ"
    "éèẻẽẹếềểễệ"
    "íìỉĩị"
    "óòỏõọốồổỗộớờởỡợ"
    "úùủũụứừửữự"
    "ýỳỷỹỵ"
    "ĂÂĐÊÔƠƯÁÀẢÃẠẮẰẲẴẶẤẦẨẪẬ"
    "ÉÈẺẼẸẾỀỂỄỆ"
    "ÍÌỈĨỊ"
    "ÓÒỎÕỌỐỒỔỖỘỚỜỞỠỢ"
    "ÚÙỦŨỤỨỪỬỮỰ"
    "ÝỲỶỸỴ"
)


def meta_surface_features(texts):

    rows = []

    for text in texts:

        s = str(text)

        n = max(len(s), 1)

        alpha = max(
            sum(ch.isalpha() for ch in s),
            1
        )

        punct = sum(
            (not ch.isalnum())
            and
            (not ch.isspace())
            for ch in s
        )

        diac = sum(
            ch in VI_DIACRITICS
            for ch in s
        )

        repeats = len(
            re.findall(
                r"(.)\1{2,}",
                s.lower()
            )
        )

        obfus = len(
            re.findall(
                r"(?<=[A-Za-zÀ-ỹ])[.*_~](?=[A-Za-zÀ-ỹ])",
                s
            )
        )

        rows.append([
            math.log1p(len(s)),
            punct / n,
            diac / alpha,
            min(repeats, 10) / 10.0,
            min(obfus, 10) / 10.0,
        ])

    return np.asarray(
        rows,
        dtype=np.float32
    )


# ============================================================
# 5. KIỂM TRA MODEL FILE
# ============================================================

VISO_DIR = WORK_DIR / "visobert_full"

VECTORIZER_PATH = (
    WORK_DIR / "full_vectorizer.joblib"
)

HATE_SVM_PATH = (
    WORK_DIR / "full_hate_svm.joblib"
)

NOISE_SVM_PATH = (
    WORK_DIR / "full_noise_svm.joblib"
)

META_PATH = (
    WORK_DIR / "meta_model.joblib"
)


required = [
    VISO_DIR / "config.json",
    VECTORIZER_PATH,
    HATE_SVM_PATH,
    NOISE_SVM_PATH,
    META_PATH,
]

for p in required:

    if not p.exists():
        raise FileNotFoundError(
            f"Không tìm thấy: {p}"
        )

print("Tất cả model files đều tồn tại.")


# ============================================================
# 6. LOAD TF-IDF + SVM + META MODEL
# ============================================================

print("\nLoading TF-IDF/SVM...")

full_vec = joblib.load(
    VECTORIZER_PATH
)

full_hate_svm = joblib.load(
    HATE_SVM_PATH
)

full_noise_svm = joblib.load(
    NOISE_SVM_PATH
)

meta_model = joblib.load(
    META_PATH
)

print("TF-IDF/SVM/meta-model loaded.")


# ============================================================
# 7. LOAD ViSoBERT
# ============================================================

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

print("\nDevice:", device)

print("Loading ViSoBERT...")

tokenizer = AutoTokenizer.from_pretrained(
    VISO_DIR
)

visobert = (
    AutoModelForSequenceClassification
    .from_pretrained(VISO_DIR)
)

visobert.to(device)
visobert.eval()

print("ViSoBERT loaded.")


# ============================================================
# 8. DATASET CHO ViSoBERT
# ============================================================

class TestDataset(Dataset):

    def __init__(self, texts):

        self.texts = (
            pd.Series(texts)
            .fillna("")
            .astype(str)
            .tolist()
        )

    def __len__(self):

        return len(self.texts)

    def __getitem__(self, idx):

        return self.texts[idx]


# ============================================================
# 9. ViSoBERT INFERENCE
# ============================================================

def predict_visobert(
    texts,
    batch_size=BATCH_SIZE
):

    dataset = TestDataset(texts)

    loader = DataLoader(
        dataset,
        batch_size=batch_size,
        shuffle=False,
    )

    all_probs = []

    with torch.no_grad():

        for batch_texts in loader:

            enc = tokenizer(
                list(batch_texts),
                padding=True,
                truncation=True,
                max_length=MAX_LENGTH,
                return_tensors="pt",
            )

            enc = {
                k: v.to(device)
                for k, v in enc.items()
            }

            outputs = visobert(**enc)

            probs = torch.softmax(
                outputs.logits,
                dim=1
            )

            all_probs.append(
                probs.cpu().numpy()
            )

    return np.concatenate(
        all_probs,
        axis=0
    ).astype(np.float32)


# ============================================================
# 10. LOAD TEST DATA
# ============================================================

test_df = pd.read_csv(
    TEST_CSV,
    dtype={"id": str}
)

required_cols = {
    "id",
    "text",
}

missing = required_cols - set(
    test_df.columns
)

if missing:
    raise ValueError(
        f"File test thiếu cột: {missing}"
    )

test_df = test_df[
    ["id", "text"]
].copy()

test_df["id"] = (
    test_df["id"]
    .astype(str)
)

test_df["text"] = (
    test_df["text"]
    .fillna("")
    .astype(str)
)

print(
    "\nSố mẫu test:",
    len(test_df)
)

display(
    test_df.head()
)


# ============================================================
# 11. TF-IDF
# ============================================================

print("\n[1/4] TF-IDF...")

X_test = full_vec.transform(
    test_df["text"]
)

print(
    "TF-IDF shape:",
    X_test.shape
)


# ============================================================
# 12. SVM PREDICTIONS
# ============================================================

print("\n[2/4] SVM inference...")

hate_svm_score = (
    full_hate_svm
    .decision_function(X_test)
    .astype(np.float32)
)

noise_score = (
    full_noise_svm
    .decision_function(X_test)
    .astype(np.float32)
)

noise_soft = softmax(
    noise_score,
    axis=1
).astype(np.float32)

print(
    "Hate SVM:",
    hate_svm_score.shape
)

print(
    "Noise SVM:",
    noise_score.shape
)


# ============================================================
# 13. ViSoBERT
# ============================================================

print("\n[3/4] ViSoBERT inference...")

viso_prob = predict_visobert(
    test_df["text"]
)

print(
    "ViSoBERT:",
    viso_prob.shape
)


# ============================================================
# 14. META SURFACE FEATURES
# ============================================================

surface = meta_surface_features(
    test_df["text"]
)

print(
    "Surface:",
    surface.shape
)


# ============================================================
# 15. STACKING
#
# Thứ tự PHẢI giống lúc train:
#
# ViSoBERT probability = 3
# SVM hate score       = 3
# noise softmax        = 7
# surface              = 5
#
# Tổng = 18 features
# ============================================================

print("\n[4/4] Stacking...")

meta_X = np.hstack([
    viso_prob,
    hate_svm_score,
    noise_soft,
    surface,
]).astype(np.float32)

print(
    "Meta feature shape:",
    meta_X.shape
)

assert meta_X.shape[1] == 18


# Hate classification
hate_pred_id = meta_model.predict(
    meta_X
).astype(int)

# Noise classification
noise_pred_id = noise_score.argmax(
    axis=1
)


# ============================================================
# 16. CHUYỂN ID -> LABEL
# ============================================================

pred_label = [
    id2label[int(x)]
    for x in hate_pred_id
]

pred_noise = [
    id2noise[int(x)]
    for x in noise_pred_id
]


# ============================================================
# 17. TẠO OUTPUT
# ============================================================

output = pd.DataFrame({

    "id":
        test_df["id"].values,

    "pred_label":
        pred_label,

    "pred_noise_type":
        pred_noise,
})


# ============================================================
# 18. KIỂM TRA
# ============================================================

assert len(output) == len(test_df)

assert output["id"].is_unique

assert set(
    output["pred_label"]
).issubset(LABELS)

assert set(
    output["pred_noise_type"]
).issubset(NOISE_LABELS)


print("\nPrediction distribution:")

print(
    "\nLABEL:"
)

print(
    output["pred_label"]
    .value_counts()
)

print(
    "\nNOISE:"
)

print(
    output["pred_noise_type"]
    .value_counts()
)


# ============================================================
# 19. SAVE
# ============================================================

output.to_csv(
    OUTPUT_CSV,
    index=False,
    encoding="utf-8",
)

print(
    "\nSaved:",
    OUTPUT_CSV
)

display(
    output.head(20)
)