Refactor FastAPI app and use /api/infer endpoint
Browse filesFiles changed (2)
- app.py+39-220
- frontend/pages/analyze.jsx+1-1
42 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492507 unmodified lines25825926026126226326426526626726826927027127227327485 unmodified lines36036136236336436536636736836937037137237311 unmodified lines38538638738838939039139239339439539698 unmodified lines49549649742 unmodified linesnn.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, Tuple7 unmodified linesfrom fastapi.staticfiles import StaticFilesfrom torchvision import models, transformsfrom ultralytics import YOLOapp = FastAPI(title="DeepFake Detection API")app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)ROOT_DIR = Path(__file__).parent85 unmodified linesdef 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)@app.on_event("startup")def load_models() -> None:global yolo_model, clf_model11 unmodified linesclf_model = modelif FRONTEND_DIST.exists():app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend")@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.")98 unmodified lines"has_face": bool(has_face),})42 unmodified lines4344454647487 unmodified lines5657585960616285 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017117211 unmodified lines18418518618718818919019119219319419519619719819920098 unmodified lines29930030130230330430530630730830931031131231331431531642 unmodified linesnn.Linear(in_features, num_classes),)return modelfrom pathlib import Pathfrom typing import List, Optional, Tuple7 unmodified linesfrom fastapi.staticfiles import StaticFilesfrom torchvision import models, transformsfrom ultralytics import YOLOfrom PIL import ImageROOT_DIR = Path(__file__).parent85 unmodified linesdef 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:global yolo_model, clf_model11 unmodified linesclf_model = model@api_app.get("/health")def health() -> dict:return {"status": "ok"}@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.")98 unmodified lines"has_face": bool(has_face),})# -------------------- Root app: mount API and frontend ---------------------app = FastAPI(title="DeepFake Detection App")# API mounted at /api so it wins over the root static mountapp.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"}
49 unmodified lines5051525354555649 unmodified linesconst formData = new FormData();formData.append("video", videoFile);const base = backendUrl || ""; // empty means same originconst url = `${base}/infer?frame_rate=5&max_frames=50`;const res = await fetch(url, { method: "POST", body: formData });if (!res.ok) {const text = await res.text();49 unmodified lines5051525354555649 unmodified linesconst formData = new FormData();formData.append("video", videoFile);const base = backendUrl || ""; // empty means same originconst url = `${base}/api/infer?frame_rate=5&max_frames=50`;const res = await fetch(url, { method: "POST", body: formData });if (!res.ok) {const text = await res.text();
app.py+39-220
frontend/pages/analyze.jsx+1-1