File size: 24,279 Bytes
b58079c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
617
618
619
620
621
622
"""evaluate_robustness.py

Run robustness evaluation on LipFD: in-memory perturb the bottom face strip
(rows 500: of the 1000x2500 composite) and re-evaluate AUROC / per-fake-vs-real /
fairness. ZERO additional disk: perturbation is applied inside __getitem__,
only the metrics JSON is written.

Perturbation set (paper-aligned, 7 frame-level subset):
  color_saturation | color_contrast | block_wise | gaussian_noise |
  gaussian_blur   | pixelate        | jpeg_quality
Levels: 1..5  (level 1 = no-op for all 7 in SEVERITY, level 5 = heaviest).

Aggregation: clip-level by basename (e.g. '2358_Real', '1681_Fake').
Demographics (gender / race4 / age_group) joined from a CSV that maps
basename -> demo attributes.

============================================================================
Commands actually executed in this session (cwd = /apdcephfs_gy4/share_303628665/joywu/research/LipFD)
============================================================================
# (a) Smoke test 1 — level=1 (no-op) clean baseline:
#     /opt/conda/envs/LipFD/bin/python evaluate_robustness.py \
#         --real_list_path datasets/FairTalking-Bench/test/0_real \
#         --fake_list_path datasets/FairTalking-Bench/test/1_fake \
#         --ckpt          checkpoints/lipfd_train/model_epoch_44.pth \
#         --demographics_csv /apdcephfs_gy4/share_303628665/joywu/research/test.csv \
#         --perturbation gaussian_noise --level 1 \
#         --batch_size 16 --loader_workers 4 --gpu 0 \
#         --save_json /apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustness/runs.json
#     -> overall_clip AUROC=0.9958  AP=0.9956  Acc=0.9484  n_clips=581  n_samples=11610
#
# (b) Smoke test 2 — gaussian_noise level=3 (verify perturbation actually bites):
#     /opt/conda/envs/LipFD/bin/python evaluate_robustness.py \
#         --real_list_path datasets/FairTalking-Bench/test/0_real \
#         --fake_list_path datasets/FairTalking-Bench/test/1_fake \
#         --ckpt          checkpoints/lipfd_train/model_epoch_44.pth \
#         --demographics_csv /apdcephfs_gy4/share_303628665/joywu/research/test.csv \
#         --perturbation gaussian_noise --level 3 \
#         --batch_size 16 --loader_workers 4 --gpu 0 \
#         --save_json /apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustness/runs.json
#     -> overall_clip AUROC=0.9772 (down 0.019)  TPR@1%FPR=0.4966 (down 0.34) — perturbation works
#
# (c) Full sweep (7 perturbations x 5 levels = 35 combos, level=1 only run once):
#     nohup bash run_robustness.sh > robustness/sweep.log 2>&1 &
#     # run_robustness.sh internally calls this script 29 times (1 baseline + 7*4 levels),
#     # appending each run to robustness/runs.json. ~2.7h on a single 100GB-class GPU.

Usage (single perturbation x level):
    python evaluate_robustness.py \
        --real_list_path datasets/FairTalking-Bench/test/0_real \
        --fake_list_path datasets/FairTalking-Bench/test/1_fake \
        --ckpt           checkpoints/lipfd_train/model_epoch_44.pth \
        --demographics_csv /apdcephfs_gy4/share_303628665/joywu/research/test.csv \
        --perturbation gaussian_noise --level 3 \
        --save_json    robustness/runs.json
"""

import argparse
import collections
import csv as _csv
import json
import math
import os
import random as _rng_mod
import re
import sys
import time

import cv2
import numpy as np
import torch
import torchvision.transforms as transforms
from sklearn.metrics import (
    accuracy_score,
    average_precision_score,
    classification_report,
    confusion_matrix,
    roc_auc_score,
    roc_curve,
)
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm

_REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _REPO_ROOT)

from models import build_model  # noqa: E402
import utils as _u  # noqa: E402


