Add app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from torchvision import transforms
|
| 5 |
+
from transformers import DeiTModel
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# -----------------------------------------------------------------------------
|
| 10 |
+
# Model Definition (re-defined to be self-contained)
|
| 11 |
+
# -----------------------------------------------------------------------------
|
| 12 |
+
class FingerprintLivenessModel(nn.Module):
|
| 13 |
+
"""
|
| 14 |
+
Simplified model for fingerprint liveness detection.
|
| 15 |
+
DeiT-Tiny backbone (192-dim) -> Fingerprint Expert (192->512) -> Classifier (512->2)
|
| 16 |
+
"""
|
| 17 |
+
def __init__(self):
|
| 18 |
+
super(FingerprintLivenessModel, self).__init__()
|
| 19 |
+
# Load pre-trained DeiT-Tiny model
|
| 20 |
+
self.base_model = DeiTModel.from_pretrained(
|
| 21 |
+
"facebook/deit-tiny-distilled-patch16-224"
|
| 22 |
+
)
|
| 23 |
+
# Fingerprint-specific expert layer
|
| 24 |
+
self.fingerprint_expert = nn.Linear(192, 512)
|
| 25 |
+
# Final classifier (2 classes: spoof=0, live=1)
|
| 26 |
+
self.classifier = nn.Linear(512, 2)
|
| 27 |
+
|
| 28 |
+
def forward(self, pixel_values):
|
| 29 |
+
outputs = self.base_model(pixel_values)
|
| 30 |
+
cls_embeddings = outputs.last_hidden_state[:, 0, :]
|
| 31 |
+
expert_features = self.fingerprint_expert(cls_embeddings)
|
| 32 |
+
logits = self.classifier(expert_features)
|
| 33 |
+
return logits
|
| 34 |
+
|
| 35 |
+
# -----------------------------------------------------------------------------
|
| 36 |
+
# Global Variables & Initialization
|
| 37 |
+
# -----------------------------------------------------------------------------
|
| 38 |
+
DEVICE = "cpu" # Force CPU for Hugging Face Spaces free tier stability
|
| 39 |
+
MODEL_PATH = "model.pth"
|
| 40 |
+
|
| 41 |
+
def load_model():
|
| 42 |
+
if not os.path.exists(MODEL_PATH):
|
| 43 |
+
raise FileNotFoundError(f"Model weights not found at: {MODEL_PATH}")
|
| 44 |
+
|
| 45 |
+
print(f"Loading model from {MODEL_PATH}...")
|
| 46 |
+
model = FingerprintLivenessModel()
|
| 47 |
+
|
| 48 |
+
# Load weights
|
| 49 |
+
checkpoint = torch.load(MODEL_PATH, map_location=DEVICE)
|
| 50 |
+
model_state_dict = model.state_dict()
|
| 51 |
+
|
| 52 |
+
# Filter and load weights
|
| 53 |
+
filtered_checkpoint = {}
|
| 54 |
+
for key in checkpoint.keys():
|
| 55 |
+
if key.startswith('base_model') or key.startswith('fingerprint_expert') or key.startswith('classifier'):
|
| 56 |
+
if key in model_state_dict:
|
| 57 |
+
filtered_checkpoint[key] = checkpoint[key]
|
| 58 |
+
|
| 59 |
+
model.load_state_dict(filtered_checkpoint, strict=False)
|
| 60 |
+
model.to(DEVICE)
|
| 61 |
+
model.eval()
|
| 62 |
+
return model
|
| 63 |
+
|
| 64 |
+
# Initialize model once
|
| 65 |
+
try:
|
| 66 |
+
model = load_model()
|
| 67 |
+
print("Model loaded successfully!")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"Error loading model: {e}")
|
| 70 |
+
model = None
|
| 71 |
+
|
| 72 |
+
# -----------------------------------------------------------------------------
|
| 73 |
+
# Preprocessing
|
| 74 |
+
# -----------------------------------------------------------------------------
|
| 75 |
+
def preprocess_image(image):
|
| 76 |
+
normalize = transforms.Normalize(
|
| 77 |
+
mean=[0.485, 0.456, 0.406],
|
| 78 |
+
std=[0.229, 0.224, 0.225]
|
| 79 |
+
)
|
| 80 |
+
transform = transforms.Compose([
|
| 81 |
+
transforms.Resize((224, 224)),
|
| 82 |
+
transforms.ToTensor(),
|
| 83 |
+
normalize
|
| 84 |
+
])
|
| 85 |
+
return transform(image).unsqueeze(0)
|
| 86 |
+
|
| 87 |
+
# -----------------------------------------------------------------------------
|
| 88 |
+
# Prediction Function
|
| 89 |
+
# -----------------------------------------------------------------------------
|
| 90 |
+
def predict(image):
|
| 91 |
+
if model is None:
|
| 92 |
+
return "Model not loaded"
|
| 93 |
+
|
| 94 |
+
if image is None:
|
| 95 |
+
return "Please upload an image."
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
# Preprocess
|
| 99 |
+
input_tensor = preprocess_image(image).to(DEVICE)
|
| 100 |
+
|
| 101 |
+
# Inference
|
| 102 |
+
with torch.no_grad():
|
| 103 |
+
logits = model(input_tensor)
|
| 104 |
+
probs = torch.softmax(logits, dim=1)
|
| 105 |
+
|
| 106 |
+
spoof_prob = probs[0, 0].item()
|
| 107 |
+
live_prob = probs[0, 1].item()
|
| 108 |
+
|
| 109 |
+
return {
|
| 110 |
+
"Live": live_prob,
|
| 111 |
+
"Spoof": spoof_prob
|
| 112 |
+
}
|
| 113 |
+
except Exception as e:
|
| 114 |
+
return f"Error during prediction: {str(e)}"
|
| 115 |
+
|
| 116 |
+
# -----------------------------------------------------------------------------
|
| 117 |
+
# Gradio Interface
|
| 118 |
+
# -----------------------------------------------------------------------------
|
| 119 |
+
title = "Fingerprint Liveness Detection"
|
| 120 |
+
description = """
|
| 121 |
+
Upload a fingerprint image to check if it's **Live** or **Spoof**.
|
| 122 |
+
This model uses a DeiT-Tiny transformer backbone with a fingerprint-specific expert layer.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
iface = gr.Interface(
|
| 126 |
+
fn=predict,
|
| 127 |
+
inputs=gr.Image(type="pil", label="Fingerprint Image"),
|
| 128 |
+
outputs=gr.Label(num_top_classes=2, label="Prediction"),
|
| 129 |
+
title=title,
|
| 130 |
+
description=description,
|
| 131 |
+
examples=[]
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
iface.launch()
|