Update app.py
Browse files123445672 unmodified lines101112131415161718181920192021242526272829222324252627282930313232333435363738373839404142434442434445464745464748495051525354555657582 unmodified lines616263565758596064656667686970717262737475767778798081828384688586878889909192939495969777989910010110210383104105851061071081091101111121131141151161171181191201211221231241251261271289697129130131132133100134135136137138139140141142143102144145146147148107108149150151152153154155156110111112113157158159160161162163164165166167116117118119120121122123168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205#!/usr/bin/env python3"""Facial Recognition Service with Gradio UICPU-only version for Hugging Face Spaces using PyTorch backendUsing DeepFace for Hugging Face Spaces compatibility"""
import warnings2 unmodified linesimport numpy as npimport cv2import gradio as grfrom deepface import DeepFace
# Suppress warningswarnings.filterwarnings('ignore')os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# InsightFace PyTorch backendfrom insightface.app import FaceAnalysis
class FacialRecognitionService: def __init__(self): """Initialize InsightFace model on CPU using PyTorch backend""" print("Loading InsightFace model (PyTorch, CPU)...") # Lightweight CPU-friendly model self.app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider']) self.app.prepare(ctx_id=-1, det_size=(640, 640)) # CPU-only print("Model loaded β
") """Initialize DeepFace with VGG-Face model""" print("Loading DeepFace model...") # Pre-load model try: DeepFace.build_model("VGG-Face") print("Model loaded β
") except Exception as e: print(f"Model loading warning: {e}")
def extract_face_embedding(self, image: np.ndarray): """Extract face embedding from an uploaded image (numpy array)""" """Extract face embedding from an uploaded image""" try: if image is None: return None
if image.shape[2] == 3: img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # DeepFace expects RGB if len(image.shape) == 2: # Grayscale img_rgb = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) elif image.shape[2] == 4: # RGBA img_rgb = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB) else: img_rgb = image
faces = self.app.get(img_rgb) if len(faces) == 0: return None
largest_face = max(faces, key=lambda x: (x.bbox[2]-x.bbox[0])*(x.bbox[3]-x.bbox[1])) return largest_face.embedding # Extract embedding embedding_objs = DeepFace.represent( img_path=img_rgb, model_name="VGG-Face", enforce_detection=True, detector_backend="opencv" ) if len(embedding_objs) > 0: return np.array(embedding_objs[0]["embedding"]) return None
except Exception as e: print(f"Error extracting embedding: {e}", file=sys.stderr)2 unmodified lines def calculate_similarity(self, emb1, emb2): """Cosine similarity normalized to 0-1""" try: norm1, norm2 = np.linalg.norm(emb1), np.linalg.norm(emb2) if norm1 == 0 or norm2 == 0: return 0.0 emb1, emb2 = emb1 / norm1, emb2 / norm2 return float((np.dot(emb1, emb2) + 1) / 2) from sklearn.metrics.pairwise import cosine_similarity similarity = cosine_similarity([emb1], [emb2])[0][0] # Convert from [-1, 1] to [0, 1] return float((similarity + 1) / 2) except: # Fallback manual calculation try: norm1, norm2 = np.linalg.norm(emb1), np.linalg.norm(emb2) if norm1 == 0 or norm2 == 0: return 0.0 return 0.0 emb1_norm, emb2_norm = emb1 / norm1, emb2 / norm2 return float((np.dot(emb1_norm, emb2_norm) + 1) / 2) except: return 0.0
def match_faces(self, target_image: np.ndarray, candidate_images: list, threshold: float = 0.6): """Match target face against candidate images""" matches = [] target_emb = self.extract_face_embedding(target_image) if target_emb is None: return "No face detected in target image" return "β No face detected in target image"
for idx, candidate in enumerate(candidate_images): if candidate is None: continue candidate_emb = self.extract_face_embedding(candidate) if candidate_emb is None: continue similarity = self.calculate_similarity(target_emb, candidate_emb) if similarity >= threshold: matches.append({ 'index': idx, 'index': idx + 1, 'confidence': similarity, 'score': int(similarity * 100) })
if not matches: return "No matches found" return "β No matches found above threshold"
return "\n".join([f"Candidate {m['index']}: {m['score']}%" for m in matches]) # Sort by confidence matches.sort(key=lambda x: x['confidence'], reverse=True) result = "β
Matches Found:\n\n" for m in matches: result += f"πΈ Candidate {m['index']}: {m['score']}% match\n" return result
# Initialize serviceprint("Initializing Facial Recognition Service...")service = FacialRecognitionService()
# Gradio functionsdef extract_face(image): """Extract embedding from single image""" if image is None: return "β Please upload an image" embedding = service.extract_face_embedding(image) if embedding is None: return "No face detected" return f"Embedding size: {len(embedding)}" return "β No face detected in image" return f"β
Face detected!\n\nEmbedding size: {len(embedding)} dimensions\nModel: VGG-Face"
def match_faces_fn(target_image, *candidate_images):def match_faces_fn(target_image, threshold, *candidate_images): """Match faces with configurable threshold""" if target_image is None: return "β Please upload a target image" candidates = [img for img in candidate_images if img is not None] if len(candidates) == 0: return "β Please upload at least one candidate image" result = service.match_faces(target_image, candidates) result = service.match_faces(target_image, candidates, threshold=threshold) return result
# Gradio UIwith gr.Blocks() as demo: gr.Markdown("## Facial Recognition Service (InsightFace, CPU Only)")with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown(""" # π Facial Recognition Service ### Powered by DeepFace (VGG-Face model) Upload images to extract face embeddings or match faces across multiple images. """) with gr.Tab("Extract Embedding"): input_img = gr.Image(label="Upload Image") output_embed = gr.Textbox(label="Face Embedding") btn_extract = gr.Button("Extract") with gr.Tab("π― Extract Face Embedding"): gr.Markdown("Upload a single image to extract facial features.") with gr.Row(): with gr.Column(): input_img = gr.Image(label="Upload Image", type="numpy") btn_extract = gr.Button("π Extract Embedding", variant="primary") with gr.Column(): output_embed = gr.Textbox(label="Result", lines=5) btn_extract.click(fn=extract_face, inputs=input_img, outputs=output_embed) with gr.Tab("Match Faces"): target_img = gr.Image(label="Target Image") candidate_imgs = [gr.Image(label=f"Candidate Image {i+1}") for i in range(5)] output_matches = gr.Textbox(label="Matches") btn_match = gr.Button("Match") btn_match.click(fn=match_faces_fn, inputs=[target_img] + candidate_imgs, outputs=output_matches)
demo.launch() with gr.Tab("π Match Faces"): gr.Markdown("Upload a target face and up to 5 candidate images to find matches.") with gr.Row(): with gr.Column(scale=1): target_img = gr.Image(label="π― Target Image", type="numpy") threshold_slider = gr.Slider( minimum=0.3, maximum=0.9, value=0.6, step=0.05, label="Match Threshold", info="Higher = stricter matching" ) btn_match = gr.Button("π Find Matches", variant="primary") with gr.Column(scale=1): output_matches = gr.Textbox(label="Match Results", lines=12) with gr.Row(): candidate_imgs = [ gr.Image(label=f"Candidate {i+1}", type="numpy") for i in range(5) ] btn_match.click( fn=match_faces_fn, inputs=[target_img, threshold_slider] + candidate_imgs, outputs=output_matches ) gr.Markdown(""" --- **Note:** This app runs on CPU. Processing may take a few seconds per image. """)
if __name__ == "__main__": demo.launch()app.py+129-47