Spaces:
Sleeping
Sleeping
File size: 1,391 Bytes
29fa984 |
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 |
from facenet_pytorch import MTCNN, InceptionResnetV1
import torch
import numpy as np
from PIL import Image
import os
# Load models once
mtcnn = MTCNN(image_size=160, margin=20)
model = InceptionResnetV1(pretrained='vggface2').eval()
def preprocess(image):
face = mtcnn(Image.fromarray(image))
if face is None:
return None
with torch.no_grad():
embedding = model(face.unsqueeze(0)).squeeze().numpy()
return embedding
def verify_identity(_, input_image, user_dir, threshold=0.7):
input_embedding = preprocess(input_image)
if input_embedding is None:
return "❌ No face detected."
best_match = None
best_score = 0
for user in os.listdir(user_dir):
user_path = os.path.join(user_dir, user)
for file in os.listdir(user_path):
img_path = os.path.join(user_path, file)
registered_img = np.array(Image.open(img_path))
emb = preprocess(registered_img)
if emb is None:
continue
score = np.dot(input_embedding, emb) / (np.linalg.norm(input_embedding) * np.linalg.norm(emb))
if score > best_score:
best_match, best_score = user, score
if best_score >= threshold:
return f"✅ Match: {best_match} (Similarity: {best_score:.2f})"
else:
return f"❌ Unknown (Best Similarity: {best_score:.2f})"
|