# ============================================================================
# Perturbation parameters — verbatim from X-AVDT/train/evaluate_robustness.py
# (originally from AVH-Align/robustness/distortions.py).
# ============================================================================
SEVERITY = {
    "color_saturation":  [1.0,   0.8,   1.2,   1.5,   2.0],
    "color_contrast":    [1.0,   0.85,  1.2,   1.4,   1.6],
    "block_wise":        [0,     8,     16,    24,    32],
    "gaussian_noise":    [0.0,   0.001, 0.005, 0.01,  0.05],
    "gaussian_blur":     [1,     3,     7,     11,    15],
    "pixelate":          [1,     2,     4,     6,     8],
    "jpeg_quality":      [100,   85,    70,    50,    30],
}
PERTURBATIONS = list(SEVERITY.keys())
DEMO_DIMS = ("gender", "race4", "age_group")


# ----- frame-level perturbation primitives (BGR uint8) -----
def _bgr2ycbcr(img_bgr):
    img = img_bgr.astype(np.float32) / 255.0
    M = np.array([
        [ 0.299,    0.587,    0.114],
        [-0.16874, -0.33126,  0.5],
        [ 0.5,    -0.41869, -0.08131],
    ], dtype=np.float32)
    yuv = img @ M.T
    yuv[..., 1:] += 0.5
    return yuv


def _ycbcr2bgr(ycbcr):
    yuv = ycbcr.copy()
    yuv[..., 1:] -= 0.5
    M = np.array([
        [1.0,  0.0,      1.402],
        [1.0, -0.34414, -0.71414],
        [1.0,  1.772,    0.0],
    ], dtype=np.float32)
    return np.clip(yuv @ M.T * 255.0, 0, 255)


def _apply_color_saturation(b, p):
    if abs(p - 1.0) < 1e-6:
        return b
    y = _bgr2ycbcr(b)
    y[..., 1] = 0.5 + (y[..., 1] - 0.5) * p
    y[..., 2] = 0.5 + (y[..., 2] - 0.5) * p
    return np.clip(_ycbcr2bgr(y), 0, 255).astype(np.uint8)


def _apply_color_contrast(b, p):
    if abs(p - 1.0) < 1e-6:
        return b
    return np.clip(b.astype(np.float32) * p, 0, 255).astype(np.uint8)


