Spaces:
Sleeping
Sleeping
| 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})" | |