Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910113 unmodified lines1516171819202122232425262728293031323334353637383940419 unmodified lines5152535455565758596061626364656667686970717273747576777879802 unmodified lines838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914016 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881896 unmodified lines1961971981992002012022032042052062072082092108 unmodified lines21922022122222322422518 unmodified lines2442452462472482495 unmodified lines255256257258259260261"""DeepShield AI — Full-Stack FastAPI BackendServes the frontend UI + deepfake detection API from one HF Space.Routes:GET / → Serves index.html (the web UI)GET /health → JSON health checkPOST /predict → Video/Photo upload → REAL/FAKE prediction"""import os3 unmodified linesimport loggingimport tempfilefrom pathlib import Pathimport cv2import torchimport numpy as npfrom PIL import Image, ImageFilefrom fastapi import FastAPI, File, UploadFile, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, FileResponsefrom fastapi.staticfiles import StaticFilesImageFile.LOAD_TRUNCATED_IMAGES = Truelogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")logger = logging.getLogger(__name__)# --- START OF IMPORT EXACTLY AS test_real.py ---sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from src.utils.helpers import load_config, get_devicefrom src.data.transforms import get_val_transformsfrom src.models.classifier import DeepfakeClassifierfrom src.utils.face_detect import FaceDetector# --- END OF IMPORT ---app = FastAPI(title="DeepShield AI",9 unmodified linesallow_headers=["*"],)DEVICE = get_device('cuda' if torch.cuda.is_available() else 'cpu')CHECKPOINT_PATH = Path("best_model.pth")MAX_FRAMES = 20MAX_FILE_MB = 30MAX_DURATION_SEC = 60# Model cachingglobal_model = Noneglobal_face_detector = Noneglobal_transform = Noneglobal_dual_input = Truedef load_model_and_detector():global global_model, global_face_detector, global_transform, global_dual_inputif global_model is not None:return global_model, global_face_detector, global_transform, global_dual_inputckpt_path_to_load = Noneif not CHECKPOINT_PATH.exists():base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))fallback_path = os.path.join(base_dir, 'models2/checkpoints/best_model.pth')if not os.path.exists(fallback_path):fallback_path = os.path.join(base_dir, 'models2/checkpoints/best_mlp.pth')if os.path.exists(fallback_path):ckpt_path_to_load = fallback_pathelse:2 unmodified linesckpt_path_to_load = str(CHECKPOINT_PATH)logger.info(f"Loading checkpoint on {DEVICE} from {ckpt_path_to_load} ...")checkpoint = torch.load(ckpt_path_to_load, map_location=str(DEVICE))is_fast_mlp = ckpt_path_to_load.endswith('best_mlp.pth')dual_input = Trueif is_fast_mlp and 'feat_dim' in checkpoint:dual_input = (checkpoint['feat_dim'] == 1536)base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))config_path = os.path.join(base_dir, 'configs/config2.yaml')if os.path.exists(config_path):config = load_config(config_path)else:# Fallback if config is missing in HF Spaces standaloneconfig = {'model': {'dino_variant': 'dinov2_vitb14', 'unfreeze_last_n_blocks': 0, 'dual_input': True},'face_detection': {'margin': 40, 'confidence_threshold': 0.9},'data': {'image_size': 224}}if not is_fast_mlp:dual_input = config['model'].get('dual_input', True)face_detector = FaceDetector(margin=config['face_detection']['margin'],confidence_threshold=config['face_detection']['confidence_threshold'],image_size=config['data']['image_size'],device=str(DEVICE)) if dual_input else Nonemodel = DeepfakeClassifier(dino_variant=config['model']['dino_variant'],freeze_backbone=not is_fast_mlp,unfreeze_last_n_blocks=config['model']['unfreeze_last_n_blocks'] if not is_fast_mlp else 0,dual_input=dual_input)if is_fast_mlp:model.classifier.load_state_dict(checkpoint['model_state_dict'])else:model.load_state_dict(checkpoint['model_state_dict'] if 'model_state_dict' in checkpoint else checkpoint)model = model.to(DEVICE).eval()transform = get_val_transforms(config['data']['image_size'])global_model = modelglobal_face_detector = face_detectorglobal_transform = transformglobal_dual_input = dual_inputlogger.info(f"Model ready. dual_input={dual_input}, device={DEVICE}, is_fast_mlp={is_fast_mlp}")return model, face_detector, transform, dual_inputdef extract_frames(video_path: str, temp_dir: str, num_frames: int = MAX_FRAMES) -> list:cap = cv2.VideoCapture(video_path)16 unmodified linesreturn saveddef run_inference(frame_paths: list) -> dict:model, face_detector, transform, dual_input = load_model_and_detector()fake_probs = []with torch.no_grad():for i, p in enumerate(frame_paths):try:img = Image.open(p).convert('RGB')t_img = transform(img).unsqueeze(0).to(DEVICE)t_face = t_imgif dual_input:face = face_detector.detect_and_crop(p)if face is not None:t_face = transform(face).unsqueeze(0).to(DEVICE)probs = torch.softmax(model(t_img, t_face if dual_input else None), dim=1)prob = probs[0, 1].item()fake_probs.append(prob)except Exception as e:logger.warning(f"Skipping frame {p}: {e}")if not fake_probs:raise ValueError("No frames could be processed.")video_fake_prob = float(np.mean(fake_probs))is_fake = video_fake_prob > 0.5avg_real = 1.0 - video_fake_prob6 unmodified lines"per_frame_scores": [round(p * 100, 1) for p in fake_probs],}@app.on_event("startup")async def startup_event():try:load_model_and_detector()except Exception as e:logger.error(f"Startup model load failed: {e}")@app.get("/health")def health_check():try:8 unmodified lines"model_loaded": model_loaded,}@app.post("/predict")async def predict(file: UploadFile = File(...)):allowed_exts = {".mp4", ".mov", ".avi", ".mkv", ".jpg", ".jpeg", ".png", ".webp"}18 unmodified linesf.write(content)del contentlogger.info(f"[{job_id}] Processing: {file.filename} ({size_mb:.1f} MB)")if ext in {".mp4", ".mov", ".avi", ".mkv"}:5 unmodified linesshutil.copy(video_path, img_path)frame_paths = [str(img_path)]result = run_inference(frame_paths)result["filename"] = file.filenameresult["file_size_mb"] = round(size_mb, 2)result["job_id"] = job_id12345673 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681692 unmodified lines17217317417517617717817918018118218318418518618718818916 unmodified lines2062072082092102112122132142152162172182192202212222232242252262272282292302312322332342356 unmodified lines2422432442452462472482492502512522532542552562572588 unmodified lines26726826927027127218 unmodified lines2912922932942952962975 unmodified lines303304305306307308309"""DeepShield AI — Full-Stack FastAPI BackendServes the frontend UI + deepfake detection API from one HF Space.Self-contained version with exact architectural parity to test_real.py"""import os3 unmodified linesimport loggingimport tempfilefrom pathlib import Pathfrom functools import lru_cacheimport cv2import torchimport torch.nn as nnimport numpy as npfrom PIL import Image, ImageFilefrom facenet_pytorch import MTCNNfrom fastapi import FastAPI, File, UploadFile, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, FileResponsefrom fastapi.staticfiles import StaticFilesimport torchvision.transforms as TImageFile.LOAD_TRUNCATED_IMAGES = Truelogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")logger = logging.getLogger(__name__)# -------------------------------------------------------------# EXACT PARITY MODEL DEFINITIONS (Copied from src/ to be standalone)# -------------------------------------------------------------class DINOv2Extractor(nn.Module):def __init__(self, variant: str = 'dinov2_vitb14'):super().__init__()self.embed_dim = 768logger.info(f"Loading {variant} from torch.hub ...")self.backbone = torch.hub.load('facebookresearch/dinov2', variant, pretrained=True,)logger.info("DINOv2 loaded.")for p in self.backbone.parameters():p.requires_grad = Falsedef forward(self, x: torch.Tensor) -> torch.Tensor:return self.backbone(x)class MLPClassifier(nn.Module):def __init__(self, input_dim: int = 1536, num_classes: int = 2, dropout: float = 0.4):super().__init__()self.net = nn.Sequential(nn.Linear(input_dim, 512),nn.BatchNorm1d(512),nn.GELU(),nn.Dropout(dropout),nn.Linear(512, 256),nn.BatchNorm1d(256),nn.GELU(),nn.Dropout(dropout * 0.75),nn.Linear(256, num_classes),)def forward(self, x: torch.Tensor) -> torch.Tensor:return self.net(x)class DeepfakeDetector(nn.Module):def __init__(self, dual_input: bool = True):super().__init__()self.dual_input = dual_inputself.extractor = DINOv2Extractor('dinov2_vitb14')feat_dim = 1536 if dual_input else 768self.classifier = MLPClassifier(feat_dim)def forward(self, full_image: torch.Tensor, face_crop: torch.Tensor = None) -> torch.Tensor:full_feat = self.extractor(full_image)if self.dual_input:face_feat = self.extractor(face_crop if face_crop is not None else full_image)features = torch.cat([full_feat, face_feat], dim=1)else:features = full_featreturn self.classifier(features)# -------------------------------------------------------------# APP SETTINGS & SETUP# -------------------------------------------------------------app = FastAPI(title="DeepShield AI",9 unmodified linesallow_headers=["*"],)DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')CHECKPOINT_PATH = Path("best_model.pth")MAX_FRAMES = 20MAX_FILE_MB = 30MAX_DURATION_SEC = 60# MTCNN face detector setup to mimic src/utils/face_detect.py preciselytry:MTCNN_DETECTOR = MTCNN(image_size=224,margin=40,keep_all=False,post_process=False,device='cpu')logger.info("MTCNN face detector initialized.")except Exception as e:MTCNN_DETECTOR = Nonelogger.warning(f"MTCNN init failed (will use fallback): {e}")# Exact transform replicationTRANSFORM = T.Compose([T.Resize((224, 224)),T.CenterCrop(224),T.ToTensor(),T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])def detect_face_crop(img: Image.Image) -> Image.Image:if MTCNN_DETECTOR is None:return Nonetry:boxes, probs = MTCNN_DETECTOR.detect(img)if boxes is None or len(boxes) == 0:return Nonebest_idx = np.argmax(probs)best_prob = probs[best_idx]if best_prob < 0.9:return Nonebox = boxes[best_idx]w, h = img.sizex1, y1, x2, y2 = [int(b) for b in box]margin = 40x1 = max(0, x1 - margin)y1 = max(0, y1 - margin)x2 = min(w, x2 + margin)y2 = min(h, y2 + margin)face = img.crop((x1, y1, x2, y2))return face.resize((224, 224), Image.LANCZOS)except Exception:passreturn None@lru_cache(maxsize=1)def load_model() -> DeepfakeDetector:# First check default path, then fallback if possibleckpt_path_to_load = Noneif not CHECKPOINT_PATH.exists():fallback_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'models2/checkpoints/best_model.pth')if os.path.exists(fallback_path):ckpt_path_to_load = fallback_pathelse:2 unmodified linesckpt_path_to_load = str(CHECKPOINT_PATH)logger.info(f"Loading checkpoint on {DEVICE} from {ckpt_path_to_load} ...")ckpt = torch.load(ckpt_path_to_load, map_location=DEVICE)state = ckpt.get("model_state_dict", ckpt)# Determine architecturemlp_w = state.get("classifier.net.0.weight", None)dual = (mlp_w.shape[1] == 1536) if mlp_w is not None else Truemodel = DeepfakeDetector(dual_input=dual).to(DEVICE)model.load_state_dict(state, strict=False)model.eval()logger.info(f"Model ready. dual_input={dual}, device={DEVICE}")return modeldef extract_frames(video_path: str, temp_dir: str, num_frames: int = MAX_FRAMES) -> list:cap = cv2.VideoCapture(video_path)16 unmodified linesreturn saveddef run_inference(model: DeepfakeDetector, frame_paths: list) -> dict:fake_probs = []with torch.no_grad():for fpath in frame_paths:try:img = Image.open(fpath).convert("RGB")t_img = TRANSFORM(img).unsqueeze(0).to(DEVICE)t_face = t_imgif model.dual_input:face_crop = detect_face_crop(img)if face_crop is not None:t_face = TRANSFORM(face_crop).unsqueeze(0).to(DEVICE)logits = model(t_img, t_face if model.dual_input else None)prob = torch.softmax(logits, dim=1)[0, 1].item()fake_probs.append(prob)except Exception as e:logger.warning(f"Skipping frame {fpath}: {e}")if not fake_probs:raise ValueError("No frames could be processed.")video_fake_prob = float(np.mean(fake_probs))is_fake = video_fake_prob > 0.5avg_real = 1.0 - video_fake_prob6 unmodified lines"per_frame_scores": [round(p * 100, 1) for p in fake_probs],}# -------------------------------------------------------------# API ROUTES# -------------------------------------------------------------@app.on_event("startup")async def startup_event():try:load_model()except Exception as e:logger.error(f"Startup model load failed: {e}")@app.get("/health")def health_check():try:8 unmodified lines"model_loaded": model_loaded,}@app.post("/predict")async def predict(file: UploadFile = File(...)):allowed_exts = {".mp4", ".mov", ".avi", ".mkv", ".jpg", ".jpeg", ".png", ".webp"}18 unmodified linesf.write(content)del contentmodel = load_model()logger.info(f"[{job_id}] Processing: {file.filename} ({size_mb:.1f} MB)")if ext in {".mp4", ".mov", ".avi", ".mkv"}:5 unmodified linesshutil.copy(video_path, img_path)frame_paths = [str(img_path)]result = run_inference(model, frame_paths)result["filename"] = file.filenameresult["file_size_mb"] = round(size_mb, 2)result["job_id"] = job_id
app.py+146-98