File size: 2,219 Bytes
8e1d600 728d627 8e1d600 83c352b 728d627 83c352b 416ec4a 728d627 8e1d600 416ec4a 8e1d600 728d627 8e1d600 728d627 8e1d600 83c352b 8e1d600 83c352b 8e1d600 83c352b 728d627 83c352b 728d627 8e1d600 83c352b 8e1d600 83c352b 8e1d600 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | # handler.py
import torch
import torch.nn as nn
from torchvision.models import shufflenet_v2_x1_0
from torchvision import transforms
from PIL import Image
import numpy as np
class EndpointHandler:
def __init__(self, path="."):
self.device = torch.device("cpu")
self.model = self._load_model()
self.model.eval() # set to eval mode
print("[INFO] ShuffleNetV2 initialized on CPU")
# Define standard image transforms for ShuffleNetV2
self.transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
def _load_model(self):
# Load a pre-defined ShuffleNetV2 model (CPU)
# pretrained ImageNet weights
model = shufflenet_v2_x1_0(pretrained=True)
# Optional: adapt the last layer to 2 classes (live/spoof)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 2) # 2 outputs: [live, spoof]
return model
def predict(self, image: Image.Image):
"""
image: PIL Image from Gradio or Flutter
returns: dict {is_live, live_prob, spoof_prob, confidence}
"""
try:
if not isinstance(image, Image.Image):
raise ValueError("Input must be a PIL Image")
# Preprocess image
x = self.transform(image).unsqueeze(0).to(self.device) # Add batch dimension
# Run model
with torch.no_grad():
outputs = self.model(x) # shape [1, 2]
probs = torch.nn.functional.softmax(outputs[0], dim=0) # [live_prob, spoof_prob]
live_score = float(probs[0])
spoof_score = float(probs[1])
confidence = max(live_score, spoof_score)
return {
"is_live": live_score > 0.5,
"live_prob": live_score,
"spoof_prob": spoof_score,
"confidence": confidence
}
except Exception as e:
print("[ERROR] Prediction failed:", e)
return {"error": str(e)}
|