testing__model / handler.py
sinara-seth's picture
done for script
3ce2b1b verified
Raw History Blame Contribute Delete
4.87 kB
"""
Hugging Face Inference Handler for Face Anti-Spoofing Model
"""
import torch
import torch.nn.functional as F
from torchvision import transforms
import cv2
import numpy as np
from PIL import Image
import base64
from io import BytesIO
from typing import Dict, List, Any
import os
import sys
# Add current directory to path
sys.path.append(os.path.dirname(__file__))
from nets.utils import get_model
class EndpointHandler:
def __init__(self, path=""):
"""
Initialize the handler
Args:
path: Path to the model files
"""
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load model
model_path = os.path.join(path, "shufflenetv2_0.5x.pth")
self.model = get_model(arch="shufflenetv2_0.5x", num_classes=2)
checkpoint = torch.load(model_path, map_location=self.device)
state_dict = checkpoint.get("state_dict", checkpoint)
# Remove "module." prefix if exists
clean_state = {}
for k, v in state_dict.items():
clean_state[k.replace("module.", "")] = v
self.model.load_state_dict(clean_state)
self.model.to(self.device)
self.model.eval()
# Face detector
self.face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
# Preprocessing
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]
)
])
print(f"[INFO] Model loaded on {self.device}")
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
Process inference request
Args:
data: Dictionary with 'inputs' key containing image data
Returns:
List of predictions
"""
inputs = data.pop("inputs", data)
# Handle different input formats
if isinstance(inputs, str):
# Base64 encoded image
image = self._decode_base64_image(inputs)
elif isinstance(inputs, dict) and "image" in inputs:
image = self._decode_base64_image(inputs["image"])
else:
return [{"error": "Invalid input format"}]
# Convert PIL to numpy
image_np = np.array(image)
if image_np.shape[2] == 4: # RGBA
image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
# Detect face
gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
faces = self.face_cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(100, 100)
)
if len(faces) == 0:
return [{
"label": "NO_FACE_DETECTED",
"score": 0.0,
"live_score": 0.0,
"spoof_score": 0.0
}]
# Process first detected face
x, y, w, h = faces[0]
pad = 20
h_img, w_img = image_np.shape[:2]
face_crop = image_np[
max(0, y - pad):min(h_img, y + h + pad),
max(0, x - pad):min(w_img, x + w + pad)
]
# Preprocess
face_pil = Image.fromarray(face_crop)
input_tensor = self.transform(face_pil).unsqueeze(0).to(self.device)
# Inference
with torch.no_grad():
output = self.model(input_tensor)
if isinstance(output, tuple):
output = output[0]
probs = F.softmax(output, dim=1)
live_prob = probs[0][0].item()
spoof_prob = probs[0][1].item()
# Determine label
is_live = live_prob > 0.5
label = "LIVE" if is_live else "SPOOF"
confidence = max(live_prob, spoof_prob)
return [{
"label": label,
"score": float(confidence),
"live_score": float(live_prob),
"spoof_score": float(spoof_prob),
"face_detected": True,
"face_bbox": {
"x": int(x),
"y": int(y),
"width": int(w),
"height": int(h)
}
}]
def _decode_base64_image(self, image_string: str) -> Image.Image:
"""
Decode base64 image string
"""
# Remove header if present
if "base64," in image_string:
image_string = image_string.split("base64,")[1]
image_bytes = base64.b64decode(image_string)
image = Image.open(BytesIO(image_bytes))
return image.convert("RGB")