| """FaceForensics++ test dataset. |
| |
| This module provides a standalone dataset class to run inference on the |
| FaceForensics++ (FF++) dataset. We deliberately do NOT reuse the |
| TalkingHeadBench file layout: videos are scanned directly from the native |
| FF++ directory tree, which looks like: |
| |
| <root>/manipulated_sequences/<generator>/c23/videos/*.mp4 (fake, label=1) |
| <root>/original_sequences/youtube/c23/videos/*.mp4 (real, label=0, optional) |
| |
| FF++ videos do not carry audio that matches our FairTalking pipeline, so the |
| dataset returns silent audio for every sample (no audio cache needed). |
| |
| The whole set is treated as a *test-only* dataset; we never split |
| train/val here. |
| """ |
| from __future__ import annotations |
|
|
| import warnings |
| from pathlib import Path |
| from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple |
|
|
| import torch |
| from torch.utils.data import Dataset |
|
|
| from .fairtalking_dataset import load_video_clip, load_audio_clip |
|
|
| |
| DEFAULT_FFPP_GENERATORS: Tuple[str, ...] = ( |
| "Deepfakes", |
| "Face2Face", |
| "FaceSwap", |
| "NeuralTextures", |
| ) |
|
|
| |
| DEFAULT_FFPP_REAL_REL = "original_sequences/youtube/c23/videos" |
|
|
| |
| def _fake_dir_for(generator: str, compression: str = "c23") -> str: |
| return f"manipulated_sequences/{generator}/{compression}/videos" |
|
|
|
|
| class FFPPTestDataset(Dataset): |
| """Standalone FaceForensics++ test dataset. |
| |
| Returns per sample: |
| video: (T, 3, H, W) float |
| audio: (S,) float (silent; FF++ has no paired audio in this layout) |
| label: int (0 = real, 1 = fake) |
| meta: dict with generator + basename + video_path |
| """ |
|
|
| def __init__( |
| self, |
| root: str, |
| generators: Sequence[str] = DEFAULT_FFPP_GENERATORS, |
| compression: str = "c23", |
| num_frames: int = 16, |
| frame_stride: int = 2, |
| frame_size: int = 224, |
| audio_seconds: float = 2.56, |
| audio_sample_rate: int = 16000, |
| include_real: bool = True, |
| real_rel_dir: Optional[str] = None, |
| real_root: Optional[str] = None, |
| max_fake_per_generator: Optional[int] = None, |
| max_real: Optional[int] = None, |
| audio_cache_dir: Optional[str] = None, |
| video_transform: Optional[Callable] = None, |
| ) -> None: |
| super().__init__() |
| self.root = Path(root) |
| self.generators = tuple(generators) |
| self.compression = compression |
| 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.audio_cache_dir = Path(audio_cache_dir) if audio_cache_dir else None |
|
|
| self.include_real = include_real |
| self.real_rel_dir = real_rel_dir or DEFAULT_FFPP_REAL_REL |
| |
| |
| |
| |
| |
| self.real_root = Path(real_root) if real_root else None |
|
|
| |
| |
| self.max_fake_per_generator = max_fake_per_generator |
| self.max_real = max_real |
|
|
| self.samples: List[Dict[str, Any]] = self._build_samples() |
| if not self.samples: |
| warnings.warn( |
| f"[FFPPTestDataset] no samples discovered under {self.root}; " |
| f"check that manipulated_sequences/<gen>/{compression}/videos/*.mp4 exists." |
| ) |
|
|
| |
| def _build_samples(self) -> List[Dict[str, Any]]: |
| samples: List[Dict[str, Any]] = [] |
|
|
| |
| for generator in self.generators: |
| gen_dir = self.root / _fake_dir_for(generator, self.compression) |
| if not gen_dir.exists(): |
| warnings.warn(f"[FFPPTestDataset] fake dir not found: {gen_dir}") |
| continue |
| mp4_files = sorted(gen_dir.glob("*.mp4")) |
| if self.max_fake_per_generator is not None: |
| mp4_files = mp4_files[: self.max_fake_per_generator] |
| for mp4_path in mp4_files: |
| samples.append({ |
| "video_path": str(mp4_path), |
| "label": 1, |
| "generator": generator, |
| "basename": mp4_path.stem, |
| }) |
|
|
| |
| if self.include_real: |
| real_dir = self._resolve_real_dir() |
| if real_dir is not None and real_dir.exists(): |
| mp4_files = sorted(real_dir.glob("*.mp4")) |
| if self.max_real is not None: |
| mp4_files = mp4_files[: self.max_real] |
| for mp4_path in mp4_files: |
| samples.append({ |
| "video_path": str(mp4_path), |
| "label": 0, |
| "generator": "real/FFPP", |
| "basename": mp4_path.stem, |
| }) |
| else: |
| warnings.warn( |
| f"[FFPPTestDataset] real dir not found (tried {real_dir}); " |
| f"only fake samples will be used, test/auc will be meaningless." |
| ) |
|
|
| return samples |
|
|
| def _resolve_real_dir(self) -> Optional[Path]: |
| """Find the directory that actually contains real .mp4 files. |
| |
| Probe order: |
| 1. <real_root>/<real_rel_dir> (both configured) |
| 2. <real_root> (real_root already points at videos) |
| 3. <root>/<real_rel_dir> (legacy default) |
| Return the first existing path, or None if nothing is found. |
| """ |
| candidates: List[Path] = [] |
| if self.real_root is not None: |
| candidates.append(self.real_root / self.real_rel_dir) |
| candidates.append(self.real_root) |
| candidates.append(self.root / self.real_rel_dir) |
| for c in candidates: |
| if c.exists() and any(c.glob("*.mp4")): |
| return c |
| |
| |
| return candidates[0] if candidates else None |
|
|
| |
| def __len__(self) -> int: |
| return len(self.samples) |
|
|
| def _audio_path_for(self, video_path: str) -> Optional[str]: |
| if self.audio_cache_dir is None: |
| return None |
| try: |
| rel = Path(video_path).relative_to(self.root) |
| except ValueError: |
| rel = Path(Path(video_path).name) |
| return str(self.audio_cache_dir / rel.with_suffix(".wav")) |
|
|
| def _load_sample(self, vpath: 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) |
|
|
| apath = self._audio_path_for(vpath) |
| if apath is not None and Path(apath).exists(): |
| 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 __getitem__(self, idx: int) -> Dict[str, Any]: |
| sample = self.samples[idx] |
| try: |
| video, audio = self._load_sample(sample["video_path"]) |
| except Exception as e: |
| warnings.warn( |
| f"[FFPPTestDataset] skipping bad sample idx={idx} " |
| f"basename={sample['basename']}: {e}" |
| ) |
| return self.__getitem__((idx + 1) % len(self)) |
|
|
| return { |
| "video": video, |
| "audio": audio, |
| "label": int(sample["label"]), |
| "meta": { |
| "basename": sample["basename"], |
| "generator": sample["generator"], |
| "num": sample["basename"], |
| "driving": "", |
| "video_path": sample["video_path"], |
| }, |
| } |
|
|