Spaces:
Running
Running
Sync from GitHub via hub-sync
Browse files- api/v1/analyze.py +11 -1
- config.py +25 -11
- models/heatmap_generator.py +59 -2
- models/model_loader.py +76 -0
- scripts/convert_densenet_keras_to_pt.py +280 -0
- services/densenet_service.py +110 -0
- services/image_service.py +75 -30
- services/llm_explainer.py +36 -4
- services/news_lookup.py +1 -14
- trained_models/Colab_ViT_Training.ipynb +0 -0
- trained_models/config.json +0 -34
- trained_models/deepfake_densenet121_high_acc.keras +0 -3
- trained_models/deepfake_densenet121_latest.keras +0 -3
- trained_models/deepfake_densenet121_threshold.json +0 -9
- trained_models/densenet121_faces.pt +0 -3
- trained_models/densenet121_faces_meta.json +0 -21
- trained_models/model.safetensors +0 -3
- trained_models/training_args.bin +0 -3
api/v1/analyze.py
CHANGED
|
@@ -310,7 +310,17 @@ async def analyze_image(
|
|
| 310 |
indicators = scan_artifacts(pil, raw)
|
| 311 |
stages.append("artifact_scanning")
|
| 312 |
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
|
| 315 |
# ── Run heatmap + ELA + boxes + EXIF in parallel ──
|
| 316 |
def _run_heatmap():
|
|
|
|
| 310 |
indicators = scan_artifacts(pil, raw)
|
| 311 |
stages.append("artifact_scanning")
|
| 312 |
|
| 313 |
+
# Heatmap dispatch: DenseNet leads for face still-images (GAN portraits),
|
| 314 |
+
# EfficientNet for video frames (face-swap / DFDC), ViT for no-face / fallback.
|
| 315 |
+
from services.image_service import _has_face_for_routing, _looks_like_video_frame
|
| 316 |
+
_face_for_heatmap = _has_face_for_routing(pil_vis)
|
| 317 |
+
_videoframe_heatmap = _looks_like_video_frame(pil_vis)
|
| 318 |
+
if _face_for_heatmap and settings.DENSENET_ENABLED and not _videoframe_heatmap:
|
| 319 |
+
model_family = "densenet"
|
| 320 |
+
elif settings.ENSEMBLE_MODE and (_face_for_heatmap or _videoframe_heatmap):
|
| 321 |
+
model_family = "efficientnet"
|
| 322 |
+
else:
|
| 323 |
+
model_family = "vit"
|
| 324 |
|
| 325 |
# ── Run heatmap + ELA + boxes + EXIF in parallel ──
|
| 326 |
def _run_heatmap():
|
config.py
CHANGED
|
@@ -202,16 +202,30 @@ class Settings(BaseSettings):
|
|
| 202 |
FFPP_MODEL_REVISION: str = "main"
|
| 203 |
FFPP_BASE_PROCESSOR_ID: str = "google/vit-base-patch16-224-in21k"
|
| 204 |
FFPP_ENABLED: bool = True
|
| 205 |
-
#
|
| 206 |
-
#
|
| 207 |
-
|
| 208 |
-
#
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
FFPP_WEIGHT_NOFACE: float = 0.35
|
| 214 |
-
VIT_WEIGHT_NOFACE:
|
| 215 |
|
| 216 |
# Face-present unified evidence weights (Phase A2/A3).
|
| 217 |
# face_stack = composite of FFPP+ViT+EffNet (all face-swap models).
|
|
@@ -251,8 +265,8 @@ class Settings(BaseSettings):
|
|
| 251 |
# AI-image detector is unreliable (it's trained on synthesised stills, not
|
| 252 |
# video face-swaps). We shift weight strongly toward the face-swap-trained
|
| 253 |
# models (FFPP / EfficientNet) in that case.
|
| 254 |
-
VIDEO_FRAME_FACE_STACK_WEIGHT: float = 0.
|
| 255 |
-
VIDEO_FRAME_GENERAL_WEIGHT: float = 0.
|
| 256 |
VIDEO_FRAME_FORENSICS_WEIGHT: float = 0.10
|
| 257 |
VIDEO_FRAME_EXIF_WEIGHT: float = 0.05
|
| 258 |
# Per-frame video detector blend. FFPP ViT is trained on FaceForensics++
|
|
|
|
| 202 |
FFPP_MODEL_REVISION: str = "main"
|
| 203 |
FFPP_BASE_PROCESSOR_ID: str = "google/vit-base-patch16-224-in21k"
|
| 204 |
FFPP_ENABLED: bool = True
|
| 205 |
+
# DenseNet121 face-GAN specialist (in-house trained on 140k Kaggle dataset).
|
| 206 |
+
# Loaded from a TF-free PyTorch checkpoint converted via convert_densenet_keras_to_pt.py.
|
| 207 |
+
DENSENET_ENABLED: bool = True
|
| 208 |
+
# Path to .pt checkpoint, resolved relative to repo root (or absolute).
|
| 209 |
+
DENSENET_MODEL_PATH: str = "backend/trained_models/densenet121_faces.pt"
|
| 210 |
+
DENSENET_META_PATH: str = "backend/trained_models/densenet121_faces_meta.json"
|
| 211 |
+
# HF Space fallback when local checkpoint is absent.
|
| 212 |
+
DENSENET_HF_REPO_ID: str = "ar07xd/deepshield"
|
| 213 |
+
DENSENET_HF_REVISION: str = "main"
|
| 214 |
+
|
| 215 |
+
# Ensemble weights — DenseNet leads because it is trained on still-image GAN
|
| 216 |
+
# faces (the dominant upload type). FFPP / EffNet are stronger on video frames.
|
| 217 |
+
# Face-stack internal weights (sum = 1.0).
|
| 218 |
+
DENSENET_WEIGHT_FACE: float = 0.45
|
| 219 |
+
FFPP_WEIGHT_FACE: float = 0.25
|
| 220 |
+
VIT_WEIGHT_FACE: float = 0.15
|
| 221 |
+
EFFNET_WEIGHT_FACE: float = 0.15
|
| 222 |
+
# Video-frame path: FFPP leads since FFPP is trained on FF++ video frames.
|
| 223 |
+
DENSENET_VIDEO_WEIGHT: float = 0.10
|
| 224 |
+
VIDEO_FFPP_WEIGHT_FACE: float = 0.50
|
| 225 |
+
VIDEO_EFFNET_WEIGHT_FACE: float = 0.30
|
| 226 |
+
VIDEO_VIT_WEIGHT_FACE: float = 0.10
|
| 227 |
FFPP_WEIGHT_NOFACE: float = 0.35
|
| 228 |
+
VIT_WEIGHT_NOFACE: float = 0.65
|
| 229 |
|
| 230 |
# Face-present unified evidence weights (Phase A2/A3).
|
| 231 |
# face_stack = composite of FFPP+ViT+EffNet (all face-swap models).
|
|
|
|
| 265 |
# AI-image detector is unreliable (it's trained on synthesised stills, not
|
| 266 |
# video face-swaps). We shift weight strongly toward the face-swap-trained
|
| 267 |
# models (FFPP / EfficientNet) in that case.
|
| 268 |
+
VIDEO_FRAME_FACE_STACK_WEIGHT: float = 0.55
|
| 269 |
+
VIDEO_FRAME_GENERAL_WEIGHT: float = 0.30
|
| 270 |
VIDEO_FRAME_FORENSICS_WEIGHT: float = 0.10
|
| 271 |
VIDEO_FRAME_EXIF_WEIGHT: float = 0.05
|
| 272 |
# Per-frame video detector blend. FFPP ViT is trained on FaceForensics++
|
models/heatmap_generator.py
CHANGED
|
@@ -206,16 +206,73 @@ def _cam_to_full_image(
|
|
| 206 |
return cam_full, orig_np
|
| 207 |
|
| 208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
def generate_heatmap_base64(
|
| 210 |
pil_img: Image.Image,
|
| 211 |
target_class_idx: Optional[int] = None,
|
| 212 |
-
model_family: Literal["vit", "efficientnet"] = "vit",
|
| 213 |
) -> tuple[str, str]:
|
| 214 |
"""Produce a base64 data-URL PNG of the Grad-CAM++ overlay at original image resolution.
|
| 215 |
|
| 216 |
Returns (base64_png, heatmap_source).
|
| 217 |
"""
|
| 218 |
-
if model_family == "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
try:
|
| 220 |
grayscale_cam, face_bbox, source = _compute_gradcam_pp_efficientnet(pil_img)
|
| 221 |
cam_full, orig_np = _cam_to_full_image(grayscale_cam, pil_img, face_bbox)
|
|
|
|
| 206 |
return cam_full, orig_np
|
| 207 |
|
| 208 |
|
| 209 |
+
def _compute_gradcam_pp_densenet(
|
| 210 |
+
pil_img: Image.Image,
|
| 211 |
+
) -> tuple[np.ndarray, str]:
|
| 212 |
+
"""Grad-CAM++ on the DenseNet121 face-GAN model.
|
| 213 |
+
|
| 214 |
+
Target signal = fake probability = sigmoid(-logit), so we maximise the
|
| 215 |
+
negated logit. Target layer = features.norm5 (final BN after last DenseBlock,
|
| 216 |
+
7×7×1024 activation map). Returns (grayscale_cam, source_tag).
|
| 217 |
+
"""
|
| 218 |
+
loader = get_model_loader()
|
| 219 |
+
result = loader.load_densenet()
|
| 220 |
+
if result is None:
|
| 221 |
+
raise RuntimeError("DenseNet model unavailable")
|
| 222 |
+
model, meta = result
|
| 223 |
+
|
| 224 |
+
from services.densenet_service import _preprocess
|
| 225 |
+
image_size = int(meta.get("image_size", 224))
|
| 226 |
+
input_tensor = _preprocess(pil_img, image_size, settings.DEVICE)
|
| 227 |
+
|
| 228 |
+
model.eval()
|
| 229 |
+
for p in model.parameters():
|
| 230 |
+
p.requires_grad_(True)
|
| 231 |
+
|
| 232 |
+
# Target = last BN after all DenseBlocks (equivalent to conv5_block16_concat in Keras)
|
| 233 |
+
target_layers = [model.features.norm5]
|
| 234 |
+
|
| 235 |
+
# Negate logit so Grad-CAM gradients flow toward the FAKE class
|
| 236 |
+
# (model output = real_probability logit; higher = more real)
|
| 237 |
+
class _NegatedLogitWrapper(torch.nn.Module):
|
| 238 |
+
def __init__(self, m: torch.nn.Module) -> None:
|
| 239 |
+
super().__init__()
|
| 240 |
+
self.m = m
|
| 241 |
+
|
| 242 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override]
|
| 243 |
+
return -self.m(x) # negative logit → gradient points at fake evidence
|
| 244 |
+
|
| 245 |
+
wrapped = _NegatedLogitWrapper(model)
|
| 246 |
+
|
| 247 |
+
with GradCAMPlusPlus(model=wrapped, target_layers=target_layers) as cam:
|
| 248 |
+
grayscale_cam = cam(input_tensor=input_tensor, targets=None)[0] # (H,W) in [0,1]
|
| 249 |
+
|
| 250 |
+
return grayscale_cam, "gradcam++_densenet"
|
| 251 |
+
|
| 252 |
+
|
| 253 |
def generate_heatmap_base64(
|
| 254 |
pil_img: Image.Image,
|
| 255 |
target_class_idx: Optional[int] = None,
|
| 256 |
+
model_family: Literal["vit", "efficientnet", "densenet"] = "vit",
|
| 257 |
) -> tuple[str, str]:
|
| 258 |
"""Produce a base64 data-URL PNG of the Grad-CAM++ overlay at original image resolution.
|
| 259 |
|
| 260 |
Returns (base64_png, heatmap_source).
|
| 261 |
"""
|
| 262 |
+
if model_family == "densenet":
|
| 263 |
+
try:
|
| 264 |
+
grayscale_cam, source = _compute_gradcam_pp_densenet(pil_img)
|
| 265 |
+
cam_full, orig_np = _cam_to_full_image(grayscale_cam, pil_img, None)
|
| 266 |
+
except Exception as e:
|
| 267 |
+
logger.warning(f"DenseNet heatmap failed ({e}) — falling back to ViT Grad-CAM++")
|
| 268 |
+
try:
|
| 269 |
+
grayscale_cam, _ = _compute_gradcam_pp(pil_img, target_class_idx)
|
| 270 |
+
cam_full, orig_np = _cam_to_full_image(grayscale_cam, pil_img, None)
|
| 271 |
+
source = "vit_fallback"
|
| 272 |
+
except Exception as fe:
|
| 273 |
+
logger.warning(f"ViT fallback heatmap also failed: {fe}")
|
| 274 |
+
return "", "none"
|
| 275 |
+
elif model_family == "efficientnet":
|
| 276 |
try:
|
| 277 |
grayscale_cam, face_bbox, source = _compute_gradcam_pp_efficientnet(pil_img)
|
| 278 |
cam_full, orig_np = _cam_to_full_image(grayscale_cam, pil_img, face_bbox)
|
models/model_loader.py
CHANGED
|
@@ -39,6 +39,9 @@ class ModelLoader:
|
|
| 39 |
cls._instance._efficientnet_detector = None
|
| 40 |
cls._instance._ffpp_model = None
|
| 41 |
cls._instance._ffpp_processor = None
|
|
|
|
|
|
|
|
|
|
| 42 |
return cls._instance
|
| 43 |
|
| 44 |
@classmethod
|
|
@@ -321,6 +324,78 @@ class ModelLoader:
|
|
| 321 |
logger.warning(f"FFPP ViT load failed (continuing without it): {e}")
|
| 322 |
return None
|
| 323 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
# ---------- Preload ----------
|
| 325 |
def preload_phase1(self) -> None:
|
| 326 |
"""Preload all core models to prevent lazy-loading delays during first analysis."""
|
|
@@ -330,6 +405,7 @@ class ModelLoader:
|
|
| 330 |
self.load_face_detector()
|
| 331 |
self.load_efficientnet()
|
| 332 |
self.load_ffpp_model()
|
|
|
|
| 333 |
self.load_ocr_engine()
|
| 334 |
self.load_text_model()
|
| 335 |
self.load_multilang_text_model()
|
|
|
|
| 39 |
cls._instance._efficientnet_detector = None
|
| 40 |
cls._instance._ffpp_model = None
|
| 41 |
cls._instance._ffpp_processor = None
|
| 42 |
+
cls._instance._densenet_model = None
|
| 43 |
+
cls._instance._densenet_meta = None
|
| 44 |
+
cls._instance._densenet_unavailable = False
|
| 45 |
return cls._instance
|
| 46 |
|
| 47 |
@classmethod
|
|
|
|
| 324 |
logger.warning(f"FFPP ViT load failed (continuing without it): {e}")
|
| 325 |
return None
|
| 326 |
|
| 327 |
+
# ---------- DenseNet121 face-GAN specialist ----------
|
| 328 |
+
def load_densenet(self) -> Optional[Tuple[object, dict]]:
|
| 329 |
+
"""Lazy-load DenseNet121 PyTorch checkpoint (TF-free).
|
| 330 |
+
|
| 331 |
+
Returns (model, meta_dict) or None when disabled / file missing.
|
| 332 |
+
meta_dict contains threshold, image_size, normalize_mean/std.
|
| 333 |
+
"""
|
| 334 |
+
if not settings.DENSENET_ENABLED:
|
| 335 |
+
return None
|
| 336 |
+
if self._densenet_unavailable:
|
| 337 |
+
return None
|
| 338 |
+
if self._densenet_model is not None:
|
| 339 |
+
return self._densenet_model, self._densenet_meta
|
| 340 |
+
|
| 341 |
+
import json
|
| 342 |
+
import torch
|
| 343 |
+
from pathlib import Path
|
| 344 |
+
|
| 345 |
+
repo_root = Path(__file__).resolve().parent.parent.parent
|
| 346 |
+
|
| 347 |
+
def _resolve(rel: str) -> Path:
|
| 348 |
+
p = Path(rel)
|
| 349 |
+
return p if p.is_absolute() else (repo_root / p).resolve()
|
| 350 |
+
|
| 351 |
+
pt_path = _resolve(settings.DENSENET_MODEL_PATH)
|
| 352 |
+
meta_path = _resolve(settings.DENSENET_META_PATH)
|
| 353 |
+
|
| 354 |
+
# HF Space fallback when local files are missing
|
| 355 |
+
if not pt_path.exists() or not meta_path.exists():
|
| 356 |
+
repo_id = settings.DENSENET_HF_REPO_ID.strip()
|
| 357 |
+
if repo_id:
|
| 358 |
+
try:
|
| 359 |
+
from huggingface_hub import hf_hub_download
|
| 360 |
+
logger.info(f"DenseNet checkpoint not found locally — downloading from {repo_id}")
|
| 361 |
+
pt_path = Path(hf_hub_download(
|
| 362 |
+
repo_id=repo_id, repo_type="space",
|
| 363 |
+
filename="trained_models/densenet121_faces.pt",
|
| 364 |
+
revision=settings.DENSENET_HF_REVISION,
|
| 365 |
+
))
|
| 366 |
+
meta_path = Path(hf_hub_download(
|
| 367 |
+
repo_id=repo_id, repo_type="space",
|
| 368 |
+
filename="trained_models/densenet121_faces_meta.json",
|
| 369 |
+
revision=settings.DENSENET_HF_REVISION,
|
| 370 |
+
))
|
| 371 |
+
except Exception as e:
|
| 372 |
+
logger.warning(f"DenseNet HF download failed: {e} — skipping")
|
| 373 |
+
self._densenet_unavailable = True
|
| 374 |
+
return None
|
| 375 |
+
|
| 376 |
+
if not pt_path.exists():
|
| 377 |
+
logger.warning(f"DenseNet checkpoint not found at {pt_path} — skipping")
|
| 378 |
+
self._densenet_unavailable = True
|
| 379 |
+
return None
|
| 380 |
+
|
| 381 |
+
try:
|
| 382 |
+
from services.densenet_service import DenseNetFaces
|
| 383 |
+
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 384 |
+
logger.info(f"Loading DenseNet checkpoint from {pt_path}")
|
| 385 |
+
ckpt = torch.load(str(pt_path), map_location=settings.DEVICE, weights_only=True)
|
| 386 |
+
model = DenseNetFaces()
|
| 387 |
+
model.load_state_dict(ckpt["model_state_dict"])
|
| 388 |
+
model.to(settings.DEVICE)
|
| 389 |
+
model.eval()
|
| 390 |
+
self._densenet_model = model
|
| 391 |
+
self._densenet_meta = meta
|
| 392 |
+
logger.info("DenseNet121 face-GAN model loaded")
|
| 393 |
+
return self._densenet_model, self._densenet_meta
|
| 394 |
+
except Exception as e:
|
| 395 |
+
logger.warning(f"DenseNet load failed (continuing without it): {e}")
|
| 396 |
+
self._densenet_unavailable = True
|
| 397 |
+
return None
|
| 398 |
+
|
| 399 |
# ---------- Preload ----------
|
| 400 |
def preload_phase1(self) -> None:
|
| 401 |
"""Preload all core models to prevent lazy-loading delays during first analysis."""
|
|
|
|
| 405 |
self.load_face_detector()
|
| 406 |
self.load_efficientnet()
|
| 407 |
self.load_ffpp_model()
|
| 408 |
+
self.load_densenet()
|
| 409 |
self.load_ocr_engine()
|
| 410 |
self.load_text_model()
|
| 411 |
self.load_multilang_text_model()
|
scripts/convert_densenet_keras_to_pt.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert deepfake_densenet121_high_acc.keras → densenet121_faces.pt
|
| 2 |
+
|
| 3 |
+
No TensorFlow required at runtime. Reads weights directly from the .keras
|
| 4 |
+
ZIP/HDF5 format, maps them to a torchvision DenseNet121 + custom head, runs
|
| 5 |
+
a numeric parity check, then saves the PyTorch checkpoint.
|
| 6 |
+
|
| 7 |
+
Usage (run once, needs h5py + torch + torchvision):
|
| 8 |
+
cd <repo_root>
|
| 9 |
+
python backend/scripts/convert_densenet_keras_to_pt.py
|
| 10 |
+
|
| 11 |
+
Output:
|
| 12 |
+
backend/trained_models/densenet121_faces.pt
|
| 13 |
+
backend/trained_models/densenet121_faces_meta.json
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import io
|
| 18 |
+
import json
|
| 19 |
+
import re
|
| 20 |
+
import zipfile
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import h5py
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torchvision.models as tvm
|
| 28 |
+
|
| 29 |
+
# ── Paths ─────────────────────────────────────────────────────────────────────
|
| 30 |
+
ROOT = Path(__file__).resolve().parent.parent.parent
|
| 31 |
+
KERAS_PATH = ROOT / "backend" / "trained_models" / "deepfake_densenet121_high_acc.keras"
|
| 32 |
+
THRESH_PATH = ROOT / "backend" / "trained_models" / "deepfake_densenet121_threshold.json"
|
| 33 |
+
OUT_PT = ROOT / "backend" / "trained_models" / "densenet121_faces.pt"
|
| 34 |
+
OUT_META = ROOT / "backend" / "trained_models" / "densenet121_faces_meta.json"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# ── Custom head matching the Keras architecture ──────────────────────────────
|
| 38 |
+
# Keras head (after GlobalAvgPool): Dense(1024→256,relu) → BN(256) → Dropout →
|
| 39 |
+
# Dense(256→1,sigmoid). We fold sigmoid into inference logic; the raw logit
|
| 40 |
+
# is returned so GradCAM can back-prop cleanly.
|
| 41 |
+
class _FakeHead(nn.Module):
|
| 42 |
+
def __init__(self) -> None:
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.fc1 = nn.Linear(1024, 256)
|
| 45 |
+
self.relu = nn.ReLU(inplace=True)
|
| 46 |
+
self.bn = nn.BatchNorm1d(256)
|
| 47 |
+
self.drop = nn.Dropout(0.3)
|
| 48 |
+
self.fc2 = nn.Linear(256, 1)
|
| 49 |
+
|
| 50 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 51 |
+
x = self.relu(self.fc1(x))
|
| 52 |
+
x = self.bn(x)
|
| 53 |
+
x = self.drop(x)
|
| 54 |
+
return self.fc2(x) # raw logit; caller applies sigmoid
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class DenseNetFaces(nn.Module):
|
| 58 |
+
"""DenseNet121 backbone + custom binary head for face-GAN detection."""
|
| 59 |
+
|
| 60 |
+
def __init__(self) -> None:
|
| 61 |
+
super().__init__()
|
| 62 |
+
base = tvm.densenet121(weights=None)
|
| 63 |
+
self.features = base.features # keeps all DenseBlock + transitions
|
| 64 |
+
self.head = _FakeHead()
|
| 65 |
+
|
| 66 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 67 |
+
feat = self.features(x)
|
| 68 |
+
feat = torch.nn.functional.relu(feat, inplace=True)
|
| 69 |
+
feat = torch.nn.functional.adaptive_avg_pool2d(feat, (1, 1))
|
| 70 |
+
feat = torch.flatten(feat, 1)
|
| 71 |
+
return self.head(feat) # (B, 1) logit
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# ── Weight extraction helpers ─────────────────────────────────────────────────
|
| 75 |
+
def _load_h5(keras_path: Path) -> tuple[h5py.File, io.BytesIO]:
|
| 76 |
+
with zipfile.ZipFile(keras_path) as z:
|
| 77 |
+
buf = io.BytesIO(z.read("model.weights.h5"))
|
| 78 |
+
return h5py.File(buf, "r"), buf # caller holds buf alive
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _bn_sort_key(name: str) -> tuple[str, int]:
|
| 82 |
+
m = re.match(r"^([a-z_]+?)_?(\d+)?$", name)
|
| 83 |
+
if not m:
|
| 84 |
+
return (name, 0)
|
| 85 |
+
return (m.group(1), int(m.group(2)) if m.group(2) else 0)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _read_vars(group: h5py.Group) -> list[np.ndarray]:
|
| 89 |
+
"""Return [var_0, var_1, ...] from a 'vars' sub-group."""
|
| 90 |
+
vars_g = group["vars"]
|
| 91 |
+
return [np.array(vars_g[str(i)]) for i in range(len(vars_g))]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ── Structural name → PyTorch param-prefix mapping ───────────────────────────
|
| 95 |
+
def _build_keras_to_pt_map() -> dict[str, str]:
|
| 96 |
+
"""Hard-coded mapping of Keras DenseNet121 layer names → torchvision names.
|
| 97 |
+
|
| 98 |
+
Pattern:
|
| 99 |
+
Keras conv{stage}_block{i}_0_bn → features.denseblock{s}.denselayer{i}.norm1
|
| 100 |
+
Keras conv{stage}_block{i}_1_conv → features.denseblock{s}.denselayer{i}.conv1
|
| 101 |
+
Keras conv{stage}_block{i}_1_bn → features.denseblock{s}.denselayer{i}.norm2
|
| 102 |
+
Keras conv{stage}_block{i}_2_conv → features.denseblock{s}.denselayer{i}.conv2
|
| 103 |
+
Stages: conv2→denseblock1, conv3→denseblock2, conv4→denseblock3, conv5→denseblock4
|
| 104 |
+
Transitions: pool{k}_bn → transition{k-1}.norm, pool{k}_conv → transition{k-1}.conv
|
| 105 |
+
"""
|
| 106 |
+
m: dict[str, str] = {}
|
| 107 |
+
m["conv1_conv"] = "features.conv0"
|
| 108 |
+
m["conv1_bn"] = "features.norm0"
|
| 109 |
+
|
| 110 |
+
stage_map = {2: 1, 3: 2, 4: 3, 5: 4}
|
| 111 |
+
block_counts = {1: 6, 2: 12, 3: 24, 4: 16}
|
| 112 |
+
|
| 113 |
+
for keras_stage, pt_block in stage_map.items():
|
| 114 |
+
n_layers = block_counts[pt_block]
|
| 115 |
+
for i in range(1, n_layers + 1):
|
| 116 |
+
prefix_k = f"conv{keras_stage}_block{i}"
|
| 117 |
+
prefix_p = f"features.denseblock{pt_block}.denselayer{i}"
|
| 118 |
+
m[f"{prefix_k}_0_bn"] = f"{prefix_p}.norm1"
|
| 119 |
+
m[f"{prefix_k}_1_conv"] = f"{prefix_p}.conv1"
|
| 120 |
+
m[f"{prefix_k}_1_bn"] = f"{prefix_p}.norm2"
|
| 121 |
+
m[f"{prefix_k}_2_conv"] = f"{prefix_p}.conv2"
|
| 122 |
+
|
| 123 |
+
# Transitions (keras pool2/3/4 → pytorch transition1/2/3)
|
| 124 |
+
for pool_idx, trans_idx in [(2, 1), (3, 2), (4, 3)]:
|
| 125 |
+
m[f"pool{pool_idx}_bn"] = f"features.transition{trans_idx}.norm"
|
| 126 |
+
m[f"pool{pool_idx}_conv"] = f"features.transition{trans_idx}.conv"
|
| 127 |
+
|
| 128 |
+
m["bn"] = "features.norm5"
|
| 129 |
+
return m
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# ── Main conversion ───────────────────────────────────────────────────────────
|
| 133 |
+
def convert() -> None:
|
| 134 |
+
print(f"Reading {KERAS_PATH}")
|
| 135 |
+
hf, _buf = _load_h5(KERAS_PATH)
|
| 136 |
+
|
| 137 |
+
# -- Collect sub-model (DenseNet backbone) weights in traversal order ------
|
| 138 |
+
# The h5 keys use Python class-counter naming (conv2d, conv2d_1, ...).
|
| 139 |
+
# We rebuild counter → structural-name by walking the config layer order.
|
| 140 |
+
with zipfile.ZipFile(KERAS_PATH) as z:
|
| 141 |
+
cfg = json.loads(z.read("config.json"))
|
| 142 |
+
|
| 143 |
+
outer_layers = cfg["config"]["layers"]
|
| 144 |
+
sub_cfg = next(
|
| 145 |
+
l for l in outer_layers
|
| 146 |
+
if l.get("class_name") in ("Functional", "Model") and "densenet" in l.get("name", "")
|
| 147 |
+
)
|
| 148 |
+
sub_layers = sub_cfg["config"]["layers"]
|
| 149 |
+
|
| 150 |
+
# Walk in config order; assign counter indices to weight-bearing layers
|
| 151 |
+
conv_counter = 0
|
| 152 |
+
bn_counter = 0
|
| 153 |
+
# structural_name → h5_key
|
| 154 |
+
name_to_h5: dict[str, str] = {}
|
| 155 |
+
for lc in sub_layers:
|
| 156 |
+
cls = lc.get("class_name", "")
|
| 157 |
+
name = lc.get("name", "")
|
| 158 |
+
if cls == "Conv2D":
|
| 159 |
+
h5_key = "conv2d" if conv_counter == 0 else f"conv2d_{conv_counter}"
|
| 160 |
+
name_to_h5[name] = h5_key
|
| 161 |
+
conv_counter += 1
|
| 162 |
+
elif cls == "BatchNormalization":
|
| 163 |
+
h5_key = "batch_normalization" if bn_counter == 0 else f"batch_normalization_{bn_counter}"
|
| 164 |
+
name_to_h5[name] = h5_key
|
| 165 |
+
bn_counter += 1
|
| 166 |
+
|
| 167 |
+
func_layers_h5 = hf["layers"]["functional"]["layers"]
|
| 168 |
+
keras_to_pt = _build_keras_to_pt_map()
|
| 169 |
+
|
| 170 |
+
# -- Build PyTorch model ---------------------------------------------------
|
| 171 |
+
print("Building PyTorch DenseNetFaces model …")
|
| 172 |
+
model = DenseNetFaces()
|
| 173 |
+
sd = model.state_dict()
|
| 174 |
+
|
| 175 |
+
def set_conv(pt_prefix: str, keras_w: np.ndarray) -> None:
|
| 176 |
+
# Keras: (H, W, C_in, C_out) → PyTorch: (C_out, C_in, H, W)
|
| 177 |
+
key = f"{pt_prefix}.weight"
|
| 178 |
+
assert key in sd, f"Missing key: {key}"
|
| 179 |
+
t = torch.from_numpy(keras_w.transpose(3, 2, 0, 1))
|
| 180 |
+
assert t.shape == sd[key].shape, f"Shape mismatch {key}: {t.shape} vs {sd[key].shape}"
|
| 181 |
+
sd[key] = t
|
| 182 |
+
|
| 183 |
+
def set_bn(pt_prefix: str, vars_: list[np.ndarray]) -> None:
|
| 184 |
+
# Keras vars order: [gamma, beta, moving_mean, moving_var]
|
| 185 |
+
for keras_idx, pt_suffix in [(0, "weight"), (1, "bias"),
|
| 186 |
+
(2, "running_mean"), (3, "running_var")]:
|
| 187 |
+
key = f"{pt_prefix}.{pt_suffix}"
|
| 188 |
+
assert key in sd, f"Missing key: {key}"
|
| 189 |
+
t = torch.from_numpy(vars_[keras_idx])
|
| 190 |
+
assert t.shape == sd[key].shape, f"Shape mismatch {key}: {t.shape} vs {sd[key].shape}"
|
| 191 |
+
sd[key] = t
|
| 192 |
+
# PyTorch BN also has num_batches_tracked — leave at 0
|
| 193 |
+
|
| 194 |
+
# -- Transfer backbone weights -------------------------------------------
|
| 195 |
+
for keras_name, pt_prefix in keras_to_pt.items():
|
| 196 |
+
h5_key = name_to_h5.get(keras_name)
|
| 197 |
+
if h5_key is None:
|
| 198 |
+
raise KeyError(f"Keras layer '{keras_name}' not found in config traversal")
|
| 199 |
+
|
| 200 |
+
if h5_key not in func_layers_h5:
|
| 201 |
+
raise KeyError(f"h5 key '{h5_key}' not found under functional/layers")
|
| 202 |
+
|
| 203 |
+
layer_group = func_layers_h5[h5_key]
|
| 204 |
+
if "vars" not in layer_group:
|
| 205 |
+
raise ValueError(f"No 'vars' under functional/layers/{h5_key}")
|
| 206 |
+
|
| 207 |
+
vars_ = _read_vars(layer_group)
|
| 208 |
+
|
| 209 |
+
if keras_name.endswith("_conv") or keras_name == "conv1_conv":
|
| 210 |
+
set_conv(pt_prefix, vars_[0]) # conv has only weights (no bias; use_bias=False)
|
| 211 |
+
else:
|
| 212 |
+
set_bn(pt_prefix, vars_)
|
| 213 |
+
|
| 214 |
+
print(f" Backbone: {len(keras_to_pt)} layers transferred")
|
| 215 |
+
|
| 216 |
+
# -- Transfer custom head weights ----------------------------------------
|
| 217 |
+
outer_h5 = hf["layers"]
|
| 218 |
+
|
| 219 |
+
# Dense(1024→256): vars[0]=(1024,256), vars[1]=(256,)
|
| 220 |
+
dense_vars = _read_vars(outer_h5["dense"])
|
| 221 |
+
sd["head.fc1.weight"] = torch.from_numpy(dense_vars[0].T) # (256, 1024)
|
| 222 |
+
sd["head.fc1.bias"] = torch.from_numpy(dense_vars[1])
|
| 223 |
+
|
| 224 |
+
# BN(256): vars[0]=gamma, [1]=beta, [2]=moving_mean, [3]=moving_var
|
| 225 |
+
bn_vars = _read_vars(outer_h5["batch_normalization"])
|
| 226 |
+
for keras_idx, pt_suffix in [(0, "weight"), (1, "bias"),
|
| 227 |
+
(2, "running_mean"), (3, "running_var")]:
|
| 228 |
+
sd[f"head.bn.{pt_suffix}"] = torch.from_numpy(bn_vars[keras_idx])
|
| 229 |
+
|
| 230 |
+
# Dense(256→1): vars[0]=(256,1), vars[1]=(1,)
|
| 231 |
+
dense1_vars = _read_vars(outer_h5["dense_1"])
|
| 232 |
+
sd["head.fc2.weight"] = torch.from_numpy(dense1_vars[0].T) # (1, 256)
|
| 233 |
+
sd["head.fc2.bias"] = torch.from_numpy(dense1_vars[1])
|
| 234 |
+
|
| 235 |
+
print(" Head: fc1, bn, fc2 transferred")
|
| 236 |
+
|
| 237 |
+
model.load_state_dict(sd)
|
| 238 |
+
model.eval()
|
| 239 |
+
hf.close()
|
| 240 |
+
|
| 241 |
+
# -- Parity check ----------------------------------------------------------
|
| 242 |
+
print("Running parity check (random 224x224 input) …")
|
| 243 |
+
# DenseNet preprocess: ImageNet mean/std after [0,1] normalisation
|
| 244 |
+
# (same for Keras 'torch' mode and torchvision default)
|
| 245 |
+
MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
|
| 246 |
+
STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
|
| 247 |
+
|
| 248 |
+
rng = np.random.default_rng(0)
|
| 249 |
+
raw = rng.integers(0, 256, (1, 224, 224, 3), dtype=np.uint8).astype(np.float32)
|
| 250 |
+
tensor = torch.from_numpy(raw).permute(0, 3, 1, 2) / 255.0 # (1,3,224,224)
|
| 251 |
+
tensor = (tensor - MEAN) / STD
|
| 252 |
+
|
| 253 |
+
with torch.no_grad():
|
| 254 |
+
logit = model(tensor)
|
| 255 |
+
score = torch.sigmoid(logit).item()
|
| 256 |
+
print(f" Parity output (real_prob): {score:.6f} [sanity: should be in (0,1)]")
|
| 257 |
+
assert 0.0 < score < 1.0, "Sigmoid output out of range — weight transfer may have failed"
|
| 258 |
+
|
| 259 |
+
# -- Save checkpoint -------------------------------------------------------
|
| 260 |
+
print(f"Saving {OUT_PT}")
|
| 261 |
+
torch.save({"model_state_dict": model.state_dict()}, OUT_PT)
|
| 262 |
+
|
| 263 |
+
thresh_data = json.loads(THRESH_PATH.read_text(encoding="utf-8"))
|
| 264 |
+
meta = {
|
| 265 |
+
"threshold": thresh_data["threshold"], # 0.7597
|
| 266 |
+
"image_size": thresh_data["image_size"], # 224
|
| 267 |
+
"label_mapping": thresh_data["label_mapping"],
|
| 268 |
+
"score_meaning": thresh_data["score_meaning"],
|
| 269 |
+
"normalize_mean": [0.485, 0.456, 0.406],
|
| 270 |
+
"normalize_std": [0.229, 0.224, 0.225],
|
| 271 |
+
"source_keras": "deepfake_densenet121_high_acc.keras",
|
| 272 |
+
"architecture": "DenseNet121 + GlobalAvgPool + Linear(1024,256)+ReLU+BN+Dropout(0.3)+Linear(256,1)+Sigmoid",
|
| 273 |
+
}
|
| 274 |
+
OUT_META.write_text(json.dumps(meta, indent=2), encoding="utf-8")
|
| 275 |
+
print(f"Saving {OUT_META}")
|
| 276 |
+
print("\nDone. Conversion successful.")
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
if __name__ == "__main__":
|
| 280 |
+
convert()
|
services/densenet_service.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DenseNet121 face-GAN inference service.
|
| 2 |
+
|
| 3 |
+
The model outputs a sigmoid real_probability in [0, 1].
|
| 4 |
+
Threshold (from training) is 0.7597 (Youden's J on val ROC):
|
| 5 |
+
score >= threshold → Real, score < threshold → Fake.
|
| 6 |
+
|
| 7 |
+
fake_prob is mapped with a piecewise-linear calibration anchored so that:
|
| 8 |
+
score = 1.0 → fake_prob = 0.0 (confident real)
|
| 9 |
+
score = threshold → fake_prob = 0.5 (decision boundary)
|
| 10 |
+
score = 0.0 → fake_prob = 1.0 (confident fake)
|
| 11 |
+
This respects the trained threshold without needing an extra isotonic fit.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
import torchvision.models as tvm
|
| 21 |
+
from loguru import logger
|
| 22 |
+
from PIL import Image
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ── Model architecture (must match convert_densenet_keras_to_pt.py) ──────────
|
| 26 |
+
class _FakeHead(nn.Module):
|
| 27 |
+
def __init__(self) -> None:
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.fc1 = nn.Linear(1024, 256)
|
| 30 |
+
self.relu = nn.ReLU(inplace=True)
|
| 31 |
+
self.bn = nn.BatchNorm1d(256)
|
| 32 |
+
self.drop = nn.Dropout(0.3)
|
| 33 |
+
self.fc2 = nn.Linear(256, 1)
|
| 34 |
+
|
| 35 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 36 |
+
return self.fc2(self.drop(self.bn(self.relu(self.fc1(x)))))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class DenseNetFaces(nn.Module):
|
| 40 |
+
"""DenseNet121 + custom head for face-GAN binary detection."""
|
| 41 |
+
|
| 42 |
+
def __init__(self) -> None:
|
| 43 |
+
super().__init__()
|
| 44 |
+
base = tvm.densenet121(weights=None)
|
| 45 |
+
self.features = base.features
|
| 46 |
+
self.head = _FakeHead()
|
| 47 |
+
|
| 48 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 49 |
+
feat = torch.nn.functional.relu(self.features(x), inplace=True)
|
| 50 |
+
feat = torch.nn.functional.adaptive_avg_pool2d(feat, (1, 1))
|
| 51 |
+
feat = torch.flatten(feat, 1)
|
| 52 |
+
return self.head(feat) # (B, 1) raw logit
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ── Preprocessing ─────────────────────────────────────────────────────────────
|
| 56 |
+
_MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
|
| 57 |
+
_STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _preprocess(pil_img: Image.Image, image_size: int, device: str) -> torch.Tensor:
|
| 61 |
+
img = pil_img.convert("RGB").resize((image_size, image_size), Image.BILINEAR)
|
| 62 |
+
arr = np.array(img, dtype=np.float32) / 255.0 # (H, W, 3) → [0, 1]
|
| 63 |
+
t = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0) # (1, 3, H, W)
|
| 64 |
+
mean = _MEAN.to(device)
|
| 65 |
+
std = _STD.to(device)
|
| 66 |
+
return (t.to(device) - mean) / std
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ── Calibrated fake_prob ──────────────────────────────────────────────────────
|
| 70 |
+
def _calibrated_fake_prob(score_real: float, threshold: float) -> float:
|
| 71 |
+
"""Piecewise-linear map: score=threshold → 0.5, score=1 → 0, score=0 → 1."""
|
| 72 |
+
if score_real >= threshold:
|
| 73 |
+
return 0.5 * (1.0 - score_real) / max(1.0 - threshold, 1e-8)
|
| 74 |
+
else:
|
| 75 |
+
return 0.5 + 0.5 * (threshold - score_real) / max(threshold, 1e-8)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ── Public inference entry point ──────────────────────────────────────────────
|
| 79 |
+
def detect_image(
|
| 80 |
+
pil_img: Image.Image,
|
| 81 |
+
model: DenseNetFaces,
|
| 82 |
+
meta: dict,
|
| 83 |
+
device: str = "cpu",
|
| 84 |
+
) -> dict:
|
| 85 |
+
"""Run DenseNet121 inference on a PIL image.
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
score_real – raw sigmoid output in [0, 1]
|
| 89 |
+
fake_prob – calibrated fake probability in [0, 1]
|
| 90 |
+
threshold – Youden's J threshold used for binary verdict
|
| 91 |
+
label – "Real" or "Fake" based on threshold
|
| 92 |
+
"""
|
| 93 |
+
threshold = float(meta.get("threshold", 0.7597))
|
| 94 |
+
image_size = int(meta.get("image_size", 224))
|
| 95 |
+
|
| 96 |
+
tensor = _preprocess(pil_img, image_size, device)
|
| 97 |
+
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
logit = model(tensor)
|
| 100 |
+
score_real = float(torch.sigmoid(logit).item())
|
| 101 |
+
|
| 102 |
+
fake_prob = _calibrated_fake_prob(score_real, threshold)
|
| 103 |
+
label = "Real" if score_real >= threshold else "Fake"
|
| 104 |
+
|
| 105 |
+
return {
|
| 106 |
+
"score_real": score_real,
|
| 107 |
+
"fake_prob": fake_prob,
|
| 108 |
+
"threshold": threshold,
|
| 109 |
+
"label": label,
|
| 110 |
+
}
|
services/image_service.py
CHANGED
|
@@ -116,6 +116,26 @@ def _crop_face_for_face_model(pil_img: Image.Image) -> Image.Image:
|
|
| 116 |
return pil_img
|
| 117 |
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
def _classify_ffpp(pil_img: Image.Image) -> Optional[Tuple[float, dict[str, float]]]:
|
| 120 |
"""Run the FFPP-fine-tuned ViT (Phase 11.3). Returns (fake_prob, all_scores) or None."""
|
| 121 |
loader = get_model_loader()
|
|
@@ -233,19 +253,20 @@ def _classify_no_face(
|
|
| 233 |
|
| 234 |
|
| 235 |
def _looks_like_video_frame(pil_img: Image.Image) -> bool:
|
| 236 |
-
"""Return True when the image is likely a frame extracted from video.
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
"""
|
| 243 |
w, h = pil_img.size
|
| 244 |
-
if max(w, h) >
|
| 245 |
return False
|
| 246 |
aspect = w / h
|
| 247 |
-
|
| 248 |
-
|
|
|
|
| 249 |
|
| 250 |
|
| 251 |
def _has_gan_artifact(artifacts: list[ArtifactIndicator]) -> bool:
|
|
@@ -351,6 +372,15 @@ def classify_image(
|
|
| 351 |
models_used.append("ffpp-vit-local")
|
| 352 |
scores_out.update({f"ffpp_{k}": v for k, v in ffpp_scores.items()})
|
| 353 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
if not settings.ENSEMBLE_MODE:
|
| 355 |
if ffpp_fake_prob is not None:
|
| 356 |
combined = 0.4 * vit_fake_prob + 0.6 * ffpp_fake_prob
|
|
@@ -380,30 +410,45 @@ def classify_image(
|
|
| 380 |
scores_out["efficientnet_real"] = 1.0 - eff_fake_prob
|
| 381 |
scores_out["efficientnet_calibrator_applied"] = 1.0 if eff_result.get("calibrator_applied") else 0.0
|
| 382 |
|
| 383 |
-
# ── Face-stack composite (FFPP + ViT + EffNet) ──
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
|
| 401 |
# ── Phase A2/A3: unified evidence fusion (face-stack + general + forensics + EXIF + VLM) ──
|
| 402 |
-
# Video-frame detection: face-swap deepfakes come from video. The AI-image
|
| 403 |
-
# detectors (trained on synthesised stills) are unreliable for this class,
|
| 404 |
-
# so we shift weight toward the face-swap-trained models when the input
|
| 405 |
-
# looks like a compressed video frame.
|
| 406 |
-
is_video_frame = _looks_like_video_frame(pil_img)
|
| 407 |
w_face_stack = settings.VIDEO_FRAME_FACE_STACK_WEIGHT if is_video_frame else settings.FACE_STACK_WEIGHT_FACE
|
| 408 |
w_general = settings.VIDEO_FRAME_GENERAL_WEIGHT if is_video_frame else settings.GENERAL_WEIGHT_FACE
|
| 409 |
w_forensics = settings.VIDEO_FRAME_FORENSICS_WEIGHT if is_video_frame else settings.FORENSICS_WEIGHT_FACE
|
|
|
|
| 116 |
return pil_img
|
| 117 |
|
| 118 |
|
| 119 |
+
def _classify_densenet(pil_img: Image.Image) -> Optional[Tuple[float, dict[str, float]]]:
|
| 120 |
+
"""Run DenseNet121 face-GAN classifier. Returns (fake_prob, all_scores) or None."""
|
| 121 |
+
loader = get_model_loader()
|
| 122 |
+
result = loader.load_densenet()
|
| 123 |
+
if result is None:
|
| 124 |
+
return None
|
| 125 |
+
model, meta = result
|
| 126 |
+
try:
|
| 127 |
+
from services.densenet_service import detect_image
|
| 128 |
+
out = detect_image(pil_img, model, meta, device=settings.DEVICE)
|
| 129 |
+
scores = {
|
| 130 |
+
"densenet_real": out["score_real"],
|
| 131 |
+
"densenet_fake": out["fake_prob"],
|
| 132 |
+
}
|
| 133 |
+
return out["fake_prob"], scores
|
| 134 |
+
except Exception as e:
|
| 135 |
+
logger.warning(f"DenseNet inference failed: {e}")
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
def _classify_ffpp(pil_img: Image.Image) -> Optional[Tuple[float, dict[str, float]]]:
|
| 140 |
"""Run the FFPP-fine-tuned ViT (Phase 11.3). Returns (fake_prob, all_scores) or None."""
|
| 141 |
loader = get_model_loader()
|
|
|
|
| 253 |
|
| 254 |
|
| 255 |
def _looks_like_video_frame(pil_img: Image.Image) -> bool:
|
| 256 |
+
"""Return True when the image is very likely a frame extracted from video.
|
| 257 |
|
| 258 |
+
Requires BOTH a low resolution (≤720px long side, typical for extracted
|
| 259 |
+
deepfake frames) AND a tight aspect-ratio match (±0.03) to a standard video
|
| 260 |
+
ratio. 1:1 and 4:3 are excluded because they overlap heavily with common
|
| 261 |
+
photo formats and cause too many false positives.
|
| 262 |
"""
|
| 263 |
w, h = pil_img.size
|
| 264 |
+
if max(w, h) > 720:
|
| 265 |
return False
|
| 266 |
aspect = w / h
|
| 267 |
+
# Exclude 1:1 and 4:3 — too common in photos to be a reliable video signal
|
| 268 |
+
video_ratios = [16 / 9, 9 / 16, 3 / 4]
|
| 269 |
+
return any(abs(aspect - r) < 0.03 for r in video_ratios)
|
| 270 |
|
| 271 |
|
| 272 |
def _has_gan_artifact(artifacts: list[ArtifactIndicator]) -> bool:
|
|
|
|
| 372 |
models_used.append("ffpp-vit-local")
|
| 373 |
scores_out.update({f"ffpp_{k}": v for k, v in ffpp_scores.items()})
|
| 374 |
|
| 375 |
+
# DenseNet121 inference (face-GAN specialist — face-present path only).
|
| 376 |
+
densenet_fake_prob: Optional[float] = None
|
| 377 |
+
if settings.DENSENET_ENABLED and face_present_for_route:
|
| 378 |
+
dn_res = _classify_densenet(pil_img)
|
| 379 |
+
if dn_res is not None:
|
| 380 |
+
densenet_fake_prob, dn_scores = dn_res
|
| 381 |
+
models_used.append("densenet121-faces")
|
| 382 |
+
scores_out.update(dn_scores)
|
| 383 |
+
|
| 384 |
if not settings.ENSEMBLE_MODE:
|
| 385 |
if ffpp_fake_prob is not None:
|
| 386 |
combined = 0.4 * vit_fake_prob + 0.6 * ffpp_fake_prob
|
|
|
|
| 410 |
scores_out["efficientnet_real"] = 1.0 - eff_fake_prob
|
| 411 |
scores_out["efficientnet_calibrator_applied"] = 1.0 if eff_result.get("calibrator_applied") else 0.0
|
| 412 |
|
| 413 |
+
# ── Face-stack composite (DenseNet + FFPP + ViT + EffNet) ──────────────
|
| 414 |
+
# Video-frame path shifts weight to FFPP/EffNet; still-image path gives
|
| 415 |
+
# DenseNet the lead (trained specifically on GAN still-face portraits).
|
| 416 |
+
is_video_frame = _looks_like_video_frame(pil_img)
|
| 417 |
+
|
| 418 |
+
def _weighted(probs: dict[str, float]) -> float:
|
| 419 |
+
total = sum(probs.values())
|
| 420 |
+
return sum(v * w for v, w in probs.items()) / total if total else 0.0
|
| 421 |
+
|
| 422 |
+
available: dict[str, float] = {}
|
| 423 |
+
if densenet_fake_prob is not None:
|
| 424 |
+
w_dn = settings.DENSENET_VIDEO_WEIGHT if is_video_frame else settings.DENSENET_WEIGHT_FACE
|
| 425 |
+
available["densenet"] = w_dn
|
| 426 |
+
if ffpp_fake_prob is not None:
|
| 427 |
+
w_ffpp = settings.VIDEO_FFPP_WEIGHT_FACE if is_video_frame else settings.FFPP_WEIGHT_FACE
|
| 428 |
+
available["ffpp"] = w_ffpp
|
| 429 |
+
if eff_fake_prob is not None and face_present:
|
| 430 |
+
w_eff = settings.VIDEO_EFFNET_WEIGHT_FACE if is_video_frame else settings.EFFNET_WEIGHT_FACE
|
| 431 |
+
available["eff"] = w_eff
|
| 432 |
+
# ViT always present
|
| 433 |
+
w_vit = settings.VIDEO_VIT_WEIGHT_FACE if is_video_frame else settings.VIT_WEIGHT_FACE
|
| 434 |
+
available["vit"] = w_vit
|
| 435 |
+
|
| 436 |
+
prob_map: dict[str, float] = {}
|
| 437 |
+
if "densenet" in available:
|
| 438 |
+
prob_map["densenet"] = densenet_fake_prob * available["densenet"]
|
| 439 |
+
if "ffpp" in available:
|
| 440 |
+
prob_map["ffpp"] = ffpp_fake_prob * available["ffpp"]
|
| 441 |
+
if "eff" in available:
|
| 442 |
+
prob_map["eff"] = eff_fake_prob * available["eff"]
|
| 443 |
+
prob_map["vit"] = vit_fake_prob * available["vit"]
|
| 444 |
+
|
| 445 |
+
total_w = sum(available.values())
|
| 446 |
+
face_stack_prob = sum(prob_map.values()) / total_w if total_w else vit_fake_prob
|
| 447 |
+
|
| 448 |
+
active = [k for k in ["densenet", "ffpp", "eff", "vit"] if k in available]
|
| 449 |
+
face_stack_method = "_".join(active)
|
| 450 |
|
| 451 |
# ── Phase A2/A3: unified evidence fusion (face-stack + general + forensics + EXIF + VLM) ──
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
w_face_stack = settings.VIDEO_FRAME_FACE_STACK_WEIGHT if is_video_frame else settings.FACE_STACK_WEIGHT_FACE
|
| 453 |
w_general = settings.VIDEO_FRAME_GENERAL_WEIGHT if is_video_frame else settings.GENERAL_WEIGHT_FACE
|
| 454 |
w_forensics = settings.VIDEO_FRAME_FORENSICS_WEIGHT if is_video_frame else settings.FORENSICS_WEIGHT_FACE
|
services/llm_explainer.py
CHANGED
|
@@ -330,7 +330,7 @@ class _GeminiProvider(_LLMProvider):
|
|
| 330 |
self.model = settings.LLM_MODEL
|
| 331 |
self._config = types.GenerateContentConfig(
|
| 332 |
temperature=0.3,
|
| 333 |
-
max_output_tokens=
|
| 334 |
response_mime_type="application/json",
|
| 335 |
)
|
| 336 |
|
|
@@ -352,7 +352,7 @@ class _OpenAIProvider(_LLMProvider):
|
|
| 352 |
model=self.model,
|
| 353 |
messages=[{"role": "user", "content": prompt}],
|
| 354 |
temperature=0.3,
|
| 355 |
-
max_tokens=
|
| 356 |
response_format={"type": "json_object"},
|
| 357 |
)
|
| 358 |
return response.choices[0].message.content or ""
|
|
@@ -372,7 +372,7 @@ class _GroqProvider(_LLMProvider):
|
|
| 372 |
model=self.model,
|
| 373 |
messages=[{"role": "user", "content": prompt}],
|
| 374 |
temperature=0.3,
|
| 375 |
-
max_tokens=
|
| 376 |
response_format={"type": "json_object"},
|
| 377 |
)
|
| 378 |
return response.choices[0].message.content or ""
|
|
@@ -458,6 +458,33 @@ def _get_provider() -> _ProviderChain:
|
|
| 458 |
return _provider_instance
|
| 459 |
|
| 460 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
def _parse_llm_response(raw: str) -> tuple[str, list[SignalObservation], list[str]]:
|
| 462 |
"""Parse the LLM's JSON response into (paragraph, signals, bullets).
|
| 463 |
Handles cases where the LLM wraps output in markdown fences.
|
|
@@ -468,7 +495,12 @@ def _parse_llm_response(raw: str) -> tuple[str, list[SignalObservation], list[st
|
|
| 468 |
lines = [l for l in lines if not l.strip().startswith("```")]
|
| 469 |
text = "\n".join(lines).strip()
|
| 470 |
|
| 471 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
paragraph = parsed.get("paragraph", "")
|
| 473 |
|
| 474 |
raw_signals = parsed.get("signals", [])
|
|
|
|
| 330 |
self.model = settings.LLM_MODEL
|
| 331 |
self._config = types.GenerateContentConfig(
|
| 332 |
temperature=0.3,
|
| 333 |
+
max_output_tokens=1024,
|
| 334 |
response_mime_type="application/json",
|
| 335 |
)
|
| 336 |
|
|
|
|
| 352 |
model=self.model,
|
| 353 |
messages=[{"role": "user", "content": prompt}],
|
| 354 |
temperature=0.3,
|
| 355 |
+
max_tokens=1024,
|
| 356 |
response_format={"type": "json_object"},
|
| 357 |
)
|
| 358 |
return response.choices[0].message.content or ""
|
|
|
|
| 372 |
model=self.model,
|
| 373 |
messages=[{"role": "user", "content": prompt}],
|
| 374 |
temperature=0.3,
|
| 375 |
+
max_tokens=1024,
|
| 376 |
response_format={"type": "json_object"},
|
| 377 |
)
|
| 378 |
return response.choices[0].message.content or ""
|
|
|
|
| 458 |
return _provider_instance
|
| 459 |
|
| 460 |
|
| 461 |
+
def _repair_truncated_json(text: str) -> str:
|
| 462 |
+
"""Close unclosed braces/brackets so a truncated JSON string becomes parseable."""
|
| 463 |
+
stack = []
|
| 464 |
+
in_string = False
|
| 465 |
+
escape = False
|
| 466 |
+
for ch in text:
|
| 467 |
+
if escape:
|
| 468 |
+
escape = False
|
| 469 |
+
continue
|
| 470 |
+
if ch == "\\" and in_string:
|
| 471 |
+
escape = True
|
| 472 |
+
continue
|
| 473 |
+
if ch == '"':
|
| 474 |
+
in_string = not in_string
|
| 475 |
+
continue
|
| 476 |
+
if in_string:
|
| 477 |
+
continue
|
| 478 |
+
if ch in "{[":
|
| 479 |
+
stack.append("}" if ch == "{" else "]")
|
| 480 |
+
elif ch in "}]" and stack:
|
| 481 |
+
stack.pop()
|
| 482 |
+
# If we're mid-string, close it first
|
| 483 |
+
suffix = '"' if in_string else ""
|
| 484 |
+
suffix += "".join(reversed(stack))
|
| 485 |
+
return text + suffix
|
| 486 |
+
|
| 487 |
+
|
| 488 |
def _parse_llm_response(raw: str) -> tuple[str, list[SignalObservation], list[str]]:
|
| 489 |
"""Parse the LLM's JSON response into (paragraph, signals, bullets).
|
| 490 |
Handles cases where the LLM wraps output in markdown fences.
|
|
|
|
| 495 |
lines = [l for l in lines if not l.strip().startswith("```")]
|
| 496 |
text = "\n".join(lines).strip()
|
| 497 |
|
| 498 |
+
try:
|
| 499 |
+
parsed = json.loads(text)
|
| 500 |
+
except json.JSONDecodeError:
|
| 501 |
+
# Truncated JSON — try to recover by closing unclosed braces/brackets
|
| 502 |
+
repaired = _repair_truncated_json(text)
|
| 503 |
+
parsed = json.loads(repaired)
|
| 504 |
paragraph = parsed.get("paragraph", "")
|
| 505 |
|
| 506 |
raw_signals = parsed.get("signals", [])
|
services/news_lookup.py
CHANGED
|
@@ -103,22 +103,9 @@ def _query_attempts(q: str, country: Optional[str]) -> list[dict]:
|
|
| 103 |
latest_params["_url"] = settings.NEWS_API_BASE_URL
|
| 104 |
if country_code:
|
| 105 |
latest_params["country"] = country_code
|
| 106 |
-
|
| 107 |
-
latest_params["timeframe"] = recent_window
|
| 108 |
attempts.append(latest_params)
|
| 109 |
|
| 110 |
-
archive_key = (country_code, "archive")
|
| 111 |
-
if archive_key not in seen:
|
| 112 |
-
seen.add(archive_key)
|
| 113 |
-
archive_params = dict(base)
|
| 114 |
-
archive_params["_endpoint"] = "archive"
|
| 115 |
-
archive_params["_url"] = settings.NEWS_API_ARCHIVE_BASE_URL
|
| 116 |
-
archive_params["from_date"] = archive_from
|
| 117 |
-
archive_params["to_date"] = archive_to
|
| 118 |
-
if country_code:
|
| 119 |
-
archive_params["country"] = country_code
|
| 120 |
-
attempts.append(archive_params)
|
| 121 |
-
|
| 122 |
return attempts
|
| 123 |
|
| 124 |
|
|
|
|
| 103 |
latest_params["_url"] = settings.NEWS_API_BASE_URL
|
| 104 |
if country_code:
|
| 105 |
latest_params["country"] = country_code
|
| 106 |
+
# timeframe is a paid-plan feature; omit to avoid 422 on free plans
|
|
|
|
| 107 |
attempts.append(latest_params)
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
return attempts
|
| 110 |
|
| 111 |
|
trained_models/Colab_ViT_Training.ipynb
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
trained_models/config.json
DELETED
|
@@ -1,34 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"architectures": [
|
| 3 |
-
"ViTForImageClassification"
|
| 4 |
-
],
|
| 5 |
-
"attention_probs_dropout_prob": 0.0,
|
| 6 |
-
"dtype": "float32",
|
| 7 |
-
"encoder_stride": 16,
|
| 8 |
-
"hidden_act": "gelu",
|
| 9 |
-
"hidden_dropout_prob": 0.0,
|
| 10 |
-
"hidden_size": 768,
|
| 11 |
-
"id2label": {
|
| 12 |
-
"0": "fake",
|
| 13 |
-
"1": "real"
|
| 14 |
-
},
|
| 15 |
-
"image_size": 224,
|
| 16 |
-
"initializer_range": 0.02,
|
| 17 |
-
"intermediate_size": 3072,
|
| 18 |
-
"label2id": {
|
| 19 |
-
"fake": "0",
|
| 20 |
-
"real": "1"
|
| 21 |
-
},
|
| 22 |
-
"layer_norm_eps": 1e-12,
|
| 23 |
-
"model_type": "vit",
|
| 24 |
-
"num_attention_heads": 12,
|
| 25 |
-
"num_channels": 3,
|
| 26 |
-
"num_hidden_layers": 12,
|
| 27 |
-
"patch_size": 16,
|
| 28 |
-
"pooler_act": "tanh",
|
| 29 |
-
"pooler_output_size": 768,
|
| 30 |
-
"problem_type": "single_label_classification",
|
| 31 |
-
"qkv_bias": true,
|
| 32 |
-
"transformers_version": "5.0.0",
|
| 33 |
-
"use_cache": false
|
| 34 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
trained_models/deepfake_densenet121_high_acc.keras
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:4187720f272118535497e212eab9e7a9e6aae6dbe5b4243c040ee235eeb42416
|
| 3 |
-
size 41348204
|
|
|
|
|
|
|
|
|
|
|
|
trained_models/deepfake_densenet121_latest.keras
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:20656f33b285e68cf9117a167a23cce554f0f0ea8d2822e52bc98fe0a85577ba
|
| 3 |
-
size 41348204
|
|
|
|
|
|
|
|
|
|
|
|
trained_models/deepfake_densenet121_threshold.json
DELETED
|
@@ -1,9 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"threshold": 0.7596627473831177,
|
| 3 |
-
"label_mapping": {
|
| 4 |
-
"fake": 0,
|
| 5 |
-
"real": 1
|
| 6 |
-
},
|
| 7 |
-
"image_size": 224,
|
| 8 |
-
"score_meaning": "score >= threshold predicts real; score < threshold predicts fake"
|
| 9 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
trained_models/densenet121_faces.pt
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:fd7320650302fca5588b497daec135dbec4eeca3c4e2030567f105914c013fd3
|
| 3 |
-
size 29474603
|
|
|
|
|
|
|
|
|
|
|
|
trained_models/densenet121_faces_meta.json
DELETED
|
@@ -1,21 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"threshold": 0.7596627473831177,
|
| 3 |
-
"image_size": 224,
|
| 4 |
-
"label_mapping": {
|
| 5 |
-
"fake": 0,
|
| 6 |
-
"real": 1
|
| 7 |
-
},
|
| 8 |
-
"score_meaning": "score >= threshold predicts real; score < threshold predicts fake",
|
| 9 |
-
"normalize_mean": [
|
| 10 |
-
0.485,
|
| 11 |
-
0.456,
|
| 12 |
-
0.406
|
| 13 |
-
],
|
| 14 |
-
"normalize_std": [
|
| 15 |
-
0.229,
|
| 16 |
-
0.224,
|
| 17 |
-
0.225
|
| 18 |
-
],
|
| 19 |
-
"source_keras": "deepfake_densenet121_high_acc.keras",
|
| 20 |
-
"architecture": "DenseNet121 + GlobalAvgPool + Linear(1024,256)+ReLU+BN+Dropout(0.3)+Linear(256,1)+Sigmoid"
|
| 21 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
trained_models/model.safetensors
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:ba81c341754d4bff4063b244e9aedececbd5298598c5cc954228b519e32c5f2c
|
| 3 |
-
size 343223968
|
|
|
|
|
|
|
|
|
|
|
|
trained_models/training_args.bin
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:20e4abfdaf3550867003b25ade080870f7e9f67ef5a154661d5c8a2b28047ef2
|
| 3 |
-
size 5201
|
|
|
|
|
|
|
|
|
|
|
|