Fix API rerouting for /api/infer
Browse files11 unmodified lines12131415161711 unmodified linesfrom torchvision import models, transformsfrom ultralytics import YOLOapp = FastAPI(title="DeepFake Detection API")11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326411 unmodified linesfrom torchvision import models, transformsfrom ultralytics import YOLOROOT_DIR = Path(__file__).parentDEEPFAKE_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] = Noneclf_model: Optional[nn.Module] = Nonedef create_resnet18_classifier(num_classes: int = 2) -> nn.Module:model = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1)in_features = model.fc.in_featuresmodel.fc = nn.Sequential(nn.Dropout(p=0.3),nn.Linear(in_features, num_classes),)return modeldef load_classifier_weights(model: nn.Module, path: Path) -> None:state = torch.load(path, map_location="cpu")ckpt = stateif isinstance(state, dict):for key in ("model_state_dict", "state_dict", "model"):if key in state and isinstance(state[key], dict):ckpt = state[key]breakmodel.load_state_dict(ckpt, strict=False)def b64_encode_image_bgr(img: np.ndarray) -> str:img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)ok, buf = cv2.imencode(".png", img_rgb)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))continuebox = res.boxes.xyxy[0].cpu().numpy().astype(int)x1, y1, x2, y2 = boxh, w = res.orig_img.shape[:2]bw, bh = x2 - x1, y2 - y1pad_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 outdef preprocess_crop(crop: np.ndarray) -> torch.Tensor:from PIL import Imageimg_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:global yolo_model, clf_modelif 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.post("/infer")async def infer(video: UploadFile = File(...), frame_rate: int = 5, max_frames: int = 50) -> dict: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.")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))idxs = sample_indices(total_frames, max_frames=max_frames)idx_set = set(idxs)all_frames: List[str] = []all_preds: List[dict] = []batch_frames: List[np.ndarray] = []batch_indices: List[int] = []i = 0while True:ret, frame = cap.read()if not ret:breakif 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 += 1if 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.5final_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)):p_real = float(probs[idx, 0])p_fake = float(probs[idx, 1])label = "fake" if p_fake >= p_real else "real"score = p_fake if label == "fake" else p_realimg_for_display = crop if has_face and crop is not None else orig_frameframe_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),})# --- Root application: mount API and static frontend ------------------------app = FastAPI(title="DeepFake Detection App")# Mount API at /api so it is not shadowed by the static frontendapp.mount("/api", api_app, name="api")# Serve the exported Next.js frontend if presentif FRONTEND_DIST.exists():app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend")from pathlib import Pathfrom typing import List, Optional, Tupleimport base64import cv2import numpy as npimport torchimport torch.nn as nnfrom fastapi import FastAPI, File, HTTPException, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFilesfrom torchvision import models, transformsfrom ultralytics import YOLOapp = FastAPI(title="DeepFake Detection API")
app.py+247