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"}