Spaces:
Sleeping
Sleeping
File size: 16,196 Bytes
56c83aa 13179ec 7d3f27a 56c83aa a62229c a1c4344 56c83aa 7d3f27a 56c83aa 043203b 56c83aa 7d3f27a 56c83aa 7d3f27a a1c4344 13179ec 7d3f27a f58e53b 7d3f27a 56c83aa a1c4344 8bcab8a a1c4344 043203b 56c83aa f58e53b 56c83aa f58e53b 56c83aa 7d3f27a a62229c 7d3f27a 043203b 7d3f27a a62229c 7d3f27a a62229c 7d3f27a 56c83aa 7d3f27a f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa 7d3f27a f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa f58e53b 56c83aa 7d3f27a 56c83aa 7d3f27a 6ed9b96 56c83aa 6e34f6d 56c83aa 6e34f6d 56c83aa 7d3f27a 6e34f6d 56c83aa 6e34f6d 56c83aa 6e34f6d 56c83aa 6e34f6d 56c83aa 6e34f6d 56c83aa 6e34f6d 56c83aa 7d3f27a a1c4344 56c83aa 6ed9b96 043203b a1c4344 56c83aa 6ed9b96 56c83aa 7d3f27a 56c83aa 043203b 56c83aa 7fb4ec5 6ed9b96 7fb4ec5 7d3f27a 6ed9b96 56c83aa 6ed9b96 043203b 56c83aa 6ed9b96 56c83aa 6ed9b96 043203b 6ed9b96 56c83aa 7d3f27a 56c83aa 043203b 56c83aa 6ed9b96 7d3f27a 56c83aa a1c4344 043203b 56c83aa a1c4344 56c83aa 13179ec 56c83aa 6ed9b96 043203b 7d3f27a 56c83aa e184c9f 043203b 56c83aa 7d3f27a a1c4344 56c83aa a1c4344 7d3f27a 56c83aa 7fb4ec5 56c83aa 7fb4ec5 56c83aa 7fb4ec5 56c83aa a1c4344 56c83aa a1c4344 56c83aa 8bcab8a a1c4344 13179ec 043203b 7d3f27a 56c83aa a1c4344 13179ec 043203b 7d3f27a 56c83aa f58e53b 56c83aa | 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 | """Deepfake Detector - Hugging Face ZeroGPU Space.
V-JEPA 2.1 ViT-Giant + AttentiveClassifier probe.
Reference version for VigilVid:
- Uses window-vote aggregation instead of max-window final scoring.
- Does not store submitted user videos after processing.
"""
import glob
import os
import shutil
import tempfile
import threading
import time
import warnings
import requests
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
import gradio as gr
import spaces
import torch
from huggingface_hub import hf_hub_download
from inference_core import AttentiveClassifier, get_video_windows
from saverapi_client import saverapi_fetch
# ---------------------------------------------------------------------------
# Config and secrets
# ---------------------------------------------------------------------------
DEVICE = "cuda"
FEATURE_DIM = 1408
HF_TOKEN = os.environ.get("HF_TOKEN")
ENCODER_REPO = os.environ.get("ENCODER_REPO", "")
PROBE_REPO = os.environ.get("PROBE_REPO", ENCODER_REPO)
# SaverAPI rotator config. The client itself lives in saverapi_client.py.
SAVER_API_KEY_COOLDOWN_SEC = int(os.environ.get("SAVER_API_KEY_COOLDOWN_SEC", "3600"))
SAVER_API_MAX_RETRIES_PER_REQUEST = int(
os.environ.get("SAVER_API_MAX_RETRIES_PER_REQUEST", "5")
)
SAVER_API_MAX_FILESIZE_MB = int(os.environ.get("SAVER_API_MAX_FILESIZE_MB", "100"))
SAVER_API_STARTUP_PROBE_URL = os.environ.get("SAVER_API_STARTUP_PROBE_URL", "").strip()
# ---------------------------------------------------------------------------
# Model loading
# ---------------------------------------------------------------------------
print("=" * 50)
print("Loading V-JEPA 2.1 encoder architecture via torch.hub...")
encoder, _ = torch.hub.load(
"facebookresearch/vjepa2",
"vjepa2_1_vit_giant_384",
pretrained=False,
trust_repo=True,
verbose=False,
)
print(f"Downloading V-JEPA 2.1 weights from {ENCODER_REPO} ...")
encoder_weights_path = hf_hub_download(
repo_id=ENCODER_REPO,
filename="vjepa2_1_vitg_384.pt",
token=HF_TOKEN,
)
ckpt = torch.load(encoder_weights_path, map_location="cpu", weights_only=True)
ckpt = ckpt.get("ema_encoder", ckpt.get("encoder", ckpt))
ckpt = {k.replace("module.", "").replace("backbone.", ""): v for k, v in ckpt.items()}
encoder.load_state_dict(ckpt, strict=False)
del ckpt
encoder = encoder.to(DEVICE).to(torch.bfloat16)
encoder.eval()
print("Encoder ready.")
print("Loading AttentiveClassifier probe...")
probe_path = hf_hub_download(
repo_id=PROBE_REPO,
filename="attentive_probe_optimized.pt",
token=HF_TOKEN,
)
probe_state = torch.load(probe_path, map_location="cpu")
if "probe_state_dict" in probe_state:
probe_state = probe_state["probe_state_dict"]
probe = AttentiveClassifier(embed_dim=FEATURE_DIM)
probe.load_state_dict(probe_state)
probe = probe.to(DEVICE)
probe.eval()
print("Probe ready.")
print("=" * 50)
# ---------------------------------------------------------------------------
# Helper utilities
# ---------------------------------------------------------------------------
def clamp_probability(value: float) -> float:
return min(max(float(value), 0.0), 1.0)
def aggregate_window_vote_probability(scores: list[dict]) -> dict[str, float | int]:
"""Blend average score with majority voting to avoid max-window bias."""
probabilities = [
clamp_probability(score["prob"])
for score in scores
if isinstance(score, dict) and "prob" in score
]
if not probabilities:
return {
"final_probability": 0.0,
"mean_probability": 0.0,
"fake_vote_ratio": 0.0,
"fake_vote_count": 0,
"peak_probability": 0.0,
}
mean_probability = sum(probabilities) / len(probabilities)
fake_vote_count = sum(1 for probability in probabilities if probability >= 0.5)
fake_vote_ratio = fake_vote_count / len(probabilities)
final_probability = (mean_probability + fake_vote_ratio) / 2
return {
"final_probability": clamp_probability(final_probability),
"mean_probability": mean_probability,
"fake_vote_ratio": fake_vote_ratio,
"fake_vote_count": fake_vote_count,
"peak_probability": max(probabilities),
}
def remove_video_files(video_path: str) -> None:
for file_path in glob.glob(video_path + "*") + [video_path]:
if os.path.exists(file_path):
try:
os.remove(file_path)
except Exception:
pass
# ---------------------------------------------------------------------------
# SaverAPI key rotator
# ---------------------------------------------------------------------------
class KeyRotator:
"""Sticky-failover pool of SaverAPI keys.
Reads keys from SAVER_API_KEY_1..SAVER_API_KEY_10. On any error, the
failing key is marked dead for `cooldown_sec` seconds. State is in-memory
only and resets on Space restart.
"""
KEY_ENV_NAMES = [f"SAVER_API_KEY_{index}" for index in range(1, 11)]
def __init__(self, cooldown_sec: int):
self.keys = [os.environ.get(name, "").strip() for name in self.KEY_ENV_NAMES]
self.keys = [key for key in self.keys if key]
self.cooldown_sec = cooldown_sec
self._dead_until: dict = {}
self._lock = threading.Lock()
self._cursor = 0
def get_key(self) -> str | None:
with self._lock:
if not self.keys:
return None
key_count = len(self.keys)
for offset in range(key_count):
index = (self._cursor + offset) % key_count
key = self.keys[index]
if self._dead_until.get(key, 0) <= time.time():
return key
return None
def mark_dead(self, key: str) -> None:
with self._lock:
self._dead_until[key] = time.time() + self.cooldown_sec
try:
self._cursor = (self.keys.index(key) + 1) % len(self.keys)
except (ValueError, ZeroDivisionError):
pass
def status(self) -> dict:
with self._lock:
now = time.time()
return {
"configured": len(self.keys),
"live": sum(
1 for key in self.keys if self._dead_until.get(key, 0) <= now
),
"dead": [
self.mask(key)
for key, timestamp in self._dead_until.items()
if timestamp > now
],
"cursor_index": self._cursor,
}
@staticmethod
def mask(key: str) -> str:
if len(key) <= 10:
return "***"
return f"{key[:6]}***{key[-4:]}"
key_rotator = KeyRotator(cooldown_sec=SAVER_API_KEY_COOLDOWN_SEC)
print(f"[SaverAPI] Rotator initialised with {len(key_rotator.keys)} key(s).")
def _saverapi_fetch_one(url: str, key: str) -> tuple[bool, str]:
"""Normalise saverapi_fetch return to (ok, file_or_error)."""
try:
return saverapi_fetch(url, key, max_filesize_mb=SAVER_API_MAX_FILESIZE_MB)
except Exception as exc:
return False, f"key-level:exception: {type(exc).__name__}: {exc}"
def download_video(url: str) -> tuple[bool, str]:
"""Tries configured SaverAPI keys in sequence."""
if not url.lower().startswith(("http://", "https://")):
return False, "Unsupported URL scheme. Use http:// or https://"
last_err = ""
for attempt in range(SAVER_API_MAX_RETRIES_PER_REQUEST):
key = key_rotator.get_key()
if key is None:
return False, "SaverAPI key pool exhausted; try again later."
ok, payload = _saverapi_fetch_one(url, key)
if ok:
return True, payload
last_err = payload
if last_err.startswith("key-level:"):
key_rotator.mark_dead(key)
print(
f"[SaverAPI] key {KeyRotator.mask(key)} failed "
f"(attempt {attempt + 1}/{SAVER_API_MAX_RETRIES_PER_REQUEST}): "
f"{last_err[:200]}"
)
continue
return False, last_err
return (
False,
f"SaverAPI: all {SAVER_API_MAX_RETRIES_PER_REQUEST} retries failed. "
f"Last: {last_err[:200]}",
)
def _startup_probe():
"""Best-effort probe of each configured key at Space boot."""
if os.environ.get("SKIP_STARTUP_PROBE", "").lower() in ("1", "true", "yes"):
print("[SaverAPI] Startup probe skipped (SKIP_STARTUP_PROBE=1).")
return
if not SAVER_API_STARTUP_PROBE_URL:
print("[SaverAPI] No SAVER_API_STARTUP_PROBE_URL set; skipping startup probe.")
return
if not key_rotator.keys:
print("[SaverAPI] No keys configured; skipping startup probe.")
return
print(
f"[SaverAPI] Probing {len(key_rotator.keys)} key(s) "
f"with {SAVER_API_STARTUP_PROBE_URL} ..."
)
for key in key_rotator.keys:
ok, payload = _saverapi_fetch_one(SAVER_API_STARTUP_PROBE_URL, key)
if ok:
remove_video_files(payload)
print(f"[SaverAPI] key {KeyRotator.mask(key)}: OK")
continue
if payload.startswith("key-level:"):
key_rotator.mark_dead(key)
print(f"[SaverAPI] key {KeyRotator.mask(key)}: DEAD ({payload[:100]})")
else:
print(
f"[SaverAPI] key {KeyRotator.mask(key)}: "
f"probe-URL error ({payload[:100]})"
)
# ---------------------------------------------------------------------------
# GPU inference
# ---------------------------------------------------------------------------
@spaces.GPU(duration=120)
def encode_and_classify(windows: list) -> list:
gpu_start_time = time.time()
print("\n[TIMING] --- GPU Allocated & Inference Started ---")
if not windows:
return []
vram_bytes = torch.cuda.get_device_properties(DEVICE).total_memory
vram_gb = vram_bytes / (1024**3)
dynamic_batch_size = max(3, int(vram_gb / 3))
all_clips = []
window_clip_counts = []
for window in windows:
all_clips.extend(window["clips"])
window_clip_counts.append(len(window["clips"]))
global_batch = torch.stack(all_clips).to(DEVICE)
all_feats = []
with torch.no_grad():
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
for index in range(0, global_batch.shape[0], dynamic_batch_size):
chunk = global_batch[index : index + dynamic_batch_size]
feats = encoder(chunk)
all_feats.append(feats)
all_feats = torch.cat(all_feats, dim=0)
scores = []
current_idx = 0
for index, window in enumerate(windows):
count = window_clip_counts[index]
window_feats = all_feats[current_idx : current_idx + count]
current_idx += count
video_feats = window_feats.view(1, -1, FEATURE_DIM)
with torch.no_grad():
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
logit, _ = probe(video_feats)
prob = torch.sigmoid(logit).item()
scores.append(
{
"prob": prob,
"start_sec": window["start_sec"],
"end_sec": window["end_sec"],
}
)
gpu_end_time = time.time()
print(f"[TIMING] GPU execution completed in {gpu_end_time - gpu_start_time:.2f}s")
return scores
# ---------------------------------------------------------------------------
# Gradio predict
# ---------------------------------------------------------------------------
def predict(
url: str,
uploaded_video: str,
current_state: dict,
) -> tuple[str, str, str, dict]:
global_start_time = time.time()
print(f"\n{'=' * 30}\n[TIMING] Request Received.")
url = (url or "").strip()
if current_state and "video_path" in current_state:
remove_video_files(current_state["video_path"])
file_start_time = time.time()
if uploaded_video:
tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
shutil.copy(uploaded_video, tmp.name)
video_path = tmp.name
elif url:
ok, path_or_err = download_video(url)
if not ok:
return f"Download failed: {path_or_err}", "", "", {}
video_path = path_or_err
else:
return "Please enter a URL or upload a video.", "", "", {}
file_ready_time = time.time()
print(
"[TIMING] File Acquisition (Download/Copy) took: "
f"{file_ready_time - file_start_time:.2f}s"
)
try:
windows, total_frames, fps, duration_sec = get_video_windows(video_path)
except Exception as exc:
remove_video_files(video_path)
return f"Video decode failed: {exc}", "", "", {}
cpu_decode_time = time.time()
print(f"[TIMING] CPU Video Decoding took: {cpu_decode_time - file_ready_time:.2f}s")
print("[TIMING] Requesting GPU Hardware from ZeroGPU Queue...")
queue_start_time = time.time()
scores = encode_and_classify(windows)
queue_and_gpu_time = time.time()
print(
"[TIMING] Total time spent requesting queue + GPU execution: "
f"{queue_and_gpu_time - queue_start_time:.2f}s"
)
if not scores:
remove_video_files(video_path)
return "No windows processed.", "", "", {}
aggregation = aggregate_window_vote_probability(scores)
final_prob = float(aggregation["final_probability"])
peak_prob = float(aggregation["peak_probability"])
label = "AI-GENERATED (FAKE)" if final_prob > 0.5 else "REAL"
elapsed_time = time.time() - global_start_time
confidence = f"{final_prob * 100:.1f}%"
lines = [
f"Processing Time: {elapsed_time:.1f}s",
f"Duration: {duration_sec:.1f}s | Frames: {total_frames} | Windows: {len(scores)}",
(
f"Aggregation: mean={float(aggregation['mean_probability']) * 100:.1f}% | "
f"fake votes={int(aggregation['fake_vote_count'])}/{len(scores)} | "
f"peak={peak_prob * 100:.1f}%\n"
),
]
for score in scores:
flag = " <- strongest window" if score["prob"] == peak_prob else ""
lines.append(
f" [{score['start_sec']:.1f}s - {score['end_sec']:.1f}s] -> "
f"{score['prob'] * 100:.1f}% fake{flag}"
)
remove_video_files(video_path)
print(f"[TIMING] Total Blocking Time Before UI Return: {elapsed_time:.2f}s")
return label, confidence, "\n".join(lines), {}
# ---------------------------------------------------------------------------
# Gradio UI
# ---------------------------------------------------------------------------
with gr.Blocks(title="Deepfake Detector") as demo:
session_state = gr.State(value={})
gr.Markdown(
"""
## Deepfake Video Detector
Paste a public Instagram, TikTok, or direct `.mp4` URL, **OR** upload a video directly.
Uses **V-JEPA 2.1 ViT-Giant** + **AttentiveClassifier** probe.
"""
)
with gr.Row():
url_box = gr.Textbox(
label="Video URL",
placeholder="https://www.instagram.com/reels/...",
autofocus=True,
scale=1,
)
upload_box = gr.Video(
label="Or Upload Video directly",
sources=["upload"],
scale=1,
)
run_btn = gr.Button("Analyze", variant="primary")
with gr.Row():
label_out = gr.Textbox(label="Prediction", scale=2)
conf_out = gr.Textbox(label="AI-generated probability", scale=1)
breakdown_out = gr.Textbox(
label="Window Breakdown & Processing Time",
lines=7,
interactive=False,
)
run_btn.click(
fn=predict,
inputs=[url_box, upload_box, session_state],
outputs=[label_out, conf_out, breakdown_out, session_state],
)
url_box.submit(
fn=predict,
inputs=[url_box, upload_box, session_state],
outputs=[label_out, conf_out, breakdown_out, session_state],
)
_startup_probe()
demo.launch()
|