File size: 26,944 Bytes
54d2b91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
"""FairTalking-Bench dataset classes.

File layout assumed:
    <root>/Real/<basename>_Real_<source>.mp4
    <root>/<Generator>/<basename_num>_Fake_<Generator>.mp4       (e.g. Float/0001_Fake_Float.mp4)
    <root>/{train,val,test}.csv    with columns:
        basename, Label, gender, race4, age_group,
        duration_range, duration_seconds, source, basename_old

    where `basename` is like "0022_Fake" or "0852_Real" (no extension, no source suffix).

Key notes (from user):
  * Real and Fake identities are DIFFERENT in the main benchmark.
  * Within the 8 generator dirs, the same numeric prefix (e.g. "0000")
    shares the same reference image and driving audio across all 8 generators.
  * Audio is embedded in the mp4; we extract wavs once into <root>/_audio/
    via scripts/prepare_audio.sh for fast loading.
"""
from __future__ import annotations

import json
import os
import random
import warnings
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple

import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset

# --- video reading -----------------------------------------------------------
try:
    import decord
    decord.bridge.set_bridge("torch")
    _HAS_DECORD = True
except Exception:  # pragma: no cover
    _HAS_DECORD = False

import soundfile as sf


GENERATORS = (
    "AniPortrait", "Ditto", "EDTalk", "Float",
    "Hallo", "Joyvasa", "SadTalk", "Sonic",
)

# Some generator directories use a different casing for the *file-name* suffix
# than the directory name itself (Linux FS is case-sensitive). Only Joyvasa is
# affected today: dir="Joyvasa" but files are named "XXXX_Fake_JoyVASA.mp4".
GEN_FILE_SUFFIX_ALIAS: Dict[str, str] = {
    "Joyvasa": "JoyVASA",
}


def _fake_filename(num: str, gen: str) -> str:
    """Return '<num>_Fake_<suffix>.mp4' where <suffix> honors the alias table."""
    return f"{num}_Fake_{GEN_FILE_SUFFIX_ALIAS.get(gen, gen)}.mp4"

# =============================================================================
# helpers
# =============================================================================

def _load_video_clip_decord(
    path: str, num_frames: int, stride: int, frame_size: int,
) -> torch.Tensor:
    """Return (T, 3, H, W) float in [0,1]. Uniformly random-offset clip."""
    vr = decord.VideoReader(path, width=frame_size, height=frame_size)
    total = len(vr)
    span = (num_frames - 1) * stride + 1
    if total < span:
        # not enough frames: repeat-pad
        idx = np.arange(num_frames) * stride
        idx = np.clip(idx, 0, total - 1)
    else:
        start = random.randint(0, total - span)
        idx = start + np.arange(num_frames) * stride
    frames = vr.get_batch(idx.tolist())          # (T, H, W, 3) uint8 torch
    frames = frames.float().permute(0, 3, 1, 2) / 255.0
    return frames


def _load_video_clip_pyav(
    path: str, num_frames: int, stride: int, frame_size: int,
) -> torch.Tensor:
    import av
    container = av.open(path)
    stream = container.streams.video[0]
    stream.codec_context.skip_frame = "NONKEY"
    frames = []
    for i, frame in enumerate(container.decode(video=0)):
        img = frame.to_ndarray(format="rgb24")
        frames.append(img)
    container.close()
    if not frames:
        raise RuntimeError(f"no frames decoded for {path}")
    arr = np.stack(frames)
    total = len(arr)
    span = (num_frames - 1) * stride + 1
    if total < span:
        idx = np.arange(num_frames) * stride
        idx = np.clip(idx, 0, total - 1)
    else:
        start = random.randint(0, total - span)
        idx = start + np.arange(num_frames) * stride
    arr = arr[idx]
    import cv2
    resized = np.stack([cv2.resize(f, (frame_size, frame_size)) for f in arr])
    t = torch.from_numpy(resized).float().permute(0, 3, 1, 2) / 255.0
    return t


