Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119#!/usr/bin/env python3"""Facial Recognition Service with Gradio UIRuns on Hugging Face Spaces"""
import warningsimport osimport sysimport numpy as npimport cv2import insightfacefrom insightface.app import FaceAnalysisimport gradio as gr
# Suppress warnings and verbose logswarnings.filterwarnings('ignore')os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'os.environ['ONNXRUNTIME_LOG_SEVERITY_LEVEL'] = '4'
class FacialRecognitionService: def __init__(self): """Initialize InsightFace model""" self.app = FaceAnalysis(providers=['CPUExecutionProvider']) self.app.prepare(ctx_id=0, det_size=(640, 640))
def extract_face_embedding(self, image: np.ndarray): """Extract face embedding from an uploaded image (numpy array)""" try: # Convert BGR to RGB if needed if image.shape[2] == 3: img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) else: img_rgb = image
faces = self.app.get(img_rgb) if len(faces) == 0: return None
# Return embedding of the largest face largest_face = max(faces, key=lambda x: (x.bbox[2]-x.bbox[0])*(x.bbox[3]-x.bbox[1])) return largest_face.embedding
except Exception as e: print(f"Error extracting embedding: {e}", file=sys.stderr) return None
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) except: return 0.0
def match_faces(self, target_image: np.ndarray, candidate_images: list, threshold: float = 0.6): """Compare target image to candidate images and return matches""" matches = [] target_emb = self.extract_face_embedding(target_image) if target_emb is None: return "No face detected in target image"
for idx, candidate in enumerate(candidate_images): 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, 'confidence': similarity, 'score': int(similarity * 100) })
if not matches: return "No matches found" return matches
# Initialize serviceservice = FacialRecognitionService()
# Gradio functionsdef extract_face(image): embedding = service.extract_face_embedding(image) if embedding is None: return "No face detected" return embedding.tolist()
def match_faces(target_image, *candidate_images): candidates = [img for img in candidate_images if img is not None] result = service.match_faces(target_image, candidates) return str(result)
# Gradio UIwith gr.Blocks() as demo: gr.Markdown("## Facial Recognition Service (InsightFace)") with gr.Tab("Extract Embedding"): input_img = gr.Image(label="Upload Image") output_embed = gr.Textbox(label="Face Embedding") btn_extract = gr.Button("Extract") 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, inputs=[target_img] + candidate_imgs, outputs=output_matches)
demo.launch()app.pyAdded+119