Refactor FastAPI app and use /api/infer endpoint
Browse filesFiles changed (2)
- app.py+39-220
- frontend/pages/analyze.jsx+1-1
42 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462474647487 unmodified lines5657582612622632642652662672682692702715960616285 unmodified lines14814915036336415115215315415515615715815916016116216316416516616716837016917017117211 unmodified lines18418518638838918718818919019139239319219319419519619719819920098 unmodified lines29930030130230330430530630730830931031131231331431531642 unmodified lines 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: 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)) 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: from PIL import Image
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_model
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.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 = 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)): 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_real
img_for_display = crop if has_face and crop is not None else 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), } )
# --- 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, Tuple
7 unmodified linesfrom fastapi.staticfiles import StaticFilesfrom torchvision import models, transformsfrom ultralytics import YOLO
app = FastAPI(title="DeepFake Detection API")
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)from PIL import Image
ROOT_DIR = Path(__file__).parent85 unmodified lines
def preprocess_crop(crop: np.ndarray) -> torch.Tensor: from PIL import Image
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=["*"],)
@app.on_event("startup")@api_app.on_event("startup")def load_models() -> None: global yolo_model, clf_model
11 unmodified lines clf_model = model
if FRONTEND_DIST.exists(): app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend")@api_app.get("/health")def health() -> dict: return {"status": "ok"}
@app.post("/infer")async def infer(video: UploadFile = File(...), frame_rate: int = 5, max_frames: int = 50) -> dict:@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 lines505152535354555649 unmodified lines const formData = new FormData(); formData.append("video", videoFile); const base = backendUrl || ""; // empty means same origin const url = `${base}/infer?frame_rate=5&max_frames=50`; const 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