def _apply_block_wise(b, p, rng):
    if p <= 0:
        return b
    width = 8
    block = np.ones((width, width, 3), dtype=np.uint8) * 128
    n = max(1, min(b.shape[0], b.shape[1]) // 256 * int(p))
    out = b.copy()
    H, W = b.shape[:2]
    for _ in range(n):
        rw = rng.randint(0, W - 1 - width)
        rh = rng.randint(0, H - 1 - width)
        out[rh:rh + width, rw:rw + width, :] = block
    return out


def _apply_gaussian_noise(b, p, rng_np):
    if p <= 0:
        return b
    y = _bgr2ycbcr(b)
    h, w, c = y.shape
    noise = math.sqrt(p) * rng_np.standard_normal((h, w, c)).astype(np.float32)
    return np.clip(_ycbcr2bgr(y + noise), 0, 255).astype(np.uint8)


def _apply_gaussian_blur(b, k):
    k = int(k)
    if k <= 1:
        return b
    if k % 2 == 0:
        k += 1
    return cv2.GaussianBlur(b, (k, k), k / 6.0)


def _apply_pixelate(b, f):
    f = int(f)
    if f <= 1:
        return b
    h, w = b.shape[:2]
    sw, sh = max(1, w // f), max(1, h // f)
    small = cv2.resize(b, (sw, sh), interpolation=cv2.INTER_AREA)
    return cv2.resize(small, (w, h), interpolation=cv2.INTER_LINEAR)


def _apply_jpeg(b, q):
    q = int(q)
    if q >= 100:
        return b
    ok, buf = cv2.imencode(".jpg", b, [int(cv2.IMWRITE_JPEG_QUALITY), q])
    if not ok:
        return b
    dec = cv2.imdecode(buf, cv2.IMREAD_COLOR)
    return dec if dec is not None else b


def perturb_bgr(bgr_uint8, perturbation, level, base_seed=42):
    """Apply perturbation to a single BGR uint8 region. Returns BGR uint8."""
    param = SEVERITY[perturbation][level - 1]
    seed = (hash((base_seed, perturbation, level)) & 0xFFFFFFFF)
    py_rng = _rng_mod.Random(seed)
    np_rng = np.random.RandomState(seed)
    if perturbation == "color_saturation":
        return _apply_color_saturation(bgr_uint8, param)
    elif perturbation == "color_contrast":
        return _apply_color_contrast(bgr_uint8, param)
    elif perturbation == "block_wise":
        return _apply_block_wise(bgr_uint8, param, py_rng)
    elif perturbation == "gaussian_noise":
        return _apply_gaussian_noise(bgr_uint8, param, np_rng)
    elif perturbation == "gaussian_blur":
        return _apply_gaussian_blur(bgr_uint8, param)
    elif perturbation == "pixelate":
        return _apply_pixelate(bgr_uint8, param)
    elif perturbation == "jpeg_quality":
        return _apply_jpeg(bgr_uint8, param)
    raise ValueError(f"unsupported perturbation: {perturbation}")


# ============================================================================
# Wrapper Dataset — replicate AVLip preprocessing, perturbing only the bottom
# face strip (rows 500: of the 1000x2500 composite).
# ============================================================================
_BASENAME_RE = re.compile(r"(\d+_(?:Real|Fake))")


def _extract_basename(img_path):
    """'/.../2358_Real_CelebV-HQ_0.png' -> '2358_Real'
       '/.../EDTalk_1681_Fake_EDTalk_0.png' -> '1681_Fake'."""
    m = _BASENAME_RE.search(os.path.basename(img_path))
    return m.group(1) if m else os.path.basename(img_path).rsplit(".", 1)[0]


def _extract_model_id(img_path, label):
    """Real -> 'Real'; fake -> the prefix model name (EDTalk / Float / SadTalk / ...)."""
    if label == 0:
        return "Real"
    return os.path.basename(img_path).split("_", 1)[0]


class PerturbedAVLip(Dataset):
    """Mirrors data.AVLip preprocessing exactly, but perturbs the bottom 500
    rows (face strip) before slicing into crops at 3 scales."""

    def __init__(self, real_dir, fake_dir, perturbation, level, base_seed=42):
        self.real_list = _u.get_list(real_dir)
        self.fake_list = _u.get_list(fake_dir)
        self.label_dict = {p: 0 for p in self.real_list}
        self.label_dict.update({p: 1 for p in self.fake_list})
        self.total_list = self.real_list + self.fake_list
        self.perturbation = perturbation
        self.level = level
        self.base_seed = base_seed
        self._is_noop = level == 1   # level 1 is no-op for every perturbation

    def __len__(self):
        return len(self.total_list)

    def _read_with_skip(self, idx, tried):
        if len(tried) >= len(self.total_list):
            raise RuntimeError("All samples are corrupted or cannot be read!")
        tried.add(idx)
        path = self.total_list[idx]
        if not os.path.exists(path):
            print(f"WARNING: File not found, skipping: {path}")
            return self._read_with_skip((idx + 1) % len(self.total_list), tried)
        img_cv = cv2.imread(path)
        if img_cv is None:
            print(f"WARNING: Failed to read image, skipping: {path}")
            return self._read_with_skip((idx + 1) % len(self.total_list), tried)
        return img_cv, self.label_dict[path], path

    def __getitem__(self, idx):
        img_cv, label, path = self._read_with_skip(idx, set())   # BGR (H,W,3) uint8

        # ---- perturb only the bottom face strip (rows 500:) ----
        if not self._is_noop:
            face_strip = img_cv[500:, :, :]
            perturbed = perturb_bgr(face_strip, self.perturbation, self.level, self.base_seed)
            img_cv = img_cv.copy()
            img_cv[500:, :, :] = perturbed

        # ---- preprocessing — bit-faithful with data/datasets.py:AVLip.__getitem__ ----
        img = torch.tensor(img_cv, dtype=torch.float32).permute(2, 0, 1)
        # NB: original AVLip computes Normalize(img) then immediately overwrites
        # `crops` with un-normalized strips, so the normalize is dead. We omit it.
        # FIX: 5-crop slicing was `i:i+500 for i in range(5)` (5 near-identical
        # 1-px-shifted views of face0); changed to `i*500:(i+1)*500` so 5 distinct
        # 500x500 face patches reach the model. Same fix in data/datasets.py:64.
        crops = [[transforms.Resize((224, 224))(img[:, 500:, i*500:(i+1)*500]) for i in range(5)], [], []]
        crop_idx = [(28, 196), (61, 163)]
        for i in range(len(crops[0])):
            crops[1].append(transforms.Resize((224, 224))(
                crops[0][i][:, crop_idx[0][0]:crop_idx[0][1], crop_idx[0][0]:crop_idx[0][1]]))
            crops[2].append(transforms.Resize((224, 224))(
                crops[0][i][:, crop_idx[1][0]:crop_idx[1][1], crop_idx[1][0]:crop_idx[1][1]]))
        big = transforms.Resize((1120, 1120))(img)
        return big, crops, label, path


def custom_collate(batch):
    """Same collate as validate.py — flattens the (scales x crops) list-of-tensors
    into per-(scale, crop) batched tensors of shape (B, 3, 224, 224)."""
    imgs = torch.stack([item[0] for item in batch])
    num_scales = len(batch[0][1])
    num_crops = len(batch[0][1][0])
    crops = []
    for s in range(num_scales):
        scale_crops = []
        for c in range(num_crops):
            tensors = [batch[i][1][s][c] for i in range(len(batch))]
            scale_crops.append(torch.stack(tensors))
        crops.append(scale_crops)
    labels = torch.tensor([item[2] for item in batch])
    paths = [item[3] for item in batch]
    return imgs, crops, labels, paths


# ============================================================================
# metric helpers (X-AVDT-compatible)
# ============================================================================
def _tpr_at_fpr(y_true, y_score, fpr_target):
    fpr, tpr, _ = roc_curve(y_true, y_score)
    if (fpr <= fpr_target).any():
        return float(tpr[fpr <= fpr_target].max())
    return 0.0


def _compute_eer_threshold(y_true, y_score):
    fpr, tpr, thresholds = roc_curve(y_true, y_score)
    fnr = 1 - tpr
    return float(thresholds[int(np.argmin(np.abs(fpr - fnr)))])


def _metrics_block(y_true, y_score, threshold=0.5):
    y_true = np.asarray(y_true)
    y_score = np.asarray(y_score)
    y_pred = (y_score >= threshold).astype(int)

    out = {}
    try:
        out["AUROC"] = float(roc_auc_score(y_true, y_score))
    except Exception:
        out["AUROC"] = None
    try:
        out["AP"] = float(average_precision_score(y_true, y_score))
    except Exception:
        out["AP"] = None
    out[f"Accuracy@{threshold:.2f}"] = float(accuracy_score(y_true, y_pred))
    out["Confusion Matrix"] = confusion_matrix(y_true, y_pred, labels=[0, 1]).tolist()
    out["Classification Report"] = classification_report(
        y_true, y_pred, labels=[0, 1], output_dict=True, zero_division=0
    )
    try:
        thr = _compute_eer_threshold(y_true, y_score)
        out["EER_threshold"] = thr
        out["Acc@EER"] = float(accuracy_score(y_true, (y_score >= thr).astype(int)))
    except Exception:
        out["EER_threshold"] = None
        out["Acc@EER"] = None
    try:
        out["TPR@FPR=1%"] = _tpr_at_fpr(y_true, y_score, 0.01)
        out["TPR@FPR=0.1%"] = _tpr_at_fpr(y_true, y_score, 0.001)
    except Exception:
        out["TPR@FPR=1%"] = None
        out["TPR@FPR=0.1%"] = None
    return out


def _fmt4(v):
    try:
        return f"{float(v):.4f}"
    except Exception:
        return "n/a"


def _set_seed(seed):
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False


def load_ckpt(model, ckpt_path):
    ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    state = ckpt.get("model", ckpt) if isinstance(ckpt, dict) else ckpt
    cleaned = collections.OrderedDict()
    for k, v in state.items():
        if k.startswith("module."):
            k = k[len("module."):]
        cleaned[k] = v
    info = model.load_state_dict(cleaned, strict=False)
    out = {"missing_count": len(info.missing_keys),
           "unexpected_count": len(info.unexpected_keys)}
    if not info.missing_keys and not info.unexpected_keys:
        print(f"[OK] Strict checkpoint match: all {len(cleaned)} keys consumed.")
    else:
        print(f"[WARN] missing={len(info.missing_keys)} unexpected={len(info.unexpected_keys)}")
    return out


def compute_fairness(y_true, y_score, groups):
    y_true = np.asarray(y_true)
    y_score = np.asarray(y_score)
    groups = np.asarray(groups)
    pred = (y_score > 0.5).astype(int)

    def _g_fpr(g):
        m = (groups == g) & (y_true == 0)
        return float(pred[m].mean()) if m.sum() else 0.0

    def _g_tpr(g):
        m = (groups == g) & (y_true == 1)
        return float(pred[m].mean()) if m.sum() else 0.0

    def _g_acc(g):
        m = (groups == g)
        return float((pred[m] == y_true[m]).mean()) if m.sum() else 0.0

    def _g_dp(g):
        m = (groups == g)
        return float(pred[m].mean()) if m.sum() else 0.0

    uniq = sorted(set(groups.tolist()))
    if not uniq:
        return None
    fprs = [_g_fpr(g) for g in uniq]
    tprs = [_g_tpr(g) for g in uniq]
    accs = [_g_acc(g) for g in uniq]
    dps  = [_g_dp(g)  for g in uniq]
    ns   = [int((groups == g).sum()) for g in uniq]
    return {
        "F_FPR": float(np.std(fprs)) * 100,
        "F_MEO": (max(max(fprs) - min(fprs), max(tprs) - min(tprs))) * 100,
        "F_DP":  float(np.std(dps))  * 100,
        "F_OAE": float(np.std(accs)) * 100,
        "groups": {g: {"n": n, "fpr": f, "tpr": t, "acc": a, "dp": d}
                   for g, n, f, t, a, d in zip(uniq, ns, fprs, tprs, accs, dps)},
    }


def load_demographics(csv_path):
    out = {}
    with open(csv_path, newline="") as f:
        for row in _csv.DictReader(f):
            base = row["basename"].strip()
            if base:
                out[base] = {
                    "gender":    (row.get("gender") or "").strip(),
                    "race4":     (row.get("race4") or "").strip(),
                    "age_group": (row.get("age_group") or "").strip(),
                }
    return out


# ============================================================================
# main
# ============================================================================
def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("--real_list_path", type=str, required=True)
    p.add_argument("--fake_list_path", type=str, required=True)
    p.add_argument("--ckpt", type=str, required=True)
    p.add_argument("--demographics_csv", type=str, required=True)
    p.add_argument("--perturbation", type=str, required=True, choices=PERTURBATIONS)
    p.add_argument("--level", type=int, required=True, choices=[1, 2, 3, 4, 5])
    p.add_argument("--arch", type=str, default="CLIP:ViT-L/14")
    p.add_argument("--batch_size", type=int, default=8)
    p.add_argument("--loader_workers", type=int, default=4)
    p.add_argument("--gpu", type=int, default=0)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--save_json", type=str, default=None)
    return p.parse_args()


def main():
    args = parse_args()
    _set_seed(args.seed)
    device = torch.device(f"cuda:{args.gpu}" if torch.cuda.is_available() else "cpu")
    print(f"[robustness] perturbation={args.perturbation} level={args.level} "
          f"param={SEVERITY[args.perturbation][args.level - 1]} ckpt={args.ckpt}")

    model = build_model(args.arch)
    load_info = load_ckpt(model, args.ckpt)
    model.to(device).eval()

    demographics = load_demographics(args.demographics_csv)

    dataset = PerturbedAVLip(args.real_list_path, args.fake_list_path,
                             args.perturbation, args.level, args.seed)
    loader = DataLoader(
        dataset, batch_size=args.batch_size, shuffle=False,
        num_workers=args.loader_workers, pin_memory=torch.cuda.is_available(),
        collate_fn=custom_collate,
        persistent_workers=args.loader_workers > 0,
        prefetch_factor=2 if args.loader_workers > 0 else None,
    )

    all_scores, all_labels, all_paths = [], [], []
    with torch.inference_mode():
        for imgs, crops, labels, paths in tqdm(
                loader, desc=f"{args.perturbation}/L{args.level}", leave=False):
            imgs = imgs.to(device)
            crops = [[t.to(device) for t in sc] for sc in crops]
            features = model.get_features(imgs).to(device)
            logits = model(crops, features)[0]
            prob = torch.sigmoid(logits.flatten()).cpu().numpy()
            all_scores.extend(prob.tolist())
            all_labels.extend(labels.numpy().tolist())
            all_paths.extend(paths)

    # ----- clip-level aggregation by basename -----
    bag_scores = collections.defaultdict(list)
    bag_meta = {}
    for path, lab, sc in zip(all_paths, all_labels, all_scores):
        basename = _extract_basename(path)
        bag_scores[basename].append(sc)
        if basename not in bag_meta:
            mid = _extract_model_id(path, lab)
            demo = demographics.get(basename, {"gender": "", "race4": "", "age_group": ""})
            bag_meta[basename] = {"label": int(lab), "model_id": mid, **demo}

    clip_keys = sorted(bag_scores)
    clip_scores = np.array([float(np.mean(bag_scores[k])) for k in clip_keys])
    clip_labels = np.array([bag_meta[k]["label"] for k in clip_keys])
    clip_models = [bag_meta[k]["model_id"] for k in clip_keys]
    clip_demos  = {d: [bag_meta[k][d] for k in clip_keys] for d in DEMO_DIMS}

    result = {
        "perturbation": args.perturbation,
        "level": args.level,
        "param": SEVERITY[args.perturbation][args.level - 1],
        "n_clips": len(clip_keys),
        "n_samples": len(all_scores),
    }

    # overall (clip-level)
    o = _metrics_block(clip_labels.tolist(), clip_scores.tolist())
    o["Accuracy"] = o["Accuracy@0.50"]
    result["overall_clip"] = o

    # per-fake-vs-real (clip-level)
    real_idx = [i for i, y in enumerate(clip_labels) if y == 0]
    real_scores = clip_scores[real_idx].tolist()
    real_labels = clip_labels[real_idx].tolist()

    fake_models = sorted({m for m, l in zip(clip_models, clip_labels) if l == 1})
    per_fake = {}
    for fm in fake_models:
        idxs = [i for i, (m, l) in enumerate(zip(clip_models, clip_labels))
                if m == fm and l == 1]
        joint_s = clip_scores[idxs].tolist() + real_scores
        joint_l = clip_labels[idxs].tolist() + real_labels
        block = _metrics_block(joint_l, joint_s)
        block["Accuracy"] = block["Accuracy@0.50"]
        per_fake[fm] = block
    result["per_fake_vs_real"] = per_fake

    # fairness (whole test, clip-level)
    result["fairness_overall"] = {}
    for d in DEMO_DIMS:
        groups = clip_demos[d]
        valid = [i for i, g in enumerate(groups) if g]
        if not valid:
            continue
        fb = compute_fairness(
            [clip_labels[i] for i in valid],
            [clip_scores[i] for i in valid],
            [groups[i] for i in valid],
        )
        result["fairness_overall"][d] = fb

    # ----- console summary -----
    print(f"\n[{args.perturbation} L{args.level}]  overall_clip "
          f"AUROC={_fmt4(o['AUROC'])} AP={_fmt4(o['AP'])} Acc={_fmt4(o['Accuracy'])} "
          f"Acc@EER={_fmt4(o['Acc@EER'])} TPR@1%FPR={_fmt4(o['TPR@FPR=1%'])} "
          f"TPR@0.1%FPR={_fmt4(o['TPR@FPR=0.1%'])}  "
          f"(n_clips={result['n_clips']} n_samples={result['n_samples']})")
    for fm, blk in per_fake.items():
        print(f"  [{fm}+Real] AUROC={_fmt4(blk['AUROC'])} AP={_fmt4(blk['AP'])} "
              f"Acc={_fmt4(blk['Accuracy'])} Acc@EER={_fmt4(blk['Acc@EER'])}")
    for d in DEMO_DIMS:
        fb = result["fairness_overall"].get(d)
        if fb:
            print(f"  fairness[{d}] F_FPR={fb['F_FPR']:.2f} F_MEO={fb['F_MEO']:.2f} "
                  f"F_DP={fb['F_DP']:.2f} F_OAE={fb['F_OAE']:.2f}")

    # ----- save / append json -----
    if args.save_json:
        os.makedirs(os.path.dirname(args.save_json) or ".", exist_ok=True)
        existing = []
        if os.path.exists(args.save_json):
            try:
                with open(args.save_json) as f:
                    blob = json.load(f)
                existing = blob.get("runs", []) if isinstance(blob, dict) else []
            except Exception:
                existing = []
        run = {
            "ckpt": args.ckpt,
            "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
            "load_info": load_info,
            "real_list_path": args.real_list_path,
            "fake_list_path": args.fake_list_path,
            "demographics_csv": args.demographics_csv,
            "seed": args.seed,
            **result,
        }
        existing.append(run)
        with open(args.save_json, "w") as f:
            json.dump({"runs": existing}, f, indent=2, default=float)
        print(f"\n>>> Appended run to {args.save_json}")


if __name__ == "__main__":
    main()