File size: 8,819 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 | """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 generator directories inside <root>/manipulated_sequences/
DEFAULT_FFPP_GENERATORS: Tuple[str, ...] = (
"Deepfakes",
"Face2Face",
"FaceSwap",
"NeuralTextures",
)
# Default relative path for real (pristine) videos
DEFAULT_FFPP_REAL_REL = "original_sequences/youtube/c23/videos"
# Relative path template for fake videos of a given generator
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
# `real_root` lets callers point real videos to a completely different
# directory than `root` (e.g. TalkingHeadBench's FF++ real copy).
# When set, real videos are read from `<real_root>/<real_rel_dir>/*.mp4`
# (or directly from `<real_root>/*.mp4` if <real_root> already points at
# the videos folder -- we try the nested path first, then fall back).
self.real_root = Path(real_root) if real_root else None
# Optional caps (useful to keep test set balanced, e.g. 200 reals to
# match 200 fakes per generator).
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]] = []
# ---- fake videos --------------------------------------------------
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,
})
# ---- real videos (optional) --------------------------------------
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
# Fall back to the preferred path even if empty so the warning is
# useful to the user.
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:
# FF++ videos in this layout have no paired audio cache; use 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"])
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"],
},
}
|