File size: 22,243 Bytes
eea47ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Robustness evaluation for CTA: in-memory perturb video frames at
inference time, recompute AUROC / AP / Acc / Acc@EER / fairness.

Mirrors X-AVDT/train/evaluate_robustness.py (DeeperForensics-style 6
frame-level perturbations × 5 levels), adapted to CTA's data layer:

    Input difference  : CTA reads mp4 directly via decord/pyav (not pre-extracted .pt)
    Perturbation point: between load_video_clip()  and  video_transform()
                        (i.e., on a (T, 3, H, W) float tensor in [0, 1])
    Audio             : NEVER perturbed (consistent with CTA's "audio is real" framing)

Perturbation set & level table copied verbatim from
/apdcephfs_gy4/share_303628665/joywu/research/X-AVDT/train/evaluate_robustness.py
to keep the comparison apples-to-apples.

Output:
  * console summary per (perturbation, level)
  * append-only JSON to --save_json (one run per CLI invocation)

Usage:
    /opt/conda/envs/pytorch/bin/python scripts/analysis/evaluate_robustness.py \\
        --ckpt outputs/cta_diffusion_combined_20260604_205145/checkpoints/epoch16-valauc1.0000.ckpt \\
        --data fairtalking_diffusion_only \\
        --perturbation gaussian_noise --level 3 \\
        --save_json outputs/analysis/robustness/cta_runs.json

  Or run the whole sweep (6 × 5 = 30 settings) by wrapping in a loop:
    for p in color_saturation color_contrast block_wise gaussian_noise gaussian_blur pixelate; do
      for L in 1 2 3 4 5; do
        python scripts/analysis/evaluate_robustness.py --ckpt ... --data ... \\
          --perturbation $p --level $L --save_json ...
      done
    done
"""
from __future__ import annotations

import argparse
import collections
import csv as _csv
import json
import math
import os
import random as _rng_mod
import sys
import time
from pathlib import Path
from typing import Dict, List, Optional

import cv2
import numpy as np
import torch
import torch.nn.functional as F
from omegaconf import OmegaConf
from sklearn.metrics import (
    accuracy_score, average_precision_score, classification_report,
    confusion_matrix, roc_auc_score, roc_curve,
)
from torch.utils.data import DataLoader
from tqdm import tqdm

# --- silence weights_only restriction (mirror src/train.py)
import lightning_fabric.utilities.cloud_io as _lf_cloud_io
_orig_torch_load = torch.load
def _unsafe_torch_load(*args, **kwargs):
    kwargs["weights_only"] = False
    return _orig_torch_load(*args, **kwargs)
_lf_cloud_io.torch.load = _unsafe_torch_load
torch.load = _unsafe_torch_load

sys.path.insert(0, str(Path(__file__).resolve().parents[2]))

from src.data import FairTalkingDataModule  # noqa: E402
from src.methods import build_method        # noqa: E402


# ============================================================================
# Perturbation table (copy-paste from X-AVDT/train/evaluate_robustness.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],   # JPEG quality factor (lower = stronger compression)
}
PERTURBATIONS = list(SEVERITY.keys())
DEMO_DIMS = ("gender", "race4", "age_group")


# ----- frame-level primitives (operate on uint8 BGR, copied verbatim) -----
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)
    bgr = yuv @ M.T
    return np.clip(bgr * 255.0, 0, 255)


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


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


def _apply_block_wise(frame_bgr, param, rng):
    if param <= 0:
        return frame_bgr
    width = 8
    block = np.ones((width, width, 3), dtype=np.uint8) * 128
    n = max(1, min(frame_bgr.shape[0], frame_bgr.shape[1]) // 256 * int(param))
    out = frame_bgr.copy()
    H, W = frame_bgr.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(frame_bgr, param, rng_np):
    if param <= 0:
        return frame_bgr
    ycbcr = _bgr2ycbcr(frame_bgr)
    h, w, c = ycbcr.shape
    noise = math.sqrt(param) * rng_np.standard_normal((h, w, c)).astype(np.float32)
    noisy = ycbcr + noise
    out = _ycbcr2bgr(noisy)
    return np.clip(out, 0, 255).astype(np.uint8)


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


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


def _apply_jpeg_quality(frame_bgr, quality):
    """JPEG-encode then decode the BGR frame to simulate compression.

    quality is the JPEG quality factor in [1, 100]; higher = better quality
    (less compression). 100 is effectively a no-op.
    """
    quality = int(quality)
    if quality >= 100:
        return frame_bgr
    quality = max(1, min(100, quality))
    encode_params = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
    ok, buf = cv2.imencode(".jpg", frame_bgr, encode_params)
    if not ok:
        return frame_bgr
    decoded = cv2.imdecode(buf, cv2.IMREAD_COLOR)
    return decoded if decoded is not None else frame_bgr


def perturb_video_tensor(video01: torch.Tensor, perturbation: str, level: int,
                         base_seed: int = 42) -> torch.Tensor:
    """video01: (T, 3, H, W) float tensor in [0, 1]. Returns same shape/dtype.

    Internally:
      1) (T,3,H,W) float [0,1]  ->  (T,H,W,3) uint8 RGB
      2) Per frame: RGB->BGR, apply perturbation, BGR->RGB
      3) (T,H,W,3) uint8 RGB    ->  (T,3,H,W) float [0,1]
    """
    if level == 1:
        return video01     # short-circuit: SEVERITY[*][0] is a no-op
    param = SEVERITY[perturbation][level - 1]

    seed = (hash((base_seed, perturbation, level)) & 0xFFFFFFFF)
    py_rng = _rng_mod.Random(seed)
    np_rng = np.random.RandomState(seed)

    # tensor -> numpy uint8 RGB (T,H,W,3)
    arr = video01.detach().cpu().numpy()           # (T,3,H,W) float
    arr = (arr * 255.0).clip(0, 255).astype(np.uint8)
    arr = np.transpose(arr, (0, 2, 3, 1))           # (T,H,W,3) RGB

    out = np.empty_like(arr)
    for t in range(arr.shape[0]):
        bgr = cv2.cvtColor(arr[t], cv2.COLOR_RGB2BGR)
        if perturbation == "color_saturation":
            bgr = _apply_color_saturation(bgr, param)
        elif perturbation == "color_contrast":
            bgr = _apply_color_contrast(bgr, param)
        elif perturbation == "block_wise":
            bgr = _apply_block_wise(bgr, param, py_rng)
        elif perturbation == "gaussian_noise":
            bgr = _apply_gaussian_noise(bgr, param, np_rng)
        elif perturbation == "gaussian_blur":
            bgr = _apply_gaussian_blur(bgr, param)
        elif perturbation == "pixelate":
            bgr = _apply_pixelate(bgr, param)
        elif perturbation == "jpeg_quality":
            bgr = _apply_jpeg_quality(bgr, param)
        else:
            raise ValueError(f"unsupported perturbation: {perturbation}")
        out[t] = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)

    # numpy uint8 RGB -> tensor [0,1]
    out = np.transpose(out, (0, 3, 1, 2))           # (T,3,H,W)
    return torch.from_numpy(out.astype(np.float32) / 255.0).to(video01.device)


# ============================================================================
# Wrapper transform: insert perturbation BEFORE the existing transform
# ============================================================================
class PerturbedVideoTransform:
    """Wrap an existing VideoTransform. Apply perturbation in [0,1] domain
    first, then delegate to the underlying transform (which crops/normalizes)."""

    def __init__(self, base_transform, perturbation: str, level: int,
                 base_seed: int = 42):
        self.base = base_transform
        self.perturbation = perturbation
        self.level = level
        self.base_seed = base_seed

    def __call__(self, video):
        if self.level != 1:
            video = perturb_video_tensor(
                video, self.perturbation, self.level, self.base_seed,
            )
        if self.base is not None:
            video = self.base(video)
        return video


# ============================================================================
# Metric helpers (copy from X-AVDT)
# ============================================================================
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: out["AUROC"] = None
    try:    out["AP"] = float(average_precision_score(y_true, y_score))
    except: 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:
        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:
        out["TPR@FPR=1%"] = None; out["TPR@FPR=0.1%"] = None
    return out


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


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: Optional[str]) -> Dict[str, Dict[str, str]]:
    if not csv_path or not os.path.exists(csv_path):
        return {}
    out = {}
    with open(csv_path, newline="") as f:
        for row in _csv.DictReader(f):
            base = (row.get("basename") or "").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


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


# ============================================================================
# main
# ============================================================================
def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("--ckpt", type=str, required=True)
    p.add_argument("--data", type=str, default="fairtalking_diffusion_only",
                   help="hydra data config name (without .yaml)")
    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("--batch_size", type=int, default=8)
    p.add_argument("--num_workers", type=int, default=4)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--demographics_csv", type=str, default=None,
                   help="optional CSV with basename,race4,gender,age_group "
                        "for fairness; if omitted, fairness section is skipped")
    p.add_argument("--save_json", type=str, default=None)
    p.add_argument("--verbose", action="store_true",
                   help="Also print per-fake-vs-real and fairness blocks to "
                        "stdout. JSON always contains them regardless.")
    return p.parse_args()


def main():
    args = parse_args()
    _set_seed(args.seed)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    # ---- model ckpt -> infer the method/data/backbone configs ---------------
    print(f"[robustness] ckpt: {args.ckpt}")
    print(f"[robustness] data config: {args.data}")
    print(f"[robustness] perturbation={args.perturbation}  level={args.level}  "
          f"param={SEVERITY[args.perturbation][args.level - 1]}")

    state = torch.load(args.ckpt, map_location="cpu")
    hp = state.get("hyper_parameters", {})
    if not hp:
        raise SystemExit("ckpt has no hyper_parameters; cannot rebuild model")
    method_cfg = OmegaConf.create(hp["method_cfg"])
    backbone_cfg = OmegaConf.create(hp["backbone_cfg"])

    # ---- build target data config (from yaml) ------------------------------
    data_cfg_path = Path("configs/data") / f"{args.data}.yaml"
    if not data_cfg_path.exists():
        raise SystemExit(f"data config not found: {data_cfg_path}")
    data_cfg = OmegaConf.load(data_cfg_path)
    # resolve env vars in cfg (DATA_ROOT, MMDF_ROOT, ...)
    os.environ.setdefault("DATA_ROOT",
        "/apdcephfs_gy4/share_303628665/joywu/dataset/FairTalking-Bench")
    os.environ.setdefault("HDTF_PAIRED_ROOT",
        "/apdcephfs_gy5/share_303628665/joyewu/HDTF-paird")
    os.environ.setdefault("MMDF_ROOT",
        "/apdcephfs_gy4/share_303628665/joywu/dataset/MMDF_test_only")
    data_cfg = OmegaConf.create(OmegaConf.to_container(data_cfg, resolve=True))

    # ---- build model + load ckpt -------------------------------------------
    model = build_method(
        method_name=method_cfg.name,
        method_cfg=method_cfg,
        backbone_cfg=backbone_cfg,
        data_cfg=data_cfg,
    )
    sd = state.get("state_dict", state)
    missing, unexpected = model.load_state_dict(sd, strict=False)
    if missing:    print(f"  missing keys: {len(missing)} (first 3: {missing[:3]})")
    if unexpected: print(f"  unexpected keys: {len(unexpected)}")
    model.to(device).eval()

    # ---- build datamodule, then patch eval_transform with perturbation ----
    dm = FairTalkingDataModule(data_cfg=data_cfg, return_paired=False)
    base_eval_transform = dm.eval_transform
    dm.eval_transform = PerturbedVideoTransform(
        base_eval_transform, args.perturbation, args.level, args.seed,
    )
    dm.setup(stage="test")
    loader = DataLoader(
        dm.test_ds, batch_size=args.batch_size, shuffle=False,
        num_workers=args.num_workers, pin_memory=torch.cuda.is_available(),
        collate_fn=getattr(dm, "_collate_fn",
                           __import__("src.data.datamodule", fromlist=["_collate_drop_none"])._collate_drop_none),
    )

    # ---- demographics (optional) -------------------------------------------
    demographics = load_demographics(args.demographics_csv)

    # ---- forward -----------------------------------------------------------
    scores, labels, basenames, generators = [], [], [], []
    with torch.inference_mode():
        for batch in tqdm(loader, desc=f"{args.perturbation}/L{args.level}", leave=False):
            if batch is None:
                continue
            batch_video = batch["video"].to(device, dtype=torch.float)
            batch_audio = batch["audio"].to(device, dtype=torch.float)
            score = model.score({"video": batch_video, "audio": batch_audio})
            scores.extend(score.detach().cpu().float().numpy().tolist())
            labels.extend(batch["label"].long().tolist())
            metas = batch.get("meta", [])
            for m in metas:
                basenames.append(str((m or {}).get("basename", "")))
                generators.append(str((m or {}).get("generator", "")))

    # ---- metrics: overall + per-fake-vs-real -------------------------------
    result = {
        "perturbation": args.perturbation,
        "level": args.level,
        "param": SEVERITY[args.perturbation][args.level - 1],
        "n_samples": len(scores),
    }
    o = _metrics_block(labels, scores)
    o["Accuracy"] = o["Accuracy@0.50"]
    result["overall"] = o

    # per-fake-vs-real (clip-level), only if generator info exists
    real_idx  = [i for i, y in enumerate(labels) if y == 0]
    real_sc   = [scores[i] for i in real_idx]
    real_lab  = [labels[i] for i in real_idx]
    fake_gens = sorted({generators[i] for i, y in enumerate(labels) if y == 1 and generators[i]})
    per_fake = {}
    for fm in fake_gens:
        idxs = [i for i, (g, y) in enumerate(zip(generators, labels)) if g == fm and y == 1]
        joint_sc  = [scores[i] for i in idxs] + real_sc
        joint_lab = [labels[i] for i in idxs] + real_lab
        block = _metrics_block(joint_lab, joint_sc)
        block["Accuracy"] = block["Accuracy@0.50"]
        per_fake[fm] = block
    result["per_fake_vs_real"] = per_fake

    # fairness (overall, by demographic dim) ----------------------------------
    fairness_overall = {}
    if demographics:
        for d in DEMO_DIMS:
            groups = [demographics.get(b, {}).get(d, "") for b in basenames]
            valid = [i for i, g in enumerate(groups) if g]
            if not valid:
                continue
            fb = compute_fairness(
                [labels[i]  for i in valid],
                [scores[i]  for i in valid],
                [groups[i]  for i in valid],
            )
            fairness_overall[d] = fb
    result["fairness_overall"] = fairness_overall

    # ---- console summary ---------------------------------------------------
    print(f"\n[{args.perturbation} L{args.level}]  AUROC={_fmt4(o['AUROC'])} "
          f"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%'])}  n={result['n_samples']}")
    if args.verbose:
        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 = 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"),
            "data_config": args.data,
            "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()