File size: 4,868 Bytes
3ce2b1b | 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | """
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") |