def load_video_clip(
    path: str, num_frames: int, stride: int, frame_size: int,
) -> torch.Tensor:
    if _HAS_DECORD:
        try:
            return _load_video_clip_decord(path, num_frames, stride, frame_size)
        except Exception as e:  # pragma: no cover
            warnings.warn(f"decord failed on {path}: {e}; falling back to pyav")
    return _load_video_clip_pyav(path, num_frames, stride, frame_size)


def load_audio_clip(
    wav_path: str, seconds: float, sample_rate: int,
) -> torch.Tensor:
    """Return (num_samples,) float32. Uniform random crop."""
    wav, sr = sf.read(wav_path, dtype="float32", always_2d=False)
    if wav.ndim > 1:
        wav = wav.mean(axis=1)
    if sr != sample_rate:
        # lightweight resample
        import librosa
        wav = librosa.resample(wav, orig_sr=sr, target_sr=sample_rate)
    target = int(seconds * sample_rate)
    if len(wav) < target:
        pad = target - len(wav)
        wav = np.pad(wav, (0, pad), mode="constant")
    else:
        start = random.randint(0, len(wav) - target)
        wav = wav[start:start + target]
    return torch.from_numpy(wav.copy())


# =============================================================================
# path resolution
# =============================================================================

@dataclass
class FileResolver:
    """Turns a csv row into video / audio paths."""
    root: Path
    audio_cache_dir: Path

    def video_path(self, row: pd.Series) -> str:
        basename: str = row["basename"]           # "0022_Fake" or "0852_Real"
        num, kind = basename.split("_", 1)
        if kind.lower() == "real":
            # real files carry source suffix we do not know, so glob
            candidates = list((self.root / "Real").glob(f"{num}_Real_*.mp4"))
            if not candidates:
                raise FileNotFoundError(f"no real video for {basename}")
            return str(candidates[0])
        elif kind.lower() == "fake":
            # fake: need a generator. csv doesn't encode it, so caller must.
            # We store generator on the row dict if iterating generators.
            gen = row.get("generator") or row.get("_generator")
            if gen is None:
                raise ValueError(
                    "fake row must carry a 'generator' column for path resolution"
                )
            return str(self.root / gen / _fake_filename(num, gen))
        else:
            raise ValueError(f"unknown label kind in basename: {basename}")

    def audio_path(self, video_path: str) -> str:
        vp = Path(video_path)
        # mirror the tree inside audio_cache_dir
        rel = vp.relative_to(self.root)
        return str(self.audio_cache_dir / rel.with_suffix(".wav"))


# =============================================================================
# main dataset (FairTalking-Bench balanced main split)
# =============================================================================

