File size: 10,842 Bytes
cc54add 4d84f9c a4459f8 4d84f9c 21764e2 4d84f9c de5919d cc54add 21764e2 cc54add a2ce50d cc54add de5919d cc54add 8637c96 cc54add 8637c96 cc54add de5919d cc54add de5919d 9f3b4d9 de5919d 8f967f6 de5919d 8637c96 cc54add 8637c96 cc54add 9f3b4d9 cc54add 9f3b4d9 b743efd 9f3b4d9 b391f65 9f3b4d9 b743efd 9f3b4d9 de5919d | 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 | from pathlib import Path
from typing import List, Optional, Tuple
import base64
import cv2
import numpy as np
import torch
import torch.nn as nn
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from torchvision import models, transforms
from ultralytics import YOLO
ROOT_DIR = Path(__file__).parent
DEEPFAKE_DIR = ROOT_DIR / "DeepFakeDetection"
FRONTEND_DIST = ROOT_DIR / "frontend_dist"
YOLO_WEIGHTS_PATH = DEEPFAKE_DIR / "yolov8n-face.pt"
CLS_WEIGHTS_PATH = DEEPFAKE_DIR / "BEST_MODEL.pth"
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
imagenet_mean = [0.485, 0.456, 0.406]
imagenet_std = [0.229, 0.224, 0.225]
eval_transform = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=imagenet_mean, std=imagenet_std),
]
)
yolo_model: Optional[YOLO] = None
clf_model: Optional[nn.Module] = None
def create_resnet18_classifier(num_classes: int = 2) -> nn.Module:
model = models.resnet18(weights=None)
in_features = model.fc.in_features
model.fc = nn.Sequential(
nn.Dropout(p=0.3),
nn.Linear(in_features, num_classes),
)
return model
from pathlib import Path
from typing import List, Optional, Tuple
import base64
import cv2
import numpy as np
import torch
import torch.nn as nn
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from torchvision import models, transforms
from ultralytics import YOLO
from PIL import Image
ROOT_DIR = Path(__file__).parent
DEEPFAKE_DIR = ROOT_DIR / "DeepFakeDetection"
FRONTEND_DIST = ROOT_DIR / "frontend_dist"
YOLO_WEIGHTS_PATH = DEEPFAKE_DIR / "yolov8n-face.pt"
CLS_WEIGHTS_PATH = DEEPFAKE_DIR / "bestresnetclassweights.pth"
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
imagenet_mean = [0.485, 0.456, 0.406]
imagenet_std = [0.229, 0.224, 0.225]
eval_transform = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=imagenet_mean, std=imagenet_std),
]
)
yolo_model: Optional[YOLO] = None
clf_model: Optional[nn.Module] = None
def create_resnet18_classifier(num_classes: int = 2) -> nn.Module:
model = models.resnet18(weights=None)
in_features = model.fc.in_features
model.fc = nn.Sequential(
nn.Dropout(p=0.3),
nn.Linear(in_features, num_classes),
)
return model
def load_classifier_weights(model: nn.Module, path: Path) -> None:
state = torch.load(path, map_location="cpu")
ckpt = state
if isinstance(state, dict):
for key in ("model_state_dict", "state_dict", "model"):
if key in state and isinstance(state[key], dict):
ckpt = state[key]
break
model.load_state_dict(ckpt, strict=False)
def b64_encode_image_bgr(img: np.ndarray) -> str:
# Keep original BGR colors as they appear in the video; OpenCV's
# encoders expect BGR, so we don't convert to RGB here.
ok, buf = cv2.imencode(".png", img)
if not ok:
raise RuntimeError("Failed to encode frame")
return base64.b64encode(buf.tobytes()).decode("utf-8")
def sample_indices(total_frames: int, max_frames: int) -> List[int]:
if total_frames <= 0:
return []
n = min(max_frames, total_frames)
return np.linspace(0, total_frames - 1, n, dtype=int).tolist()
def crop_faces(frames: List[np.ndarray]) -> List[Tuple[Optional[np.ndarray], bool]]:
results = yolo_model(frames, verbose=False)
out: List[Tuple[Optional[np.ndarray], bool]] = []
for res in results:
if len(res.boxes) == 0:
out.append((None, False))
continue
box = res.boxes.xyxy[0].cpu().numpy().astype(int)
x1, y1, x2, y2 = box
h, w = res.orig_img.shape[:2]
bw, bh = x2 - x1, y2 - y1
pad_w = int((1.3 - 1) * bw / 2)
pad_h = int((1.3 - 1) * bh / 2)
x1 = max(0, x1 - pad_w)
y1 = max(0, y1 - pad_h)
x2 = min(w, x2 + pad_w)
y2 = min(h, y2 + pad_h)
crop = res.orig_img[y1:y2, x1:x2]
if crop.size == 0:
out.append((None, False))
else:
crop = cv2.resize(crop, (299, 299))
out.append((crop, True))
return out
def preprocess_crop(crop: np.ndarray) -> torch.Tensor:
img_rgb = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(img_rgb)
return eval_transform(pil_img)
# -------------------------- API sub-application -----------------------------
api_app = FastAPI(title="DeepFake Detection API")
api_app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@api_app.on_event("startup")
def load_models() -> None:
"""Eagerly load models at startup (best effort)."""
ensure_models_loaded()
def ensure_models_loaded() -> None:
"""Lazily load YOLO and classifier if they are not in memory.
This is safe to call from within request handlers and avoids relying solely
on startup events (which can behave differently when mounted).
"""
global yolo_model, clf_model
if yolo_model is not None and clf_model is not None:
return
if not YOLO_WEIGHTS_PATH.exists():
raise RuntimeError(f"YOLO weights not found at {YOLO_WEIGHTS_PATH}")
if not CLS_WEIGHTS_PATH.exists():
raise RuntimeError(f"Classifier weights not found at {CLS_WEIGHTS_PATH}")
yolo_model = YOLO(str(YOLO_WEIGHTS_PATH))
model = create_resnet18_classifier(num_classes=2)
load_classifier_weights(model, CLS_WEIGHTS_PATH)
model.to(DEVICE)
model.eval()
clf_model = model
@api_app.get("/health")
def health() -> dict:
return {"status": "ok"}
@api_app.post("/infer")
async def infer(
video: UploadFile = File(...),
# Keep params for compatibility but default to 20 frames like preprocessing
frame_rate: int = 5,
max_frames: int = 20,
) -> dict:
# Basic validation of uploaded file
if video.content_type is None or not video.content_type.startswith("video/"):
raise HTTPException(status_code=400, detail="Please upload a valid video file.")
# Ensure models are in memory (handles cases where startup didn't run)
try:
ensure_models_loaded()
except Exception as e: # surface model-loading issues clearly to the client
raise HTTPException(status_code=500, detail=f"Model loading failed: {e}")
tmp_path = ROOT_DIR / "_tmp_video.mp4"
try:
content = await video.read()
with open(tmp_path, "wb") as f:
f.write(content)
cap = cv2.VideoCapture(str(tmp_path))
if not cap.isOpened():
raise HTTPException(status_code=400, detail="Could not open video.")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Mirror preprocessing: uniformly sample exactly `max_frames` indices
# across the whole video (equivalent to np.linspace in processing_detect_n_crop).
idxs = np.linspace(0, max(0, total_frames - 1), max_frames).astype(int).tolist()
idx_set = set(idxs)
all_frames: List[str] = []
all_preds: List[dict] = []
batch_frames: List[np.ndarray] = []
batch_indices: List[int] = []
i = 0
while True:
ret, frame = cap.read()
if not ret:
break
if i in idx_set:
batch_frames.append(frame)
batch_indices.append(i)
if len(batch_frames) >= 8:
run_batch(batch_frames, batch_indices, all_frames, all_preds)
batch_frames = []
batch_indices = []
i += 1
if batch_frames:
run_batch(batch_frames, batch_indices, all_frames, all_preds)
cap.release()
if not all_frames:
raise HTTPException(status_code=400, detail="No frames could be processed.")
face_scores = [p["prob_fake"] for p in all_preds if p.get("has_face")]
if face_scores:
avg_fake = float(np.mean(face_scores))
else:
avg_fake = 0.5
final_label = "fake" if avg_fake >= 0.5 else "real"
return {
"frames": all_frames,
"predictions": all_preds,
"final_label": final_label,
"final_score": avg_fake,
}
finally:
if tmp_path.exists():
tmp_path.unlink(missing_ok=True)
def run_batch(
frames: List[np.ndarray],
indices: List[int],
out_frames: List[str],
out_preds: List[dict],
) -> None:
crops_info = crop_faces(frames)
tensors: List[torch.Tensor] = []
for crop, has_face in crops_info:
if has_face and crop is not None:
tensors.append(preprocess_crop(crop))
else:
tensors.append(torch.zeros(3, 224, 224))
batch = torch.stack(tensors, dim=0).to(DEVICE)
with torch.no_grad():
logits = clf_model(batch)
probs = torch.softmax(logits, dim=1).cpu().numpy()
for idx, (orig_frame, (crop, has_face)) in enumerate(zip(frames, crops_info)):
if has_face and crop is not None:
p_fake = float(probs[idx, 0])
p_real = float(probs[idx, 1])
label = "fake" if p_fake >= p_real else "real"
score = p_fake if label == "fake" else p_real
img_for_display = crop
else:
p_fake = 0.0
p_real = 0.0
label = "no_face"
score = 0.0
img_for_display = orig_frame
frame_b64 = b64_encode_image_bgr(img_for_display)
out_frames.append(frame_b64)
out_preds.append(
{
"frame_index": int(indices[idx]),
"label": label,
"score": float(score),
"prob_real": p_real,
"prob_fake": p_fake,
"has_face": bool(has_face and crop is not None),
}
)
# -------------------- Root app: mount API and frontend ---------------------
app = FastAPI(title="DeepFake Detection App")
# API mounted at /api so it wins over the root static mount
app.mount("/api", api_app, name="api")
if FRONTEND_DIST.exists():
app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend")
else:
@app.get("/")
def root() -> dict:
return {"message": "Frontend not built. API is at /api/infer"}
|