File size: 5,291 Bytes
1cb32b9
c9ee150
1cb32b9
 
 
 
 
 
 
 
 
c9ee150
 
1cb32b9
c9ee150
47db9f1
1cb32b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9ee150
 
 
1cb32b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9ee150
 
 
1cb32b9
 
 
 
 
 
c9ee150
 
 
1cb32b9
c9ee150
1cb32b9
c9ee150
1cb32b9
 
 
c9ee150
1cb32b9
c9ee150
1cb32b9
c9ee150
 
1cb32b9
 
 
 
 
 
 
c9ee150
1cb32b9
c9ee150
1cb32b9
c9ee150
 
 
1cb32b9
 
 
 
 
 
 
c9ee150
1cb32b9
 
 
c9ee150
 
 
 
 
1cb32b9
 
 
 
 
c9ee150
 
 
 
 
 
 
 
 
 
 
 
 
1cb32b9
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""
Robust Hugging Face Space App for Face Recognition
"""

import gradio as gr
import numpy as np
import cv2
from PIL import Image
import warnings
import os

# Suppress all warnings
warnings.filterwarnings('ignore')

# Import the robust face recognition functions
from face_recognition import get_similarity, get_face_class

def predict_similarity(file1, file2):
    """Predict similarity between two face images"""
    try:
        if file1 is None or file2 is None:
            return "Please upload both images"
        
        # Load images
        img1 = cv2.imread(file1)
        img2 = cv2.imread(file2)
        
        if img1 is None or img2 is None:
            return "Error loading images. Please ensure they are valid image files."
        
        # Get similarity score
        similarity_score = get_similarity(img1, img2)
        
        if similarity_score == -1.0:
            return "Error processing images. Please try again."
        
        # Interpret the result
        if similarity_score > 0.8:
            result = f"Very High Similarity ({similarity_score:.4f}) - Likely same person"
        elif similarity_score > 0.6:
            result = f"High Similarity ({similarity_score:.4f}) - Possibly same person"
        elif similarity_score > 0.4:
            result = f"Moderate Similarity ({similarity_score:.4f}) - Uncertain"
        elif similarity_score > 0.2:
            result = f"Low Similarity ({similarity_score:.4f}) - Likely different persons"
        else:
            result = f"Very Low Similarity ({similarity_score:.4f}) - Definitely different persons"
        
        return result
        
    except Exception as e:
        return f"Error: {str(e)}"

def predict_class(file):
    """Predict the class of a face image"""
    try:
        if file is None:
            return "Please upload an image"
        
        # Load image
        img = cv2.imread(file)
        
        if img is None:
            return "Error loading image. Please ensure it's a valid image file."
        
        # Get face class
        face_class = get_face_class(img)
        
        if face_class.startswith("Error:"):
            return face_class
        
        return f"Predicted Face Class: {face_class}"
        
    except Exception as e:
        return f"Error: {str(e)}"

# Create Gradio interface
with gr.Blocks(title="Face Recognition System", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# πŸ‘€ Face Recognition System")
    gr.Markdown("Upload face images to compare similarity or classify faces using advanced AI.")
    
    with gr.Tab("πŸ” Face Similarity"):
        gr.Markdown("## Compare Two Faces")
        gr.Markdown("Upload two face images to compare their similarity using cosine similarity.")
        
        with gr.Row():
            with gr.Column():
                img1 = gr.Image(type="filepath", label="First Face Image", height=200)
            with gr.Column():
                img2 = gr.Image(type="filepath", label="Second Face Image", height=200)
        
        similarity_btn = gr.Button("πŸ” Compare Faces", variant="primary", size="lg")
        similarity_output = gr.Textbox(label="Similarity Result", interactive=False, lines=3)
        
        similarity_btn.click(
            fn=predict_similarity,
            inputs=[img1, img2],
            outputs=similarity_output
        )
    
    with gr.Tab("🏷️ Face Classification"):
        gr.Markdown("## Classify a Face")
        gr.Markdown("Upload a face image to classify it into predefined categories.")
        
        img_class = gr.Image(type="filepath", label="Face Image", height=300)
        class_btn = gr.Button("🏷️ Classify Face", variant="primary", size="lg")
        class_output = gr.Textbox(label="Classification Result", interactive=False, lines=2)
        
        class_btn.click(
            fn=predict_class,
            inputs=[img_class],
            outputs=class_output
        )
    
    with gr.Tab("ℹ️ About"):
        gr.Markdown("""
        ## About This Face Recognition System
        
        This advanced face recognition system uses:
        - **🧠 Siamese Neural Network** for robust face feature extraction
        - **πŸ“ Cosine Similarity** for accurate face comparison
        - **🎯 K-Nearest Neighbors** for face classification
        - **πŸ›‘οΈ Robust Error Handling** for reliable operation
        
        ### How to Use:
        1. **Face Similarity**: Upload two face images to compare their similarity
        2. **Face Classification**: Upload a single face image to classify it
        
        ### Similarity Score Interpretation:
        - **0.8-1.0**: Very High Similarity (likely same person) 🟒
        - **0.6-0.8**: High Similarity (possibly same person) 🟑
        - **0.4-0.6**: Moderate Similarity (uncertain) 🟠
        - **0.2-0.4**: Low Similarity (likely different persons) πŸ”΄
        - **0.0-0.2**: Very Low Similarity (definitely different persons) ⚫
        
        ### Technical Features:
        - Handles various image formats
        - Automatic face detection and cropping
        - Robust error handling
        - Cross-platform compatibility
        - Optimized for production use
        """)

if __name__ == "__main__":
    demo.launch()