class FairTalkingBenchDataset(Dataset):
    """
    Returns per sample:
        video:   (T, 3, H, W) float
        audio:   (S,) float
        label:   int in {0=real, 1=fake}
        meta:    dict with demographic info + generator + basename
    """

    def __init__(
        self,
        root: str,
        split_csv: str,
        audio_cache_dir: str,
        generators: Sequence[str] = GENERATORS,
        num_frames: int = 16,
        frame_stride: int = 2,
        frame_size: int = 224,
        audio_seconds: float = 2.56,
        audio_sample_rate: int = 16000,
        video_transform: Optional[Callable] = None,
        return_paired: bool = False,
        expand_fakes: str = "random",   # "random": pick 1 generator per fake row
                                         # "all":    explode into 8 rows (for eval)
    ) -> None:
        super().__init__()
        self.root = Path(root)
        self.resolver = FileResolver(
            root=self.root,
            audio_cache_dir=Path(audio_cache_dir),
        )
        self.generators = tuple(generators)
        self.num_frames = num_frames
        self.frame_stride = frame_stride
        self.frame_size = frame_size
        self.audio_seconds = audio_seconds
        self.audio_sample_rate = audio_sample_rate
        self.video_transform = video_transform
        self.return_paired = return_paired
        self.expand_fakes = expand_fakes

        df = pd.read_csv(self.root / split_csv)
        df = df[df["basename"].notna()].copy()
        df["_num"] = df["basename"].str.extract(r"^(\d+)_")[0]
        df["_kind"] = df["basename"].str.extract(r"_(Real|Fake)$")[0]

        if expand_fakes == "all":
            # explode each fake row into 8 generator copies
            reals = df[df["_kind"] == "Real"].copy()
            reals["_generator"] = None
            fakes = df[df["_kind"] == "Fake"]
            expanded = []
            for g in self.generators:
                tmp = fakes.copy()
                tmp["_generator"] = g
                expanded.append(tmp)
            df = pd.concat([reals] + expanded, ignore_index=True)

        self.df = df.reset_index(drop=True)

    # ------------------------------------------------------------------
    def __len__(self) -> int:
        return len(self.df)

    def _resolve_row(self, row: pd.Series) -> Tuple[str, str]:
        row = row.copy()
        if row["_kind"] == "Fake":
            gen = row["_generator"] if "_generator" in row.index else None
            if gen is None:
                # try generators in random order, pick the first whose file exists
                cand = list(self.generators)
                random.shuffle(cand)
                for g in cand:
                    p = self.root / g / _fake_filename(str(row['_num']), g)
                    if p.exists():
                        gen = g
                        break
                if gen is None:
                    raise FileNotFoundError(
                        f"no fake file found for basename={row['basename']} among any generator"
                    )
            row["_generator"] = gen
            row["generator"] = gen
        # Real rows: no generator, FileResolver handles that branch directly.
        vpath = self.resolver.video_path(row)
        apath = self.resolver.audio_path(vpath)
        return vpath, apath

    def _load_sample(self, vpath: str, apath: str) -> Tuple[torch.Tensor, torch.Tensor]:
        video = load_video_clip(
            vpath, self.num_frames, self.frame_stride, self.frame_size,
        )
        if self.video_transform is not None:
            video = self.video_transform(video)
        if os.path.exists(apath):
            audio = load_audio_clip(
                apath, self.audio_seconds, self.audio_sample_rate,
            )
        else:
            # silent fallback if audio extraction wasn't done yet
            warnings.warn(f"missing audio cache: {apath}; returning silence")
            audio = torch.zeros(int(self.audio_seconds * self.audio_sample_rate))
        return video, audio

    # ------------------------------------------------------------------
    def __getitem__(self, idx: int) -> Dict[str, Any]:
        row = self.df.iloc[idx]
        try:
            vpath, apath = self._resolve_row(row)
            video, audio = self._load_sample(vpath, apath)
        except Exception as e:
            # robust dataloader: skip broken samples
            warnings.warn(f"skipping bad sample idx={idx} basename={row['basename']}: {e}")
            # return random other idx
            return self.__getitem__((idx + 1) % len(self))

        label = int(row["Label"])

        gen_val = ""
        if row["_kind"] == "Fake" and "_generator" in row.index:
            gen_val = row["_generator"] or ""

        sample: Dict[str, Any] = {
            "video": video,
            "audio": audio,
            "label": label,
            "meta": {
                "basename": str(row["basename"]),
                "generator": str(gen_val),
                "gender": str(row.get("gender") or ""),
                "race4": str(row.get("race4") or ""),
                "age_group": str(row.get("age_group") or ""),
                "source": str(row.get("source") or ""),
                "num": str(row.get("_num") or ""),
            },
        }

        # --- optional: cross-generator paired companion (for CTA aux loss) ----
        if self.return_paired and row["_kind"] == "Fake" and gen_val:
            other_gens = [g for g in self.generators if g != gen_val]
            other = random.choice(other_gens)
            alt_row = row.copy()
            alt_row["_generator"] = other
            alt_row["generator"] = other
            try:
                avpath = self.resolver.video_path(alt_row)
                aapath = self.resolver.audio_path(avpath)
                alt_video, alt_audio = self._load_sample(avpath, aapath)
                sample["alt_video"] = alt_video
                sample["alt_audio"] = alt_audio
                sample["meta"]["alt_generator"] = other
            except Exception:
                pass

        return sample


# =============================================================================
# HDTF identity-paired subsets (Protocol 4)
# =============================================================================

