Update app.py
Browse files12345672 unmodified lines101112131415162 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788891 unmodified line91929394959697982 unmodified lines10110210310410510610710810911011111211311411 unmodified lines12612712812913013113213313411 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911922 unmodified lines195196197198199200201202203204#!/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')2 unmodified linesclass 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)return Nonedef 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:continue1 unmodified linecandidate_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,2 unmodified lines})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 result11 unmodified linesembedding = 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):11 unmodified lines# 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)]2 unmodified linesinputs=[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__":12345672 unmodified lines101112131415162 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091 unmodified line1111121131141151161171181191201211221231241251262 unmodified lines12913013113213313413513613713813914014114214314411 unmodified lines15615715815916016116216316411 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422 unmodified lines245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301#!/usr/bin/env python3"""Facial Recognition Service with Gradio UIUsing face_recognition library for maximum Hugging Face Spaces compatibility"""import warnings2 unmodified linesimport numpy as npimport cv2import gradio as grimport face_recognition# Suppress warningswarnings.filterwarnings('ignore')2 unmodified linesclass FacialRecognitionService:def __init__(self):"""Initialize face recognition service"""print("Face Recognition Service ready β ")self.model = "large" # 'large' (more accurate) or 'small' (faster)def extract_face_embedding(self, image: np.ndarray):"""Extract 128-dimensional face embedding from an image"""try:if image is None:return None# Convert to RGB if needed (face_recognition requires RGB)if 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)elif image.shape[2] == 3: # BGR (from OpenCV)img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)else:img_rgb = image# Detect face locationsface_locations = face_recognition.face_locations(img_rgb, model=self.model)if len(face_locations) == 0:return None# Get face encodings (embeddings)face_encodings = face_recognition.face_encodings(img_rgb, face_locations, model=self.model)if len(face_encodings) == 0:return None# Return the first (or largest) face encodingif len(face_locations) > 1:# Find largest faceareas = [(loc[2] - loc[0]) * (loc[1] - loc[3]) for loc in face_locations]largest_idx = np.argmax(areas)return face_encodings[largest_idx]return face_encodings[0]except Exception as e:print(f"Error extracting embedding: {e}", file=sys.stderr)return Nonedef calculate_similarity(self, emb1, emb2):"""Calculate cosine similarity normalized to 0-1 range"""try:# Normalize embeddingsnorm1 = np.linalg.norm(emb1)norm2 = np.linalg.norm(emb2)if norm1 == 0 or norm2 == 0:return 0.0emb1_norm = emb1 / norm1emb2_norm = emb2 / norm2# Cosine similaritysimilarity = np.dot(emb1_norm, emb2_norm)# Convert from [-1, 1] to [0, 1]return float((similarity + 1) / 2)except Exception as e:print(f"Error calculating similarity: {e}", file=sys.stderr)return 0.0def calculate_face_distance(self, emb1, emb2):"""Calculate Euclidean distance (lower is more similar)"""try:distance = np.linalg.norm(emb1 - emb2)return float(distance)except:return float('inf')def match_faces(self, target_image: np.ndarray, candidate_images: list, threshold: float = 0.6, use_distance: bool = False):"""Match target face against candidate images"""matches = []# Extract target embeddingtarget_emb = self.extract_face_embedding(target_image)if target_emb is None:return "β No face detected in target image"# Compare with each candidatefor idx, candidate in enumerate(candidate_images):if candidate is None:continue1 unmodified linecandidate_emb = self.extract_face_embedding(candidate)if candidate_emb is None:continueif use_distance:# Use face_recognition's built-in distance metricdistance = self.calculate_face_distance(target_emb, candidate_emb)# Convert distance to similarity score (0.6 distance = ~60% match)similarity = max(0, 1 - (distance / 1.2)) # Normalize to 0-1else:# Use cosine similaritysimilarity = self.calculate_similarity(target_emb, candidate_emb)if similarity >= threshold:matches.append({'index': idx + 1,2 unmodified lines})if not matches:return f"β No matches found above {int(threshold * 100)}% threshold"# Sort by confidence (highest first)matches.sort(key=lambda x: x['confidence'], reverse=True)result = "β **Matches Found:**\n\n"for m in matches:confidence_bar = "β" * int(m['score'] / 10) + "β" * (10 - int(m['score'] / 10))result += f"πΈ **Candidate {m['index']}:** {m['score']}%\n"result += f" {confidence_bar}\n\n"return result11 unmodified linesembedding = service.extract_face_embedding(image)if embedding is None:return "β No face detected in image\n\nTips:\n- Ensure face is clearly visible\n- Face should be well-lit\n- Try a different angle"return f"β **Face detected successfully!**\n\nπ Embedding Details:\n- Dimensions: {len(embedding)}\n- Model: dlib (HOG + CNN)\n- Encoding: 128-D vector\n\nThis embedding can be used for facial recognition and comparison."def match_faces_fn(target_image, threshold, *candidate_images):11 unmodified lines# Gradio UIwith gr.Blocks(theme=gr.themes.Soft(), title="Facial Recognition Service") as demo:gr.Markdown("""# π Facial Recognition Service### Powered by dlib's state-of-the-art face recognitionUpload images to extract face embeddings or match faces across multiple images.- 128-dimensional face encodings- High accuracy facial recognition- CPU-optimized for Hugging Face Spaces""")with gr.Tab("π― Extract Face Embedding"):gr.Markdown("""Upload a single image to extract facial features. The system will:- Detect the face in the image- Extract a 128-dimensional embedding vector- Return the embedding information""")with gr.Row():with gr.Column():input_img = gr.Image(label="Upload Image", type="numpy", height=400)btn_extract = gr.Button("π Extract Embedding", variant="primary", size="lg")with gr.Column():output_embed = gr.Textbox(label="Result", lines=10, max_lines=15)btn_extract.click(fn=extract_face, inputs=input_img, outputs=output_embed)gr.Markdown("""**Tips for best results:**- Use clear, well-lit photos- Face should be visible and not obstructed- Front-facing photos work best""")with gr.Tab("π Match Faces"):gr.Markdown("""Upload a target face and up to 5 candidate images to find matches.The system compares facial features and returns similarity scores.""")with gr.Row():with gr.Column(scale=1):target_img = gr.Image(label="π― Target Image", type="numpy", height=300)threshold_slider = gr.Slider(minimum=0.3,maximum=0.95,value=0.6,step=0.05,label="Match Threshold",info="Higher = stricter matching (0.6 recommended)")btn_match = gr.Button("π Find Matches", variant="primary", size="lg")with gr.Column(scale=1):output_matches = gr.Textbox(label="Match Results", lines=15, max_lines=20)gr.Markdown("### πΈ Candidate Images")with gr.Row():candidate_imgs = [gr.Image(label=f"Candidate {i+1}", type="numpy", height=200)for i in range(5)]2 unmodified linesinputs=[target_img, threshold_slider] + candidate_imgs,outputs=output_matches)gr.Markdown("""**Similarity Scoring:**- 90-100%: Very high confidence match- 70-89%: High confidence match- 60-69%: Good match- Below 60%: Low confidence""")with gr.Tab("βΉοΈ About"):gr.Markdown("""## About This ServiceThis facial recognition system uses **dlib's face recognition model**, which provides:- **High Accuracy**: 99.38% accuracy on the Labeled Faces in the Wild benchmark- **128-D Embeddings**: Compact representation of facial features- **Robust Detection**: Works with various lighting conditions and angles- **Privacy-Focused**: All processing happens in your browser session### How It Works1. **Face Detection**: Locates faces in uploaded images2. **Feature Extraction**: Generates 128-dimensional embedding vectors3. **Similarity Comparison**: Compares embeddings using cosine similarity4. **Threshold Filtering**: Returns matches above the confidence threshold### Use Cases- Identity verification- Duplicate photo detection- Face clustering in photo libraries- Security and access control systems### Technical Details- **Model**: dlib ResNet-based face recognition- **Detection**: HOG + CNN face detector- **Embedding Size**: 128 dimensions- **Computing**: CPU-optimized (no GPU required)---**Note:** This app runs entirely on CPU. Processing time: ~1-3 seconds per image.""")gr.Markdown("""---<div style="text-align: center; color: #666; font-size: 0.9em;">π Privacy: All processing happens on the server. Images are not stored.</div>""")if __name__ == "__main__":
app.py+154-57