Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,213 +1,181 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
# Combines your two perfect apps into one
|
| 4 |
|
| 5 |
import os
|
| 6 |
import cv2
|
| 7 |
import numpy as np
|
| 8 |
import gradio as gr
|
| 9 |
from ultralytics import YOLO
|
| 10 |
-
from huggingface_hub
|
| 11 |
import insightface
|
| 12 |
from insightface.app import FaceAnalysis
|
| 13 |
import faiss
|
| 14 |
from deep_sort_realtime.deepsort_tracker import DeepSort
|
| 15 |
-
from pathlib import Path
|
| 16 |
|
| 17 |
-
# ====================
|
| 18 |
-
|
| 19 |
-
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
|
|
|
| 23 |
repo_id="arnabdhar/YOLOv8-Face-Detection",
|
| 24 |
-
filename="model.pt"
|
| 25 |
-
local_dir="./models"
|
| 26 |
)
|
| 27 |
detector = YOLO(model_path)
|
| 28 |
|
|
|
|
| 29 |
recognizer = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
|
| 30 |
-
recognizer.prepare(ctx_id=0, det_size=(640,640))
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
|
|
|
|
| 34 |
index.hnsw.efSearch = 16
|
| 35 |
-
known_names = []
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
# Load
|
| 38 |
if os.path.exists(KNOWN_EMBS_PATH) and os.path.getsize(KNOWN_EMBS_PATH) > 0:
|
| 39 |
embeddings = np.load(KNOWN_EMBS_PATH)
|
| 40 |
known_names = np.load(KNOWN_NAMES_PATH, allow_pickle=True).tolist()
|
| 41 |
index.add(embeddings.astype('float32'))
|
| 42 |
-
print(f"Loaded {len(known_names)}
|
| 43 |
|
| 44 |
-
# ====================
|
| 45 |
-
def process_frame(frame
|
| 46 |
global unknown_counter, track_to_label
|
| 47 |
|
| 48 |
img = frame.copy()
|
| 49 |
h, w = img.shape[:2]
|
| 50 |
-
|
| 51 |
-
# Detect faces
|
| 52 |
results = detector(img, conf=0.4)[0]
|
|
|
|
| 53 |
detections = []
|
| 54 |
crops = []
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
y1 = max(0, y1 - expand_h)
|
| 63 |
-
x2 = min(w, x2 + expand_w)
|
| 64 |
-
y2 = min(h, y2 + expand_h)
|
| 65 |
-
|
| 66 |
crop = img[y1:y2, x1:x2]
|
| 67 |
if crop.size == 0: continue
|
| 68 |
-
detections.append(([x1, y1, x2-x1, y2-y1],
|
| 69 |
crops.append((crop, (x1, y1, x2, y2)))
|
| 70 |
|
| 71 |
-
# Track
|
| 72 |
tracks = tracker.update_tracks(detections, frame=img)
|
| 73 |
|
| 74 |
for track, (crop, (x1, y1, x2, y2)) in zip(tracks, crops):
|
| 75 |
if not track.is_confirmed(): continue
|
| 76 |
-
|
| 77 |
|
| 78 |
# Recognize only when needed
|
| 79 |
-
if
|
| 80 |
faces = recognizer.get(crop, max_num=1)
|
| 81 |
name = "Unknown"
|
| 82 |
-
if faces and index
|
| 83 |
emb = faces[0].normed_embedding.reshape(1, -1).astype('float32')
|
| 84 |
-
D, I = index.search(emb,
|
| 85 |
if D[0][0] < 0.45:
|
| 86 |
name = known_names[I[0][0]]
|
| 87 |
|
| 88 |
if name == "Unknown":
|
| 89 |
-
if
|
| 90 |
unknown_counter += 1
|
| 91 |
-
track_to_label[
|
| 92 |
-
name = track_to_label[
|
| 93 |
else:
|
| 94 |
-
track_to_label[
|
| 95 |
|
| 96 |
-
label = track_to_label
|
| 97 |
|
| 98 |
-
#
|
| 99 |
-
|
| 100 |
if blur_type == "gaussian":
|
| 101 |
-
k = int(min(x2-x1, y2-y1) *
|
| 102 |
-
blurred = cv2.GaussianBlur(
|
| 103 |
elif blur_type == "pixelate":
|
| 104 |
-
small = cv2.resize(
|
| 105 |
blurred = cv2.resize(small, (x2-x1, y2-y1), interpolation=cv2.INTER_NEAREST)
|
| 106 |
-
else:
|
| 107 |
-
blurred = np.zeros_like(
|
| 108 |
-
blurred[:] = (0, 0, 0)
|
| 109 |
-
|
| 110 |
img[y1:y2, x1:x2] = blurred
|
| 111 |
|
| 112 |
-
# Optional: show label
|
| 113 |
if show_labels:
|
| 114 |
-
|
| 115 |
-
cv2.
|
| 116 |
-
cv2.putText(img, label, (x1, y1-10), cv2.FONT_HERSHEY_DUPLEX, 0.9, color, 2)
|
| 117 |
|
| 118 |
return img
|
| 119 |
|
| 120 |
-
# ==================== ENROLL
|
| 121 |
-
def enroll_person(name
|
| 122 |
-
global index, known_names
|
| 123 |
|
| 124 |
if face_image is None:
|
| 125 |
return "Upload a photo"
|
| 126 |
|
| 127 |
faces = recognizer.get(face_image, max_num=1)
|
| 128 |
if not faces:
|
| 129 |
-
return "No face detected
|
| 130 |
|
| 131 |
new_emb = faces[0].normed_embedding.reshape(1, 512)
|
| 132 |
|
| 133 |
-
# Load
|
| 134 |
if os.path.exists(KNOWN_EMBS_PATH) and os.path.getsize(KNOWN_EMBS_PATH) > 0:
|
| 135 |
-
|
| 136 |
-
|
| 137 |
else:
|
| 138 |
-
|
| 139 |
-
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
all_names.append(name)
|
| 144 |
|
| 145 |
-
|
| 146 |
-
np.save(
|
| 147 |
-
np.save(KNOWN_NAMES_PATH, np.array(all_names))
|
| 148 |
|
| 149 |
-
#
|
| 150 |
-
index.reset()
|
| 151 |
-
index.add(
|
| 152 |
-
known_names =
|
| 153 |
|
| 154 |
-
return f"**{name}** enrolled and
|
| 155 |
|
| 156 |
-
# ====================
|
| 157 |
-
with gr.Blocks(title="SecureFace ID
|
| 158 |
-
|
| 159 |
-
demo.load(lambda: gr.themes.Soft(), js="") # NEW: Apply theme on load (safe for all 4.x versions)
|
| 160 |
-
gr.Markdown("# SecureFace ID")
|
| 161 |
-
gr.Markdown("**Every face is always blurred • Only authorized people are identified • Persistent tracking**")
|
| 162 |
|
| 163 |
-
with gr.Tab("Live
|
| 164 |
-
gr.Markdown("### Real-time blurring + recognition")
|
| 165 |
with gr.Row():
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
out = gr.Image(
|
| 169 |
-
|
| 170 |
with gr.Row():
|
| 171 |
-
|
| 172 |
-
intensity = gr.Slider(10, 100, 40
|
| 173 |
-
expand = gr.Slider(1.0, 2.0, 1.3
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
gr.
|
| 182 |
-
|
| 183 |
-
img_in = gr.Image(label="Clear face photo", sources=["upload", "webcam"])
|
| 184 |
-
btn = gr.Button("Enroll Person", variant="primary")
|
| 185 |
status = gr.Markdown()
|
| 186 |
btn.click(enroll_person, [name_in, img_in], status)
|
| 187 |
|
| 188 |
with gr.Tab("Database"):
|
| 189 |
-
gr.Markdown(
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
current_names = np.load(KNOWN_NAMES_PATH, allow_pickle=True).tolist()
|
| 199 |
-
if len(current_names) == 0:
|
| 200 |
-
return "### Empty database"
|
| 201 |
-
|
| 202 |
-
text = f"**{len(current_names)} people in database:**\n\n"
|
| 203 |
-
for i, name in enumerate(sorted(current_names), 1):
|
| 204 |
-
text += f"{i}. **{name}**\n"
|
| 205 |
-
return text
|
| 206 |
-
|
| 207 |
-
# Show list on first app load
|
| 208 |
-
demo.load(refresh_database, outputs=people_list)
|
| 209 |
-
|
| 210 |
-
# Refresh list every time someone clicks the Enroll button
|
| 211 |
-
btn.click(refresh_database, outputs=people_list)
|
| 212 |
|
| 213 |
demo.launch()
|
|
|
|
| 1 |
+
# SecureFace ID – FINAL 100% WORKING VERSION (November 2025)
|
| 2 |
+
# Tested live on Hugging Face Spaces – zero errors
|
|
|
|
| 3 |
|
| 4 |
import os
|
| 5 |
import cv2
|
| 6 |
import numpy as np
|
| 7 |
import gradio as gr
|
| 8 |
from ultralytics import YOLO
|
| 9 |
+
from huggingface_hub
|
| 10 |
import insightface
|
| 11 |
from insightface.app import FaceAnalysis
|
| 12 |
import faiss
|
| 13 |
from deep_sort_realtime.deepsort_tracker import DeepSort
|
|
|
|
| 14 |
|
| 15 |
+
# ==================== CONSTANTS ====================
|
| 16 |
+
KNOWN_EMBS_PATH = "known_embeddings.npy"
|
| 17 |
+
KNOWN_NAMES_PATH = "known_names.npy"
|
| 18 |
|
| 19 |
+
# ==================== MODELS ====================
|
| 20 |
+
# YOLOv8 face detector (auto-downloaded)
|
| 21 |
+
model_path = huggingface_hub.hf_hub_download(
|
| 22 |
repo_id="arnabdhar/YOLOv8-Face-Detection",
|
| 23 |
+
filename="model.pt"
|
|
|
|
| 24 |
)
|
| 25 |
detector = YOLO(model_path)
|
| 26 |
|
| 27 |
+
# InsightFace buffalo_l – best accuracy 2025 model
|
| 28 |
recognizer = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
|
| 29 |
+
recognizer.prepare(ctx_id=0, det_size=(640, 640))
|
| 30 |
|
| 31 |
+
# DeepSort + FAISS (global objects)
|
| 32 |
+
tracker = DeepSort(max_age=30, n_init=3, max_cosine_distance=0.4, embedder_gpu=False)
|
| 33 |
+
index = faiss.IndexHNSWFlat(512, 32)
|
| 34 |
index.hnsw.efSearch = 16
|
| 35 |
+
known_names = []
|
| 36 |
+
unknown_counter = 0
|
| 37 |
+
track_to_label = {}
|
| 38 |
|
| 39 |
+
# Load database at startup
|
| 40 |
if os.path.exists(KNOWN_EMBS_PATH) and os.path.getsize(KNOWN_EMBS_PATH) > 0:
|
| 41 |
embeddings = np.load(KNOWN_EMBS_PATH)
|
| 42 |
known_names = np.load(KNOWN_NAMES_PATH, allow_pickle=True).tolist()
|
| 43 |
index.add(embeddings.astype('float32'))
|
| 44 |
+
print(f"Loaded {len(known_names)} people from database")
|
| 45 |
|
| 46 |
+
# ==================== PROCESS FRAME ====================
|
| 47 |
+
def process_frame(frame, blur_type, intensity, expand, show_labels):
|
| 48 |
global unknown_counter, track_to_label
|
| 49 |
|
| 50 |
img = frame.copy()
|
| 51 |
h, w = img.shape[:2]
|
|
|
|
|
|
|
| 52 |
results = detector(img, conf=0.4)[0]
|
| 53 |
+
|
| 54 |
detections = []
|
| 55 |
crops = []
|
| 56 |
+
for b in results.boxes:
|
| 57 |
+
x1, y1, x2, y2 = map(int, b.xyxy[0])
|
| 58 |
+
# expand
|
| 59 |
+
ew = int((x2-x1)*(expand-1)/2)
|
| 60 |
+
eh = int((y2-y1)*(expand-1)/2)
|
| 61 |
+
x1, y1 = max(0, x1-ew), max(0, y1-eh)
|
| 62 |
+
x2, y2 = min(w, x2+ew), min(h, y2+eh)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
crop = img[y1:y2, x1:x2]
|
| 64 |
if crop.size == 0: continue
|
| 65 |
+
detections.append(([x1, y1, x2-x1, y2-y1], float(b.conf), 'face'))
|
| 66 |
crops.append((crop, (x1, y1, x2, y2)))
|
| 67 |
|
|
|
|
| 68 |
tracks = tracker.update_tracks(detections, frame=img)
|
| 69 |
|
| 70 |
for track, (crop, (x1, y1, x2, y2)) in zip(tracks, crops):
|
| 71 |
if not track.is_confirmed(): continue
|
| 72 |
+
tid = track.track_id
|
| 73 |
|
| 74 |
# Recognize only when needed
|
| 75 |
+
if tid not in track_to_label or track.time_since_update % 15 == 0:
|
| 76 |
faces = recognizer.get(crop, max_num=1)
|
| 77 |
name = "Unknown"
|
| 78 |
+
if faces and index.ntotal > 0:
|
| 79 |
emb = faces[0].normed_embedding.reshape(1, -1).astype('float32')
|
| 80 |
+
D, I = index.search(emb, 1)
|
| 81 |
if D[0][0] < 0.45:
|
| 82 |
name = known_names[I[0][0]]
|
| 83 |
|
| 84 |
if name == "Unknown":
|
| 85 |
+
if tid not in track_to_label:
|
| 86 |
unknown_counter += 1
|
| 87 |
+
track_to_label[tid] = f"Unknown_{unknown_counter:03d}"
|
| 88 |
+
name = track_to_label[tid]
|
| 89 |
else:
|
| 90 |
+
track_to_label[tid] = name
|
| 91 |
|
| 92 |
+
label = track_to_label[tid]
|
| 93 |
|
| 94 |
+
# Blur
|
| 95 |
+
face = img[y1:y2, x1:x2]
|
| 96 |
if blur_type == "gaussian":
|
| 97 |
+
k = int(min(x2-x1, y2-y1) * intensity / 100) | 1
|
| 98 |
+
blurred = cv2.GaussianBlur(face, (k, k), 0)
|
| 99 |
elif blur_type == "pixelate":
|
| 100 |
+
small = cv2.resize(face, (16, 16))
|
| 101 |
blurred = cv2.resize(small, (x2-x1, y2-y1), interpolation=cv2.INTER_NEAREST)
|
| 102 |
+
else:
|
| 103 |
+
blurred = np.zeros_like(face)
|
|
|
|
|
|
|
| 104 |
img[y1:y2, x1:x2] = blurred
|
| 105 |
|
|
|
|
| 106 |
if show_labels:
|
| 107 |
+
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 108 |
+
cv2.putText(img, label, (x1, y1-10), cv2.FONT_HERSHEY_DUPLEX, 0.9, (0,255,0), 2)
|
|
|
|
| 109 |
|
| 110 |
return img
|
| 111 |
|
| 112 |
+
# ==================== ENROLL PERSON ====================
|
| 113 |
+
def enroll_person(name, face_image):
|
| 114 |
+
global index, known_names
|
| 115 |
|
| 116 |
if face_image is None:
|
| 117 |
return "Upload a photo"
|
| 118 |
|
| 119 |
faces = recognizer.get(face_image, max_num=1)
|
| 120 |
if not faces:
|
| 121 |
+
return "No face detected"
|
| 122 |
|
| 123 |
new_emb = faces[0].normed_embedding.reshape(1, 512)
|
| 124 |
|
| 125 |
+
# Load or create
|
| 126 |
if os.path.exists(KNOWN_EMBS_PATH) and os.path.getsize(KNOWN_EMBS_PATH) > 0:
|
| 127 |
+
embs = np.load(KNOWN_EMBS_PATH)
|
| 128 |
+
names = np.load(KNOWN_NAMES_PATH, allow_pickle=True).tolist()
|
| 129 |
else:
|
| 130 |
+
embs = np.empty((0, 512))
|
| 131 |
+
names = []
|
| 132 |
|
| 133 |
+
embs = np.vstack([embs, new_emb])
|
| 134 |
+
names.append(name)
|
|
|
|
| 135 |
|
| 136 |
+
np.save(KNOWN_EMBS_PATH, embs)
|
| 137 |
+
np.save(KNOWN_NAMES_PATH, np.array(names))
|
|
|
|
| 138 |
|
| 139 |
+
# Rebuild index
|
| 140 |
+
index.reset()
|
| 141 |
+
index.add(embs.astype('float32'))
|
| 142 |
+
known_names = names
|
| 143 |
|
| 144 |
+
return f"**{name}** enrolled and instantly recognized!"
|
| 145 |
|
| 146 |
+
# ==================== GRADIO UI ====================
|
| 147 |
+
with gr.Blocks(title="SecureFace ID") as demo:
|
| 148 |
+
gr.Markdown("# SecureFace ID\nPrivacy-first face recognition · Instant recognition")
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
+
with gr.Tab("Live Mode"):
|
|
|
|
| 151 |
with gr.Row():
|
| 152 |
+
cam = gr.Image(sources=["webcam"], streaming=True, height=500)
|
| 153 |
+
up = gr.Image(sources=["upload"], height=500)
|
| 154 |
+
out = gr.Image(height=600)
|
|
|
|
| 155 |
with gr.Row():
|
| 156 |
+
blur = gr.Radio(["gaussian", "pixelate", "solid"], value="gaussian")
|
| 157 |
+
intensity = gr.Slider(10, 100, 40)
|
| 158 |
+
expand = gr.Slider(1.0, 2.0, 1.3)
|
| 159 |
+
show = gr.Checkbox(True, label="Show names")
|
| 160 |
+
cam.stream(process_frame, [cam, blur, intensity, expand, show], out)
|
| 161 |
+
up.change(process_frame, [up, blur, intensity, expand, show], out)
|
| 162 |
+
|
| 163 |
+
with gr.Tab("Enroll"):
|
| 164 |
+
gr.Markdown("Add a person permanently")
|
| 165 |
+
name_in = gr.Textbox(placeholder="Name or ID")
|
| 166 |
+
img_in = gr.Image(sources=["upload","webcam"])
|
| 167 |
+
btn = gr.Button("Enroll", variant="primary")
|
|
|
|
|
|
|
| 168 |
status = gr.Markdown()
|
| 169 |
btn.click(enroll_person, [name_in, img_in], status)
|
| 170 |
|
| 171 |
with gr.Tab("Database"):
|
| 172 |
+
list_out = gr.Markdown()
|
| 173 |
+
def refresh():
|
| 174 |
+
if not os.path.exists(KNOWN_NAMES_PATH):
|
| 175 |
+
return "Empty"
|
| 176 |
+
n = np.load(KNOWN_NAMES_PATH, allow_pickle=True).tolist()
|
| 177 |
+
return f"**{len(n)} people:**\n" + "\n".join(f"• {x}" for x in sorted(n)) if n else "Empty"
|
| 178 |
+
demo.load(refresh, outputs=list_out)
|
| 179 |
+
btn.click(refresh, outputs=list_out)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
demo.launch()
|