class HDTFIdPairedDataset(Dataset):
    """
    Reads a csv produced by scripts/prepare_hdtf_splits.py. Expected columns:
        basename_num, identity_id, subset  (A|B|C)

    For each identity_id we build a tuple:
        { 'real': path_to_real_mp4,
          'fakes': { g: path_to_g_fake_mp4 for g in generators } }

    __getitem__ returns either a (real, fake) pair [sampled generator] or
    the full 9-tuple depending on mode.
    """

    def __init__(
        self,
        root: str,
        subset_csv: str,
        audio_cache_dir: str,
        generators: Sequence[str] = GENERATORS,
        num_frames: int = 16,
        frame_stride: int = 2,
        frame_size: int = 224,
        audio_seconds: float = 2.56,
        audio_sample_rate: int = 16000,
        mode: str = "pair",               # "pair" | "tuple"
        video_transform: Optional[Callable] = None,
    ) -> None:
        super().__init__()
        self.root = Path(root)
        self.resolver = FileResolver(
            root=self.root,
            audio_cache_dir=Path(audio_cache_dir),
        )
        self.generators = tuple(generators)
        self.num_frames = num_frames
        self.frame_stride = frame_stride
        self.frame_size = frame_size
        self.audio_seconds = audio_seconds
        self.audio_sample_rate = audio_sample_rate
        self.mode = mode
        self.video_transform = video_transform

        self.df = pd.read_csv(self.root / subset_csv)
        # Each row is one identity with its real basename_num.
        # fakes share the same basename_num across generators.

    def __len__(self) -> int:
        return len(self.df) if self.mode == "tuple" else len(self.df) * len(self.generators)

    def _load(self, path: str) -> Tuple[torch.Tensor, torch.Tensor]:
        video = load_video_clip(path, self.num_frames, self.frame_stride, self.frame_size)
        if self.video_transform is not None:
            video = self.video_transform(video)
        apath = self.resolver.audio_path(path)
        if os.path.exists(apath):
            audio = load_audio_clip(apath, self.audio_seconds, self.audio_sample_rate)
        else:
            audio = torch.zeros(int(self.audio_seconds * self.audio_sample_rate))
        return video, audio

    def _real_path(self, row: pd.Series) -> str:
        num = str(row["basename_num"]).zfill(4)
        candidates = list((self.root / "Real").glob(f"{num}_Real_*.mp4"))
        if not candidates:
            raise FileNotFoundError(f"missing real for id={row.get('identity_id')} num={num}")
        return str(candidates[0])

    def _fake_path(self, row: pd.Series, gen: str) -> str:
        num = str(row["basename_num"]).zfill(4)
        return str(self.root / gen / _fake_filename(num, gen))

    def __getitem__(self, idx: int) -> Dict[str, Any]:
        if self.mode == "tuple":
            row = self.df.iloc[idx]
            real_v, real_a = self._load(self._real_path(row))
            fakes_v, fakes_a, gens = [], [], []
            for g in self.generators:
                fp = self._fake_path(row, g)
                try:
                    v, a = self._load(fp)
                    fakes_v.append(v); fakes_a.append(a); gens.append(g)
                except Exception as e:
                    warnings.warn(f"missing {fp}: {e}")
            return {
                "real_video": real_v,
                "real_audio": real_a,
                "fake_videos": torch.stack(fakes_v),
                "fake_audios": torch.stack(fakes_a),
                "generators": gens,
                "identity_id": str(row.get("identity_id", "")),
                "subset": str(row.get("subset", "")),
            }
        else:  # pair mode
            row_idx = idx // len(self.generators)
            gen_idx = idx % len(self.generators)
            row = self.df.iloc[row_idx]
            gen = self.generators[gen_idx]
            # alternate real/fake within a batch: even idx real, odd idx fake
            if idx % 2 == 0:
                vpath = self._real_path(row); label = 0
            else:
                vpath = self._fake_path(row, gen); label = 1
            v, a = self._load(vpath)
            return {
                "video": v, "audio": a, "label": label,
                "meta": {
                    "identity_id": str(row.get("identity_id", "")),
                    "subset": str(row.get("subset", "")),
                    "generator": gen if label == 1 else "",
                },
            }

