Update app.py
Browse files
app.py
CHANGED
|
@@ -1,580 +1,42 @@
|
|
| 1 |
-
|
| 2 |
-
from
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
from
|
| 6 |
-
import base64
|
| 7 |
-
from io import BytesIO
|
| 8 |
|
| 9 |
-
|
| 10 |
-
"""Convert numpy array to base64 string for HTML display"""
|
| 11 |
-
if img_array is None:
|
| 12 |
-
return None
|
| 13 |
-
img = Image.fromarray(img_array.astype('uint8'))
|
| 14 |
-
buffered = BytesIO()
|
| 15 |
-
img.save(buffered, format="PNG")
|
| 16 |
-
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 17 |
-
return f"data:image/png;base64,{img_str}"
|
| 18 |
|
| 19 |
-
def
|
| 20 |
-
|
| 21 |
-
try:
|
| 22 |
-
# Use DeepFace.extract_faces to detect and align
|
| 23 |
-
face_objs = DeepFace.extract_faces(
|
| 24 |
-
img_path=img,
|
| 25 |
-
detector_backend=detector_backend,
|
| 26 |
-
align=True,
|
| 27 |
-
enforce_detection=True
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
if len(face_objs) == 0:
|
| 31 |
-
return None, None, None
|
| 32 |
-
|
| 33 |
-
# Get the first face
|
| 34 |
-
face_obj = face_objs[0]
|
| 35 |
-
detected_face = face_obj['face'] # Aligned face array
|
| 36 |
-
facial_area = face_obj['facial_area'] # Face coordinates
|
| 37 |
-
confidence = face_obj['confidence']
|
| 38 |
-
|
| 39 |
-
# Convert detected face back to uint8 for visualization
|
| 40 |
-
if detected_face.max() <= 1.0:
|
| 41 |
-
detected_face = (detected_face * 255).astype('uint8')
|
| 42 |
-
|
| 43 |
-
# Draw rectangle on original image
|
| 44 |
-
img_with_box = img.copy()
|
| 45 |
-
x, y, w, h = facial_area['x'], facial_area['y'], facial_area['w'], facial_area['h']
|
| 46 |
-
cv2.rectangle(img_with_box, (x, y), (x+w, y+h), (0, 255, 0), 3)
|
| 47 |
-
|
| 48 |
-
# Add label
|
| 49 |
-
label = f"Face Detected ({confidence:.1%})"
|
| 50 |
-
cv2.putText(img_with_box, label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
|
| 51 |
-
|
| 52 |
-
return detected_face, img_with_box, facial_area
|
| 53 |
-
except Exception as e:
|
| 54 |
-
return None, None, str(e)
|
| 55 |
|
| 56 |
-
def
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
face_img = (face_img * 255).astype('uint8')
|
| 62 |
-
|
| 63 |
-
# Resize
|
| 64 |
-
resized = cv2.resize(face_img, target_size)
|
| 65 |
-
|
| 66 |
-
# Normalize to [0, 1]
|
| 67 |
-
normalized = resized.astype('float32') / 255.0
|
| 68 |
-
|
| 69 |
-
# Convert to visualization (scale back for display)
|
| 70 |
-
normalized_vis = (normalized * 255).astype('uint8')
|
| 71 |
-
|
| 72 |
-
return normalized, normalized_vis
|
| 73 |
-
except Exception as e:
|
| 74 |
-
return None, None
|
| 75 |
|
| 76 |
-
|
| 77 |
-
"""Create a visual representation of the embedding vector"""
|
| 78 |
-
try:
|
| 79 |
-
# Reshape embedding for visualization
|
| 80 |
-
emb_len = len(embedding)
|
| 81 |
-
|
| 82 |
-
# Create a grid visualization
|
| 83 |
-
grid_size = int(np.ceil(np.sqrt(emb_len)))
|
| 84 |
-
grid = np.zeros((grid_size, grid_size))
|
| 85 |
-
|
| 86 |
-
# Normalize embedding to [0, 1]
|
| 87 |
-
emb_normalized = (embedding - embedding.min()) / (embedding.max() - embedding.min() + 1e-10)
|
| 88 |
-
|
| 89 |
-
# Fill grid
|
| 90 |
-
for i in range(min(emb_len, grid_size * grid_size)):
|
| 91 |
-
row = i // grid_size
|
| 92 |
-
col = i % grid_size
|
| 93 |
-
grid[row, col] = emb_normalized[i]
|
| 94 |
-
|
| 95 |
-
# Scale to image size
|
| 96 |
-
grid_img = cv2.resize(grid, img_shape, interpolation=cv2.INTER_NEAREST)
|
| 97 |
-
|
| 98 |
-
# Apply colormap
|
| 99 |
-
grid_colored = cv2.applyColorMap((grid_img * 255).astype('uint8'), cv2.COLORMAP_JET)
|
| 100 |
-
grid_colored = cv2.cvtColor(grid_colored, cv2.COLOR_BGR2RGB)
|
| 101 |
-
|
| 102 |
-
return grid_colored
|
| 103 |
-
except Exception as e:
|
| 104 |
-
return None
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
Verify faces with complete step-by-step visualization
|
| 109 |
-
"""
|
| 110 |
-
try:
|
| 111 |
-
# Check if images are provided
|
| 112 |
-
if nid_image is None or webcam_image is None:
|
| 113 |
-
return (
|
| 114 |
-
"❌ Error: Please upload both images",
|
| 115 |
-
None, None, None, None, None, None, None, None, None
|
| 116 |
-
)
|
| 117 |
-
|
| 118 |
-
# Initialize outputs
|
| 119 |
-
step_status = "<h3>🔄 Processing...</h3>"
|
| 120 |
-
|
| 121 |
-
# STEP 1: Face Detection - NID Image
|
| 122 |
-
step_status += "<div style='padding: 10px; background-color: #fff3cd; border-radius: 5px; margin: 10px 0;'>"
|
| 123 |
-
step_status += "<b>Step 1: Face Detection (NID Image)</b><br>"
|
| 124 |
-
step_status += "Detecting face in NID card image using face detector...<br>"
|
| 125 |
-
|
| 126 |
-
nid_face, nid_detected_img, nid_area = detect_and_align_face(nid_image, detector_backend='opencv')
|
| 127 |
-
|
| 128 |
-
if nid_face is None:
|
| 129 |
-
return (
|
| 130 |
-
"❌ Error: No face detected in NID image. Please ensure the image contains a clear, visible face.",
|
| 131 |
-
None, None, None, None, None, None, None, None, None
|
| 132 |
-
)
|
| 133 |
-
|
| 134 |
-
step_status += f"✅ Face detected at position: x={nid_area['x']}, y={nid_area['y']}, width={nid_area['w']}, height={nid_area['h']}</div>"
|
| 135 |
-
|
| 136 |
-
# STEP 2: Face Detection - Webcam Image
|
| 137 |
-
step_status += "<div style='padding: 10px; background-color: #fff3cd; border-radius: 5px; margin: 10px 0;'>"
|
| 138 |
-
step_status += "<b>Step 2: Face Detection (Webcam Image)</b><br>"
|
| 139 |
-
step_status += "Detecting face in webcam image...<br>"
|
| 140 |
-
|
| 141 |
-
webcam_face, webcam_detected_img, webcam_area = detect_and_align_face(webcam_image, detector_backend='opencv')
|
| 142 |
-
|
| 143 |
-
if webcam_face is None:
|
| 144 |
-
return (
|
| 145 |
-
"❌ Error: No face detected in webcam image. Please ensure the image contains a clear, visible face.",
|
| 146 |
-
nid_detected_img, None, None, None, None, None, None, None, None
|
| 147 |
-
)
|
| 148 |
-
|
| 149 |
-
step_status += f"✅ Face detected at position: x={webcam_area['x']}, y={webcam_area['y']}, width={webcam_area['w']}, height={webcam_area['h']}</div>"
|
| 150 |
-
|
| 151 |
-
# STEP 3: Face Alignment
|
| 152 |
-
step_status += "<div style='padding: 10px; background-color: #d1ecf1; border-radius: 5px; margin: 10px 0;'>"
|
| 153 |
-
step_status += "<b>Step 3: Face Alignment</b><br>"
|
| 154 |
-
step_status += "Aligning faces to standard position using facial landmarks (eyes, nose, mouth)...<br>"
|
| 155 |
-
step_status += "✅ Both faces aligned and cropped to focus on facial region</div>"
|
| 156 |
-
|
| 157 |
-
aligned_nid = nid_face
|
| 158 |
-
aligned_webcam = webcam_face
|
| 159 |
-
|
| 160 |
-
# STEP 4: Preprocessing
|
| 161 |
-
step_status += "<div style='padding: 10px; background-color: #f8d7da; border-radius: 5px; margin: 10px 0;'>"
|
| 162 |
-
step_status += "<b>Step 4: Preprocessing</b><br>"
|
| 163 |
-
step_status += f"Resizing images to {model_name} input size<br>"
|
| 164 |
-
step_status += "Normalizing pixel values to range [0, 1]<br>"
|
| 165 |
-
|
| 166 |
-
# Get target size based on model
|
| 167 |
-
target_sizes = {
|
| 168 |
-
"VGG-Face": (224, 224),
|
| 169 |
-
"Facenet": (160, 160),
|
| 170 |
-
"OpenFace": (96, 96),
|
| 171 |
-
"ArcFace": (112, 112)
|
| 172 |
-
}
|
| 173 |
-
target_size = target_sizes.get(model_name, (224, 224))
|
| 174 |
-
|
| 175 |
-
nid_preprocessed, nid_preprocessed_vis = preprocess_face(aligned_nid, target_size)
|
| 176 |
-
webcam_preprocessed, webcam_preprocessed_vis = preprocess_face(aligned_webcam, target_size)
|
| 177 |
-
|
| 178 |
-
step_status += f"✅ Images resized to {target_size[0]}x{target_size[1]} and normalized</div>"
|
| 179 |
-
|
| 180 |
-
# STEP 5: Neural Network Processing
|
| 181 |
-
step_status += "<div style='padding: 10px; background-color: #e7d4f5; border-radius: 5px; margin: 10px 0;'>"
|
| 182 |
-
step_status += "<b>Step 5: Neural Network Processing</b><br>"
|
| 183 |
-
step_status += f"Passing images through {model_name} deep neural network...<br>"
|
| 184 |
-
step_status += f"Model: {model_name} (Convolutional Neural Network with multiple layers)<br>"
|
| 185 |
-
|
| 186 |
-
# Get embeddings separately for visualization (Step 6)
|
| 187 |
-
step_status += "✅ Processing images...</div>"
|
| 188 |
-
|
| 189 |
-
step_status += "<div style='padding: 10px; background-color: #e0e0e0; border-radius: 5px; margin: 10px 0;'>"
|
| 190 |
-
step_status += "<b>Step 6: Generate Embeddings (Feature Vectors)</b><br>"
|
| 191 |
-
step_status += "Converting face images into numerical vectors that represent unique facial features...<br>"
|
| 192 |
-
|
| 193 |
-
try:
|
| 194 |
-
nid_embedding_result = DeepFace.represent(
|
| 195 |
-
img_path=nid_image,
|
| 196 |
-
model_name=model_name,
|
| 197 |
-
enforce_detection=True,
|
| 198 |
-
detector_backend='opencv'
|
| 199 |
-
)
|
| 200 |
-
webcam_embedding_result = DeepFace.represent(
|
| 201 |
-
img_path=webcam_image,
|
| 202 |
-
model_name=model_name,
|
| 203 |
-
enforce_detection=True,
|
| 204 |
-
detector_backend='opencv'
|
| 205 |
-
)
|
| 206 |
-
|
| 207 |
-
nid_embedding = nid_embedding_result[0]["embedding"]
|
| 208 |
-
webcam_embedding = webcam_embedding_result[0]["embedding"]
|
| 209 |
-
|
| 210 |
-
embedding_dim = len(nid_embedding)
|
| 211 |
-
step_status += f"✅ Generated {embedding_dim}-dimensional embeddings for both faces<br>"
|
| 212 |
-
step_status += f"NID Embedding sample: [{nid_embedding[0]:.4f}, {nid_embedding[1]:.4f}, ..., {nid_embedding[-1]:.4f}]<br>"
|
| 213 |
-
step_status += f"Webcam Embedding sample: [{webcam_embedding[0]:.4f}, {webcam_embedding[1]:.4f}, ..., {webcam_embedding[-1]:.4f}]</div>"
|
| 214 |
-
|
| 215 |
-
# Create embedding visualizations
|
| 216 |
-
nid_emb_vis = create_embedding_visualization(np.array(nid_embedding))
|
| 217 |
-
webcam_emb_vis = create_embedding_visualization(np.array(webcam_embedding))
|
| 218 |
-
except Exception as e:
|
| 219 |
-
step_status += f"⚠️ Embedding visualization unavailable: {str(e)}</div>"
|
| 220 |
-
nid_emb_vis = None
|
| 221 |
-
webcam_emb_vis = None
|
| 222 |
-
embedding_dim = "N/A"
|
| 223 |
-
|
| 224 |
-
# Perform actual verification
|
| 225 |
-
result = DeepFace.verify(
|
| 226 |
-
img1_path=nid_image,
|
| 227 |
-
img2_path=webcam_image,
|
| 228 |
-
model_name=model_name,
|
| 229 |
-
enforce_detection=True,
|
| 230 |
-
detector_backend='opencv'
|
| 231 |
-
)
|
| 232 |
-
|
| 233 |
-
# STEP 7: Calculate Distance
|
| 234 |
-
distance = result["distance"]
|
| 235 |
-
threshold = result["threshold"]
|
| 236 |
-
metric = result["similarity_metric"]
|
| 237 |
-
|
| 238 |
-
step_status += "<div style='padding: 10px; background-color: #fff8dc; border-radius: 5px; margin: 10px 0;'>"
|
| 239 |
-
step_status += "<b>Step 7: Calculate Distance</b><br>"
|
| 240 |
-
step_status += f"Computing {metric} distance between the two embeddings...<br>"
|
| 241 |
-
step_status += f"Distance Metric: {metric}<br>"
|
| 242 |
-
step_status += f"<b>Calculated Distance: {distance:.6f}</b><br>"
|
| 243 |
-
step_status += "Lower distance = More similar faces</div>"
|
| 244 |
-
|
| 245 |
-
# STEP 8: Threshold Comparison
|
| 246 |
-
verified = result["verified"]
|
| 247 |
-
|
| 248 |
-
step_status += "<div style='padding: 10px; background-color: #d1ecf1; border-radius: 5px; margin: 10px 0;'>"
|
| 249 |
-
step_status += "<b>Step 8: Compare Distance to Threshold</b><br>"
|
| 250 |
-
step_status += f"Model Threshold: {threshold:.6f}<br>"
|
| 251 |
-
step_status += f"Calculated Distance: {distance:.6f}<br>"
|
| 252 |
-
step_status += f"<b>Is Distance < Threshold? {distance:.6f} < {threshold:.6f}?</b><br>"
|
| 253 |
-
|
| 254 |
-
if distance < threshold:
|
| 255 |
-
step_status += f"✅ YES! {distance:.6f} < {threshold:.6f} → Faces MATCH</div>"
|
| 256 |
-
else:
|
| 257 |
-
step_status += f"❌ NO! {distance:.6f} ≥ {threshold:.6f} → Faces DO NOT MATCH</div>"
|
| 258 |
-
|
| 259 |
-
# STEP 9: Final Result
|
| 260 |
-
if verified:
|
| 261 |
-
confidence = ((threshold - distance) / threshold) * 100
|
| 262 |
-
status = "✅ MATCH"
|
| 263 |
-
status_color = "green"
|
| 264 |
-
else:
|
| 265 |
-
confidence = ((distance - threshold) / distance) * 100 if distance > 0 else 0
|
| 266 |
-
status = "❌ NO MATCH"
|
| 267 |
-
status_color = "red"
|
| 268 |
-
|
| 269 |
-
step_status += f"<div style='padding: 15px; background-color: {'#d4edda' if verified else '#f8d7da'}; border-radius: 5px; margin: 10px 0; border: 3px solid {status_color};'>"
|
| 270 |
-
step_status += f"<h2 style='color: {status_color}; margin: 0;'><b>Step 9: Final Result - {status}</b></h2><br>"
|
| 271 |
-
step_status += f"<b>Confidence: {confidence:.2f}%</b><br>"
|
| 272 |
-
step_status += f"Model: {result['model']}<br>"
|
| 273 |
-
step_status += f"Detector: {result['detector_backend']}</div>"
|
| 274 |
-
|
| 275 |
-
# Create comprehensive summary
|
| 276 |
-
summary = f"""
|
| 277 |
-
<div style='padding: 20px; background-color: #f9f9f9; border-radius: 10px; border: 2px solid #ddd;'>
|
| 278 |
-
<h2 style='text-align: center; color: {status_color};'>{status}</h2>
|
| 279 |
-
<hr>
|
| 280 |
-
<h3>📊 Final Metrics:</h3>
|
| 281 |
-
<ul style='font-size: 16px; line-height: 1.8;'>
|
| 282 |
-
<li><b>Verification Result:</b> <span style='color: {status_color};'>{verified}</span></li>
|
| 283 |
-
<li><b>Confidence Score:</b> {confidence:.2f}%</li>
|
| 284 |
-
<li><b>Distance Score:</b> {distance:.6f}</li>
|
| 285 |
-
<li><b>Threshold:</b> {threshold:.6f}</li>
|
| 286 |
-
<li><b>Difference:</b> {abs(distance - threshold):.6f}</li>
|
| 287 |
-
<li><b>Model Used:</b> {result['model']}</li>
|
| 288 |
-
<li><b>Face Detector:</b> {result['detector_backend']}</li>
|
| 289 |
-
<li><b>Similarity Metric:</b> {metric}</li>
|
| 290 |
-
<li><b>Embedding Dimension:</b> {embedding_dim}D vector</li>
|
| 291 |
-
</ul>
|
| 292 |
-
<hr>
|
| 293 |
-
<div style='background-color: #fff3cd; padding: 10px; border-radius: 5px;'>
|
| 294 |
-
<b>💡 Understanding the Process:</b><br>
|
| 295 |
-
• The system extracted {embedding_dim} unique facial features from each image<br>
|
| 296 |
-
• These features were compared using {metric} distance metric<br>
|
| 297 |
-
• The distance of {distance:.6f} {'is below' if verified else 'exceeds'} the threshold of {threshold:.6f}<br>
|
| 298 |
-
• Therefore, the faces {'are identified as the same person' if verified else 'are identified as different people'}
|
| 299 |
-
</div>
|
| 300 |
-
</div>
|
| 301 |
-
"""
|
| 302 |
-
|
| 303 |
-
return (
|
| 304 |
-
summary,
|
| 305 |
-
nid_detected_img, # Step 1 output
|
| 306 |
-
webcam_detected_img, # Step 2 output
|
| 307 |
-
aligned_nid, # Step 3 output (NID)
|
| 308 |
-
aligned_webcam, # Step 3 output (Webcam)
|
| 309 |
-
nid_preprocessed_vis, # Step 4 output (NID)
|
| 310 |
-
webcam_preprocessed_vis, # Step 4 output (Webcam)
|
| 311 |
-
nid_emb_vis, # Step 6 output (NID embedding)
|
| 312 |
-
webcam_emb_vis, # Step 6 output (Webcam embedding)
|
| 313 |
-
step_status # All steps status
|
| 314 |
-
)
|
| 315 |
-
|
| 316 |
-
except Exception as e:
|
| 317 |
-
error_msg = f"""
|
| 318 |
-
<div style='padding: 20px; background-color: #f8d7da; border-radius: 10px; border: 2px solid #dc3545;'>
|
| 319 |
-
<h3 style='color: #dc3545;'>❌ Error Occurred</h3>
|
| 320 |
-
<p><b>Error:</b> {str(e)}</p>
|
| 321 |
-
<p>Please ensure both images contain clear, visible faces and try again.</p>
|
| 322 |
-
</div>
|
| 323 |
-
"""
|
| 324 |
-
return (error_msg, None, None, None, None, None, None, None, None, None)
|
| 325 |
|
|
|
|
|
|
|
|
|
|
| 326 |
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
"""
|
| 338 |
-
)
|
| 339 |
-
|
| 340 |
-
with gr.Row():
|
| 341 |
-
with gr.Column():
|
| 342 |
-
nid_input = gr.Image(
|
| 343 |
-
label="📇 NID Card Image",
|
| 344 |
-
type="numpy",
|
| 345 |
-
sources=["upload", "webcam"],
|
| 346 |
-
height=300
|
| 347 |
-
)
|
| 348 |
-
|
| 349 |
-
with gr.Column():
|
| 350 |
-
webcam_input = gr.Image(
|
| 351 |
-
label="📷 Webcam/Live Image",
|
| 352 |
-
type="numpy",
|
| 353 |
-
sources=["upload", "webcam"],
|
| 354 |
-
height=300
|
| 355 |
-
)
|
| 356 |
-
|
| 357 |
-
with gr.Row():
|
| 358 |
-
model_dropdown = gr.Dropdown(
|
| 359 |
-
choices=["ArcFace", "VGG-Face", "OpenFace", "Facenet"],
|
| 360 |
-
value="ArcFace",
|
| 361 |
-
label="🤖 Select Verification Model",
|
| 362 |
-
info="ArcFace recommended for best accuracy"
|
| 363 |
-
)
|
| 364 |
-
|
| 365 |
-
verify_button = gr.Button("🔍 Verify Faces & Show Process", variant="primary", size="lg")
|
| 366 |
-
|
| 367 |
-
gr.Markdown("---")
|
| 368 |
-
gr.Markdown("## 📊 Verification Result")
|
| 369 |
-
|
| 370 |
-
result_output = gr.HTML(label="Final Result Summary")
|
| 371 |
-
|
| 372 |
-
gr.Markdown("---")
|
| 373 |
-
gr.Markdown("## 🔍 Step-by-Step Process Visualization")
|
| 374 |
-
|
| 375 |
-
process_output = gr.HTML(label="Detailed Process Steps")
|
| 376 |
-
|
| 377 |
-
gr.Markdown("### Step 1-2: Face Detection")
|
| 378 |
-
gr.Markdown("*Detecting and locating faces in both images*")
|
| 379 |
-
|
| 380 |
-
with gr.Row():
|
| 381 |
-
step1_output = gr.Image(label="Step 1: Face Detected in NID Image", type="numpy")
|
| 382 |
-
step2_output = gr.Image(label="Step 2: Face Detected in Webcam Image", type="numpy")
|
| 383 |
-
|
| 384 |
-
gr.Markdown("### Step 3: Face Alignment")
|
| 385 |
-
gr.Markdown("*Cropped and aligned face regions*")
|
| 386 |
-
|
| 387 |
-
with gr.Row():
|
| 388 |
-
step3a_output = gr.Image(label="Step 3: Aligned NID Face", type="numpy")
|
| 389 |
-
step3b_output = gr.Image(label="Step 3: Aligned Webcam Face", type="numpy")
|
| 390 |
-
|
| 391 |
-
gr.Markdown("### Step 4: Preprocessing")
|
| 392 |
-
gr.Markdown("*Resized and normalized images ready for neural network*")
|
| 393 |
-
|
| 394 |
-
with gr.Row():
|
| 395 |
-
step4a_output = gr.Image(label="Step 4: Preprocessed NID Face", type="numpy")
|
| 396 |
-
step4b_output = gr.Image(label="Step 4: Preprocessed Webcam Face", type="numpy")
|
| 397 |
-
|
| 398 |
-
gr.Markdown("### Step 5: Neural Network Processing")
|
| 399 |
-
gr.Markdown("*Images processed through deep convolutional neural network layers*")
|
| 400 |
-
gr.Info("Neural network processing happens internally - multiple convolutional, pooling, and dense layers extract features")
|
| 401 |
-
|
| 402 |
-
gr.Markdown("### Step 6: Face Embeddings (Feature Vectors)")
|
| 403 |
-
gr.Markdown("*Visual representation of high-dimensional embedding vectors*")
|
| 404 |
-
gr.Markdown("Each color represents a value in the embedding vector - similar patterns indicate similar faces")
|
| 405 |
-
|
| 406 |
-
with gr.Row():
|
| 407 |
-
step6a_output = gr.Image(label="Step 6: NID Face Embedding Visualization", type="numpy")
|
| 408 |
-
step6b_output = gr.Image(label="Step 6: Webcam Face Embedding Visualization", type="numpy")
|
| 409 |
-
|
| 410 |
-
gr.Markdown("### Step 7-9: Distance Calculation, Threshold Comparison & Final Result")
|
| 411 |
-
gr.Markdown("*Numerical comparison and decision-making process shown in the process steps above*")
|
| 412 |
-
|
| 413 |
-
# Button click event
|
| 414 |
-
verify_button.click(
|
| 415 |
-
fn=verify_faces_with_visualization,
|
| 416 |
-
inputs=[nid_input, webcam_input, model_dropdown],
|
| 417 |
-
outputs=[
|
| 418 |
-
result_output,
|
| 419 |
-
step1_output,
|
| 420 |
-
step2_output,
|
| 421 |
-
step3a_output,
|
| 422 |
-
step3b_output,
|
| 423 |
-
step4a_output,
|
| 424 |
-
step4b_output,
|
| 425 |
-
step6a_output,
|
| 426 |
-
step6b_output,
|
| 427 |
-
process_output
|
| 428 |
-
]
|
| 429 |
-
)
|
| 430 |
-
|
| 431 |
-
gr.Markdown(
|
| 432 |
-
"""
|
| 433 |
-
---
|
| 434 |
-
|
| 435 |
-
## 📖 Complete Process Explanation
|
| 436 |
-
|
| 437 |
-
### 🔄 The 9-Step Face Verification Pipeline:
|
| 438 |
-
|
| 439 |
-
| Step | Name | What Happens | Why It's Important |
|
| 440 |
-
|------|------|--------------|-------------------|
|
| 441 |
-
| **1-2** | **Face Detection** | Locates face in image using Haar Cascades or MTCNN | Must find face before processing |
|
| 442 |
-
| **3** | **Face Alignment** | Rotates and crops face using eye positions as reference | Standardizes face orientation |
|
| 443 |
-
| **4** | **Preprocessing** | Resizes to model input size, normalizes pixels to [0,1] | Prepares data for neural network |
|
| 444 |
-
| **5** | **Neural Network** | Passes through CNN layers (conv → pool → dense) | Extracts hierarchical features |
|
| 445 |
-
| **6** | **Embedding** | Final layer outputs N-dimensional vector (128-512D) | Compresses face to numerical representation |
|
| 446 |
-
| **7** | **Distance Calc** | Computes Euclidean/Cosine distance between vectors | Measures similarity mathematically |
|
| 447 |
-
| **8** | **Threshold** | Compares distance to model-specific threshold | Determines if similarity is high enough |
|
| 448 |
-
| **9** | **Decision** | Returns Match/No Match based on comparison | Final verification result |
|
| 449 |
-
|
| 450 |
-
---
|
| 451 |
-
|
| 452 |
-
### 🧠 Understanding Each Step in Detail:
|
| 453 |
-
|
| 454 |
-
#### Step 1-2: Face Detection
|
| 455 |
-
- **Input**: Full image (NID card or webcam photo)
|
| 456 |
-
- **Process**: Scans image with trained detector (OpenCV Haar Cascades, MTCNN, etc.)
|
| 457 |
-
- **Output**: Bounding box coordinates (x, y, width, height) of detected face
|
| 458 |
-
- **Visualization**: Green rectangle drawn around detected face with confidence score
|
| 459 |
-
|
| 460 |
-
#### Step 3: Face Alignment
|
| 461 |
-
- **Input**: Detected face region
|
| 462 |
-
- **Process**:
|
| 463 |
-
- Detects facial landmarks (eyes, nose, mouth)
|
| 464 |
-
- Calculates rotation angle to make eyes horizontal
|
| 465 |
-
- Crops to standard size maintaining face center
|
| 466 |
-
- **Output**: Aligned and cropped face image
|
| 467 |
-
- **Why**: Ensures all faces have same orientation for consistent comparison
|
| 468 |
-
|
| 469 |
-
#### Step 4: Preprocessing
|
| 470 |
-
- **Input**: Aligned face image
|
| 471 |
-
- **Process**:
|
| 472 |
-
- Resize to model's required input size (e.g., 224×224, 160×160)
|
| 473 |
-
- Convert pixel values from [0, 255] to [0, 1]
|
| 474 |
-
- May apply mean subtraction and standardization
|
| 475 |
-
- **Output**: Normalized face array ready for neural network
|
| 476 |
-
- **Why**: Neural networks require specific input formats
|
| 477 |
-
|
| 478 |
-
#### Step 5: Neural Network Processing
|
| 479 |
-
- **Input**: Preprocessed face array
|
| 480 |
-
- **Process**:
|
| 481 |
-
- Convolutional layers detect edges, textures, patterns
|
| 482 |
-
- Pooling layers reduce spatial dimensions
|
| 483 |
-
- Deeper layers detect complex features (eyes, nose shape, face structure)
|
| 484 |
-
- Fully connected layers combine features
|
| 485 |
-
- **Output**: Raw feature vector (pre-embedding)
|
| 486 |
-
- **Architecture**: VGG-Face (16-22 layers), ResNet (50-100 layers), ArcFace (custom architecture)
|
| 487 |
-
|
| 488 |
-
#### Step 6: Embedding Generation
|
| 489 |
-
- **Input**: Neural network output
|
| 490 |
-
- **Process**:
|
| 491 |
-
- Final dense layer compresses features to fixed-length vector
|
| 492 |
-
- Each dimension captures specific facial characteristic
|
| 493 |
-
- L2 normalization ensures unit length
|
| 494 |
-
- **Output**: N-dimensional embedding (128D, 512D, etc.)
|
| 495 |
-
- **Visualization**: Shown as colored heatmap where each pixel represents one dimension
|
| 496 |
-
- **Example**: [0.234, -0.456, 0.123, ..., 0.789] (512 numbers)
|
| 497 |
-
|
| 498 |
-
#### Step 7: Calculate Distance
|
| 499 |
-
- **Input**: Two embedding vectors (E1 and E2)
|
| 500 |
-
- **Formulas**:
|
| 501 |
-
- **Euclidean**: √(Σ(E1ᵢ - E2ᵢ)²)
|
| 502 |
-
- **Cosine**: 1 - (E1·E2)/(||E1||×||E2||)
|
| 503 |
-
- **Output**: Single distance value
|
| 504 |
-
- **Interpretation**:
|
| 505 |
-
- Smaller distance = More similar faces
|
| 506 |
-
- Larger distance = Less similar faces
|
| 507 |
-
|
| 508 |
-
#### Step 8: Threshold Comparison
|
| 509 |
-
- **Input**: Calculated distance and model threshold
|
| 510 |
-
- **Process**: Simple comparison: `if distance < threshold`
|
| 511 |
-
- **Thresholds** (examples):
|
| 512 |
-
- ArcFace: ~0.68 (Cosine)
|
| 513 |
-
- Facenet: ~0.40 (Euclidean)
|
| 514 |
-
- VGG-Face: ~0.40 (Cosine)
|
| 515 |
-
- **Output**: Boolean (True/False)
|
| 516 |
-
|
| 517 |
-
#### Step 9: Final Decision
|
| 518 |
-
- **Input**: Threshold comparison result
|
| 519 |
-
- **Output**:
|
| 520 |
-
- **MATCH** if distance < threshold
|
| 521 |
-
- **NO MATCH** if distance ≥ threshold
|
| 522 |
-
- **Confidence**: Calculated as percentage based on distance from threshold
|
| 523 |
-
|
| 524 |
-
---
|
| 525 |
-
|
| 526 |
-
### 🎯 Model Comparison
|
| 527 |
-
|
| 528 |
-
| Model | Embedding Size | Speed | Accuracy | Best For |
|
| 529 |
-
|-------|---------------|-------|----------|----------|
|
| 530 |
-
| **ArcFace** | 512D | Medium | 99.4%+ | High-security verification |
|
| 531 |
-
| **VGG-Face** | 2622D | Slow | 98.9%+ | High accuracy needed |
|
| 532 |
-
| **OpenFace** | 128D | Fast | 93%+ | Real-time applications |
|
| 533 |
-
| **Facenet** | 128D | Fast | 99.2%+ | Resource-constrained systems |
|
| 534 |
-
|
| 535 |
-
---
|
| 536 |
-
|
| 537 |
-
### 💡 Key Concepts
|
| 538 |
-
|
| 539 |
-
**What is an Embedding?**
|
| 540 |
-
- A mathematical representation of a face in high-dimensional space
|
| 541 |
-
- Similar faces have embeddings close together
|
| 542 |
-
- Different faces have embeddings far apart
|
| 543 |
-
- Think of it as "coordinates" for a face in 128-512 dimensional space
|
| 544 |
-
|
| 545 |
-
**Distance Metrics:**
|
| 546 |
-
- **Euclidean Distance**: Straight-line distance between two points
|
| 547 |
-
- **Cosine Distance**: Measures angle between vectors (better for normalized embeddings)
|
| 548 |
-
- **L2 Distance**: Similar to Euclidean, often used in face recognition
|
| 549 |
-
|
| 550 |
-
**Why Use Deep Learning?**
|
| 551 |
-
- Traditional methods (pixel comparison) fail with lighting, angle, expression changes
|
| 552 |
-
- Deep learning learns invariant features that work across variations
|
| 553 |
-
- Trained on millions of face images to recognize patterns humans can't describe
|
| 554 |
-
|
| 555 |
-
---
|
| 556 |
-
|
| 557 |
-
### ⚠️ Important Notes
|
| 558 |
-
|
| 559 |
-
**For Best Results:**
|
| 560 |
-
- ✅ Use clear, well-lit, front-facing photos
|
| 561 |
-
- ✅ Ensure face is unobstructed
|
| 562 |
-
- ✅ Similar lighting in both images helps
|
| 563 |
-
- ✅ High resolution images (at least 640×480)
|
| 564 |
-
|
| 565 |
-
**Limitations:**
|
| 566 |
-
- ❌ Won't work with heavily occluded faces (masks, sunglasses)
|
| 567 |
-
- ❌ Extreme angles or profiles reduce accuracy
|
| 568 |
-
- ❌ Very low quality or blurry images may fail
|
| 569 |
-
- ❌ Identical twins may be difficult to distinguish
|
| 570 |
-
|
| 571 |
-
---
|
| 572 |
-
|
| 573 |
-
**🔬 Educational Purpose**: This tool demonstrates how modern face recognition works.
|
| 574 |
-
For production systems, additional security measures and privacy protections are required.
|
| 575 |
-
"""
|
| 576 |
-
)
|
| 577 |
|
| 578 |
-
# Launch the app
|
| 579 |
if __name__ == "__main__":
|
| 580 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from Crypto.Cipher import AES
|
| 2 |
+
from Crypto.Protocol.KDF import PBKDF2
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
from dotenv import load_dotenv
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
load_dotenv() # Load all environment variables
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
def unpad(data):
|
| 10 |
+
return data[:-data[-1]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
def decrypt_and_run():
|
| 13 |
+
# Get password from Hugging Face Secrets environment variable
|
| 14 |
+
password = os.getenv("PASSWORD")
|
| 15 |
+
if not password:
|
| 16 |
+
raise ValueError("PASSWORD secret not found in environment variables")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
salt = encrypted[:16]
|
| 24 |
+
iv = encrypted[16:32]
|
| 25 |
+
ciphertext = encrypted[32:]
|
| 26 |
|
| 27 |
+
key = PBKDF2(password, salt, dkLen=32, count=1000000)
|
| 28 |
+
cipher = AES.new(key, AES.MODE_CBC, iv)
|
| 29 |
+
|
| 30 |
+
plaintext = unpad(cipher.decrypt(ciphertext))
|
| 31 |
+
|
| 32 |
+
with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode='wb') as tmp:
|
| 33 |
+
tmp.write(plaintext)
|
| 34 |
+
tmp.flush()
|
| 35 |
+
print(f"[INFO] Running decrypted code from {tmp.name}")
|
| 36 |
+
os.system(f"python {tmp.name}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
|
|
|
| 38 |
if __name__ == "__main__":
|
| 39 |
+
decrypt_and_run()
|
| 40 |
+
|
| 41 |
+
# This script decrypts the encrypted code and runs it.
|
| 42 |
+
# Ensure you have the PASSWORD secret set in your Hugging Face Secrets
|