Download handler.py from sinara-seth/model_face_recognition_2026: direct link, hf CLI and curl.
- Browser
- Download file 2.22 kB
-
https://huggingface.co/spaces/sinara-seth/model_face_recognition_2026/resolve/main/handler.py
- Command line
-
hf download hf://spaces/sinara-seth/model_face_recognition_2026/handler.py
-
curl -L -o handler.py https://huggingface.co/spaces/sinara-seth/model_face_recognition_2026/resolve/main/handler.py
2.22 kB
| # 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)} | |