Update app.py
Browse files12345672 unmodified lines10111213141516171819202122232425262728293031323334353637383940414243444546474849502 unmodified lines5354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123#!/usr/bin/env python3"""Facial Recognition Service with Gradio UICPU-only version for Hugging Face Spaces using PyTorch backend"""import warnings2 unmodified linesimport numpy as npimport cv2import gradio as gr# Suppress warningswarnings.filterwarnings('ignore')os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'# InsightFace PyTorch backendfrom insightface.app import FaceAnalysisclass FacialRecognitionService:def __init__(self):"""Initialize InsightFace model on CPU using PyTorch backend"""print("Loading InsightFace model (PyTorch, CPU)...")# Lightweight CPU-friendly modelself.app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])self.app.prepare(ctx_id=-1, det_size=(640, 640)) # CPU-onlyprint("Model loaded β ")def extract_face_embedding(self, image: np.ndarray):"""Extract face embedding from an uploaded image (numpy array)"""try:if image is None:return Noneif image.shape[2] == 3:img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)else:img_rgb = imagefaces = self.app.get(img_rgb)if len(faces) == 0:return Nonelargest_face = max(faces, key=lambda x: (x.bbox[2]-x.bbox[0])*(x.bbox[3]-x.bbox[1]))return largest_face.embeddingexcept Exception as e:print(f"Error extracting embedding: {e}", file=sys.stderr)2 unmodified linesdef 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.0emb1, emb2 = emb1 / norm1, emb2 / norm2return float((np.dot(emb1, emb2) + 1) / 2)except:return 0.0def match_faces(self, target_image: np.ndarray, candidate_images: list, threshold: float = 0.6):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:continuesimilarity = 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 "\n".join([f"Candidate {m['index']}: {m['score']}%" for m in matches])# Initialize serviceservice = FacialRecognitionService()# Gradio functionsdef extract_face(image):embedding = service.extract_face_embedding(image)if embedding is None:return "No face detected"return f"Embedding size: {len(embedding)}"def match_faces_fn(target_image, *candidate_images):candidates = [img for img in candidate_images if img is not None]result = service.match_faces(target_image, candidates)return result# Gradio UIwith gr.Blocks() as demo:gr.Markdown("## Facial Recognition Service (InsightFace, CPU Only)")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_fn, inputs=[target_img] + candidate_imgs, outputs=output_matches)demo.launch()12345672 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657582 unmodified lines616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205#!/usr/bin/env python3"""Facial Recognition Service with Gradio UIUsing 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'class FacialRecognitionService:def __init__(self):"""Initialize DeepFace with VGG-Face model"""print("Loading DeepFace model...")# Pre-load modeltry: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"""try:if image is None:return None# DeepFace expects RGBif len(image.shape) == 2: # Grayscaleimg_rgb = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)elif image.shape[2] == 4: # RGBAimg_rgb = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)else:img_rgb = image# Extract embeddingembedding_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 Noneexcept Exception as e:print(f"Error extracting embedding: {e}", file=sys.stderr)2 unmodified linesdef calculate_similarity(self, emb1, emb2):"""Cosine similarity normalized to 0-1"""try:from sklearn.metrics.pairwise import cosine_similaritysimilarity = cosine_similarity([emb1], [emb2])[0][0]# Convert from [-1, 1] to [0, 1]return float((similarity + 1) / 2)except:# Fallback manual calculationtry:norm1, norm2 = np.linalg.norm(emb1), np.linalg.norm(emb2)if norm1 == 0 or norm2 == 0:return 0.0emb1_norm, emb2_norm = emb1 / norm1, emb2 / norm2return float((np.dot(emb1_norm, emb2_norm) + 1) / 2)except:return 0.0def 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"for idx, candidate in enumerate(candidate_images):if candidate is None:continuecandidate_emb = self.extract_face_embedding(candidate)if candidate_emb is None:continuesimilarity = self.calculate_similarity(target_emb, candidate_emb)if similarity >= threshold:matches.append({'index': idx + 1,'confidence': similarity,'score': int(similarity * 100)})if not matches:return "β No matches found above threshold"# Sort by confidencematches.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 in image"return f"β Face detected!\n\nEmbedding size: {len(embedding)} dimensions\nModel: VGG-Face"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, threshold=threshold)return result# Gradio UIwith 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 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"):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