# =============================================================================
# TalkingHeadBench test dataset (fake + optional real)
# =============================================================================

# Mapping of THB real-subset name -> relative directory under <real_root>
# where the .mp4 files can actually be found on disk.
THB_REAL_SUBDIRS: Dict[str, str] = {
    "FaceForensics++": "FaceForensics++/original_sequences/youtube/c23/videos",
    "CelebV-HQ": "CelebV-HQ",
    "VoxCeleb2": "VoxCeleb2",
    "HDTF": "HDTF",
}


class TalkingHeadBenchFakeTestDataset(Dataset):
    """
    Dataset for TalkingHeadBench test videos.

    By default this loads only fake videos from ``<root>/fake/<gen>/test``.
    If ``real_root`` + ``real_split_json`` are also provided, real videos from
    the given ``real_subsets`` (e.g. FaceForensics++) under the ``real_split_name``
    split (default: ``Test``) are added with label=0, so that meaningful AUC
    can be computed.

    Returns per sample:
        video:   (T, 3, H, W) float
        audio:   (S,) float
        label:   int (0 = real, 1 = fake)
        meta:    dict with generator info and basename
    """

    def __init__(
        self,
        root: str,
        audio_cache_dir: str,
        generators: Sequence[str] = GENERATORS,
        num_frames: int = 16,
        frame_stride: int = 2,
        frame_size: int = 224,
        audio_seconds: float = 2.56,
        audio_sample_rate: int = 16000,
        video_transform: Optional[Callable] = None,
        real_root: Optional[str] = None,
        real_split_json: Optional[str] = None,
        real_subsets: Optional[Sequence[str]] = None,
        real_split_name: str = "Test",
        real_audio_cache_dir: Optional[str] = None,
    ) -> None:
        super().__init__()
        self.root = Path(root)
        self.resolver = FileResolver(
            root=self.root,
            audio_cache_dir=Path(audio_cache_dir),
        )
        self.generators = tuple(generators)
        self.num_frames = num_frames
        self.frame_stride = frame_stride
        self.frame_size = frame_size
        self.audio_seconds = audio_seconds
        self.audio_sample_rate = audio_sample_rate
        self.video_transform = video_transform

        # Optional real-video configuration
        self.real_root = Path(real_root) if real_root else None
        self.real_split_json = Path(real_split_json) if real_split_json else None
        self.real_subsets = tuple(real_subsets) if real_subsets else ()
        self.real_split_name = real_split_name
        self.real_audio_cache_dir = (
            Path(real_audio_cache_dir) if real_audio_cache_dir else None
        )

        # Build dataset by scanning fake/test directories (+ optional real)
        self.samples = self._build_samples()

    def _build_samples(self) -> List[Dict[str, Any]]:
        """Scan <root>/fake/<generator>/test/ directories to build the sample list.

        Expected TalkingHeadBench file naming:
            <image_num>--<driving_signal>--<generator>.mp4
        where fields are separated by the literal string "--".

        If real-video configuration is provided, also append real samples
        (label=0) from the requested split / subsets of the THB real dataset.
        """
        samples: List[Dict[str, Any]] = []

        # ---- fake videos --------------------------------------------------
        for generator in self.generators:
            test_dir = self.root / "fake" / generator / "test"

            if not test_dir.exists():
                warnings.warn(f"Test directory not found for {generator}: {test_dir}")
                continue

            mp4_files = sorted(test_dir.glob("*.mp4"))

            for mp4_path in mp4_files:
                basename = mp4_path.stem  # e.g. "00683--xqtbz-pVp2g_1--AniPortraitAudio"

                # Split on the "--" separator used by THB.
                parts = basename.split("--")
                if len(parts) >= 3:
                    num = parts[0]
                    driving = "--".join(parts[1:-1])  # keep middle field intact
                else:
                    # Unexpected format: keep the whole stem as num so we do not silently drop it.
                    num = basename
                    driving = ""

                samples.append({
                    "video_path": str(mp4_path),
                    "audio_path": self.resolver.audio_path(str(mp4_path)),
                    "label": 1,
                    "generator": generator,
                    "basename": basename,
                    "num": num,
                    "driving": driving,
                })

        if not samples:
            warnings.warn(f"No fake test samples found in {self.root}/fake/*/test/")

        # ---- real videos (optional) --------------------------------------
        real_samples = self._build_real_samples()
        samples.extend(real_samples)

        return samples

    def _build_real_samples(self) -> List[Dict[str, Any]]:
        """Load real-video samples from the THB real split JSON if configured."""
        real_samples: List[Dict[str, Any]] = []
        if self.real_root is None or self.real_split_json is None or not self.real_subsets:
            return real_samples

        if not self.real_split_json.exists():
            warnings.warn(f"Real split json not found: {self.real_split_json}")
            return real_samples

        try:
            with open(self.real_split_json, "r") as f:
                split_map = json.load(f)
        except Exception as e:
            warnings.warn(f"Failed to load real split json {self.real_split_json}: {e}")
            return real_samples

        subsets_dict = split_map.get(self.real_split_name, {})
        if not subsets_dict:
            warnings.warn(
                f"Split '{self.real_split_name}' not found in {self.real_split_json}"
            )
            return real_samples

        audio_cache = self.real_audio_cache_dir or (self.real_root / "_audio")

        for subset in self.real_subsets:
            filenames = subsets_dict.get(subset)
            if not filenames:
                warnings.warn(
                    f"Real subset '{subset}' missing in split '{self.real_split_name}'"
                )
                continue

            rel_dir = THB_REAL_SUBDIRS.get(subset, subset)
            subset_dir = self.real_root / rel_dir
            if not subset_dir.exists():
                warnings.warn(f"Real subset dir not found: {subset_dir}")
                continue

            n_found = 0
            for fname in filenames:
                mp4_path = subset_dir / fname
                if not mp4_path.exists():
                    # Silently skip missing files so partial downloads still work.
                    continue
                basename = mp4_path.stem
                audio_path = audio_cache / subset / (basename + ".wav")
                real_samples.append({
                    "video_path": str(mp4_path),
                    "audio_path": str(audio_path),
                    "label": 0,
                    "generator": f"real/{subset}",
                    "basename": basename,
                    "num": basename,
                    "driving": "",
                })
                n_found += 1

            warnings.warn(
                f"[THB real] {subset}: matched {n_found}/{len(filenames)} files under {subset_dir}"
            )

        return real_samples

    def __len__(self) -> int:
        return len(self.samples)

    def _load_sample(self, vpath: str, apath: str) -> Tuple[torch.Tensor, torch.Tensor]:
        """Load video and audio samples."""
        video = load_video_clip(
            vpath, self.num_frames, self.frame_stride, self.frame_size,
        )
        if self.video_transform is not None:
            video = self.video_transform(video)
            
        if os.path.exists(apath):
            audio = load_audio_clip(
                apath, self.audio_seconds, self.audio_sample_rate,
            )
        else:
            # silent fallback if audio extraction wasn't done yet
            warnings.warn(f"missing audio cache: {apath}; returning silence")
            audio = torch.zeros(int(self.audio_seconds * self.audio_sample_rate))
            
        return video, audio

    def __getitem__(self, idx: int) -> Dict[str, Any]:
        sample = self.samples[idx]
        
        try:
            video, audio = self._load_sample(sample["video_path"], sample["audio_path"])
        except Exception as e:
            # robust dataloader: skip broken samples
            warnings.warn(f"skipping bad sample idx={idx} basename={sample['basename']}: {e}")
            # return random other idx
            return self.__getitem__((idx + 1) % len(self))

        return {
            "video": video,
            "audio": audio,
            "label": int(sample.get("label", 1)),
            "meta": {
                "basename": sample["basename"],
                "generator": sample["generator"],
                "num": sample["num"],
                "driving": sample.get("driving", ""),
                "video_path": sample["video_path"],
            },
        }