Spaces:
Running
on
Zero
Running
on
Zero
- app.py +50 -68
- apt.txt +0 -4
- requirements.txt +1 -6
app.py
CHANGED
@@ -1,85 +1,67 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import face_recognition
|
3 |
-
import numpy as np
|
4 |
import os
|
|
|
5 |
from PIL import Image
|
6 |
-
import
|
7 |
-
|
8 |
-
# Verificar si CUDA está disponible y seleccionar el modelo adecuado
|
9 |
-
if dlib.DLIB_USE_CUDA:
|
10 |
-
print("✅ CUDA está disponible. Se usará GPU para reconocimiento facial.")
|
11 |
-
model_used = "cnn" # Modelo optimizado para GPU
|
12 |
-
else:
|
13 |
-
print("⚠ CUDA no está disponible. Se usará CPU para reconocimiento facial.")
|
14 |
-
model_used = "hog" # Modelo más adecuado para CPU
|
15 |
|
16 |
-
#
|
17 |
IMAGE_DIRECTORY = "dataset_faces/"
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
known_images.append(path)
|
35 |
-
known_names.append(filename)
|
36 |
-
return known_encodings, known_images, known_names
|
37 |
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
if uploaded_image is None:
|
47 |
-
return [], "No se subió ninguna imagen."
|
48 |
-
|
49 |
-
# Convertir la imagen subida a array de NumPy
|
50 |
-
image_np = np.array(uploaded_image)
|
51 |
-
face_encodings = face_recognition.face_encodings(image_np, model=model_used)
|
52 |
-
if not face_encodings:
|
53 |
-
return [], "⚠ No se detectó ningún rostro en la imagen subida."
|
54 |
-
|
55 |
-
query_encoding = face_encodings[0]
|
56 |
-
distances = face_recognition.face_distance(known_encodings, query_encoding)
|
57 |
-
sorted_indices = np.argsort(distances) # Ordenar por similitud (menor distancia = mayor similitud)
|
58 |
-
|
59 |
-
# Mostrar las 5 imágenes más similares
|
60 |
-
top_n = 5
|
61 |
gallery_items = []
|
62 |
-
|
63 |
-
for
|
64 |
-
|
65 |
-
|
66 |
-
similarity = 1 - distances[idx] # Definir similitud (valor entre 0 y 1)
|
67 |
-
caption = f"{os.path.basename(known_images[idx])}: Similitud: {similarity:.2f}"
|
68 |
gallery_items.append({"image": img, "caption": caption})
|
69 |
-
|
70 |
-
|
71 |
-
return gallery_items,
|
72 |
|
73 |
-
#
|
74 |
demo = gr.Interface(
|
75 |
-
fn=
|
76 |
-
inputs=gr.Image(label="Sube una imagen", type="pil"),
|
77 |
outputs=[
|
78 |
-
gr.Gallery(label="
|
79 |
-
gr.Textbox(label="
|
80 |
],
|
81 |
-
title="🔍 Buscador de Rostros
|
82 |
-
description="Sube una imagen y
|
83 |
)
|
84 |
|
85 |
demo.launch()
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import numpy as np
|
3 |
from PIL import Image
|
4 |
+
import gradio as gr
|
5 |
+
from deepface import DeepFace
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
# Ruta de la carpeta con rostros
|
8 |
IMAGE_DIRECTORY = "dataset_faces/"
|
9 |
|
10 |
+
# Cargar embeddings de todas las imágenes del dataset
|
11 |
+
def build_database():
|
12 |
+
database = []
|
13 |
+
for filename in os.listdir(IMAGE_DIRECTORY):
|
14 |
+
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
|
15 |
+
path = os.path.join(IMAGE_DIRECTORY, filename)
|
16 |
+
try:
|
17 |
+
representation = DeepFace.represent(img_path=path, model_name="Facenet")[0]["embedding"]
|
18 |
+
database.append((filename, path, representation))
|
19 |
+
except:
|
20 |
+
print(f"❌ No se pudo procesar: {filename}")
|
21 |
+
return database
|
22 |
+
|
23 |
+
# Inicializamos base de datos
|
24 |
+
database = build_database()
|
25 |
|
26 |
+
# Comparar imagen cargada con las del dataset
|
27 |
+
def find_similar_faces(uploaded_image):
|
28 |
+
try:
|
29 |
+
uploaded_image = np.array(uploaded_image)
|
30 |
+
query_representation = DeepFace.represent(img_path=uploaded_image, model_name="Facenet")[0]["embedding"]
|
31 |
+
except:
|
32 |
+
return [], "⚠ No se detectó un rostro válido en la imagen."
|
|
|
|
|
|
|
33 |
|
34 |
+
similarities = []
|
35 |
+
for name, path, rep in database:
|
36 |
+
distance = np.linalg.norm(np.array(query_representation) - np.array(rep))
|
37 |
+
similarity = 1 / (1 + distance) # Normalizamos para que 1 = muy similar
|
38 |
+
similarities.append((similarity, name, path))
|
39 |
|
40 |
+
# Ordenar por similitud
|
41 |
+
similarities.sort(reverse=True)
|
42 |
+
top_matches = similarities[:5]
|
43 |
+
|
44 |
+
# Formatear salida para gradio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
gallery_items = []
|
46 |
+
text_summary = ""
|
47 |
+
for sim, name, path in top_matches:
|
48 |
+
img = Image.open(path)
|
49 |
+
caption = f"{name} - Similitud: {sim:.2f}"
|
|
|
|
|
50 |
gallery_items.append({"image": img, "caption": caption})
|
51 |
+
text_summary += caption + "\n"
|
52 |
+
|
53 |
+
return gallery_items, text_summary
|
54 |
|
55 |
+
# Interfaz Gradio
|
56 |
demo = gr.Interface(
|
57 |
+
fn=find_similar_faces,
|
58 |
+
inputs=gr.Image(label="📤 Sube una imagen", type="pil"),
|
59 |
outputs=[
|
60 |
+
gr.Gallery(label="📸 Rostros más similares").style(grid=[2], height="auto"),
|
61 |
+
gr.Textbox(label="🧠 Similitud", lines=6)
|
62 |
],
|
63 |
+
title="🔍 Buscador de Rostros con DeepFace",
|
64 |
+
description="Sube una imagen y te mostrará los rostros más similares desde el directorio `dataset_faces/`."
|
65 |
)
|
66 |
|
67 |
demo.launch()
|
apt.txt
DELETED
@@ -1,4 +0,0 @@
|
|
1 |
-
cmake
|
2 |
-
libboost-all-dev
|
3 |
-
libgtk-3-dev
|
4 |
-
build-essential
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -1,10 +1,5 @@
|
|
1 |
gradio
|
2 |
numpy
|
3 |
Pillow
|
|
|
4 |
opencv-python-headless
|
5 |
-
|
6 |
-
# Usa face_recognition desde GitHub
|
7 |
-
git+https://github.com/ageitgey/face_recognition.git
|
8 |
-
|
9 |
-
# Asegura versión de dlib
|
10 |
-
dlib==19.24.0
|
|
|
1 |
gradio
|
2 |
numpy
|
3 |
Pillow
|
4 |
+
deepface
|
5 |
opencv-python-headless
|
|
|
|
|
|
|
|
|
|
|
|