Spaces:
Runtime error
Runtime error
no cache embeddings baches
Browse files
app.py
CHANGED
@@ -2,12 +2,11 @@ import numpy as np
|
|
2 |
from PIL import Image
|
3 |
import gradio as gr
|
4 |
from deepface import DeepFace
|
5 |
-
from datasets import load_dataset, DownloadConfig
|
6 |
import os
|
7 |
import pickle
|
8 |
from pathlib import Path
|
9 |
import gc
|
10 |
-
import io
|
11 |
|
12 |
# 🔑 Configurar token de Hugging Face
|
13 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
@@ -19,33 +18,23 @@ EMBEDDINGS_DIR = Path("embeddings")
|
|
19 |
EMBEDDINGS_DIR.mkdir(exist_ok=True)
|
20 |
EMBEDDINGS_FILE = EMBEDDINGS_DIR / "embeddings.pkl"
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
# ✅ Cargar el dataset de Hugging Face forzando la descarga limpia
|
25 |
-
download_config = DownloadConfig(
|
26 |
-
force_download=True,
|
27 |
-
token=HF_TOKEN
|
28 |
-
)
|
29 |
dataset = load_dataset("Segizu/facial-recognition", download_config=download_config)
|
30 |
if "train" in dataset:
|
31 |
dataset = dataset["train"]
|
32 |
|
|
|
|
|
|
|
33 |
# 🔄 Preprocesar imagen para Facenet
|
34 |
-
def preprocess_image(img):
|
35 |
-
if isinstance(img, str):
|
36 |
-
# Si es una ruta de archivo o bytes en string
|
37 |
-
img = Image.open(io.BytesIO(img.encode() if isinstance(img, str) else img))
|
38 |
-
elif isinstance(img, bytes):
|
39 |
-
# Si son bytes directos
|
40 |
-
img = Image.open(io.BytesIO(img))
|
41 |
-
|
42 |
img_rgb = img.convert("RGB")
|
43 |
img_resized = img_rgb.resize((160, 160), Image.Resampling.LANCZOS)
|
44 |
return np.array(img_resized)
|
45 |
|
46 |
# 📦 Construir base de datos de embeddings
|
47 |
def build_database():
|
48 |
-
# Intentar cargar embeddings desde el archivo
|
49 |
if EMBEDDINGS_FILE.exists():
|
50 |
print("📂 Cargando embeddings desde el archivo...")
|
51 |
with open(EMBEDDINGS_FILE, 'rb') as f:
|
@@ -53,61 +42,45 @@ def build_database():
|
|
53 |
|
54 |
print("🔄 Calculando embeddings (esto puede tomar unos minutos)...")
|
55 |
database = []
|
56 |
-
batch_size = 10
|
57 |
|
58 |
for i in range(0, len(dataset), batch_size):
|
59 |
batch = dataset[i:i + batch_size]
|
60 |
-
print(f"📦 Procesando lote {i//batch_size + 1}/{(len(dataset) + batch_size - 1)//batch_size}")
|
61 |
|
62 |
for j, item in enumerate(batch):
|
63 |
try:
|
64 |
-
#
|
65 |
-
print(f"Estructura del item {i+j}:", type(item), item.keys() if hasattr(item, 'keys') else "No tiene keys")
|
66 |
-
|
67 |
-
# Intentar diferentes formas de acceder a la imagen
|
68 |
-
if isinstance(item, dict):
|
69 |
-
if 'image' in item:
|
70 |
-
img = item['image']
|
71 |
-
elif 'bytes' in item:
|
72 |
-
img = item['bytes']
|
73 |
-
else:
|
74 |
-
print(f"❌ No se encontró la imagen en el item {i+j}")
|
75 |
-
continue
|
76 |
-
else:
|
77 |
-
print(f"❌ Formato de item no reconocido: {type(item)}")
|
78 |
-
continue
|
79 |
-
|
80 |
img_processed = preprocess_image(img)
|
81 |
embedding = DeepFace.represent(
|
82 |
img_path=img_processed,
|
83 |
model_name="Facenet",
|
84 |
enforce_detection=False
|
85 |
)[0]["embedding"]
|
|
|
86 |
database.append((f"image_{i+j}", img, embedding))
|
87 |
print(f"✅ Procesada imagen {i+j+1}/{len(dataset)}")
|
88 |
|
89 |
# Liberar memoria
|
90 |
del img_processed
|
91 |
gc.collect()
|
92 |
-
|
93 |
except Exception as e:
|
94 |
print(f"❌ No se pudo procesar imagen {i+j}: {str(e)}")
|
95 |
-
print(f"Tipo de error: {type(e)}")
|
96 |
continue
|
97 |
|
98 |
-
# Guardar progreso
|
99 |
-
if database:
|
100 |
print("💾 Guardando progreso...")
|
101 |
with open(EMBEDDINGS_FILE, 'wb') as f:
|
102 |
pickle.dump(database, f)
|
103 |
|
104 |
-
# Liberar memoria después de cada lote
|
105 |
gc.collect()
|
106 |
|
107 |
return database
|
108 |
|
109 |
# 🔍 Buscar rostros similares
|
110 |
-
def find_similar_faces(uploaded_image):
|
111 |
try:
|
112 |
img_processed = preprocess_image(uploaded_image)
|
113 |
query_embedding = DeepFace.represent(
|
@@ -115,11 +88,8 @@ def find_similar_faces(uploaded_image):
|
|
115 |
model_name="Facenet",
|
116 |
enforce_detection=False
|
117 |
)[0]["embedding"]
|
118 |
-
|
119 |
-
# Liberar memoria
|
120 |
del img_processed
|
121 |
gc.collect()
|
122 |
-
|
123 |
except Exception as e:
|
124 |
print(f"Error al procesar imagen de consulta: {str(e)}")
|
125 |
return [], "⚠ No se detectó un rostro válido en la imagen."
|
|
|
2 |
from PIL import Image
|
3 |
import gradio as gr
|
4 |
from deepface import DeepFace
|
5 |
+
from datasets import load_dataset, DownloadConfig, Image as HfImage
|
6 |
import os
|
7 |
import pickle
|
8 |
from pathlib import Path
|
9 |
import gc
|
|
|
10 |
|
11 |
# 🔑 Configurar token de Hugging Face
|
12 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
18 |
EMBEDDINGS_DIR.mkdir(exist_ok=True)
|
19 |
EMBEDDINGS_FILE = EMBEDDINGS_DIR / "embeddings.pkl"
|
20 |
|
21 |
+
# ✅ Cargar el dataset de Hugging Face con imágenes decodificadas
|
22 |
+
download_config = DownloadConfig(force_download=True, token=HF_TOKEN)
|
|
|
|
|
|
|
|
|
|
|
23 |
dataset = load_dataset("Segizu/facial-recognition", download_config=download_config)
|
24 |
if "train" in dataset:
|
25 |
dataset = dataset["train"]
|
26 |
|
27 |
+
# Asegurar que la columna 'image' sea del tipo imagen
|
28 |
+
dataset = dataset.cast_column("image", HfImage())
|
29 |
+
|
30 |
# 🔄 Preprocesar imagen para Facenet
|
31 |
+
def preprocess_image(img: Image.Image) -> np.ndarray:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
img_rgb = img.convert("RGB")
|
33 |
img_resized = img_rgb.resize((160, 160), Image.Resampling.LANCZOS)
|
34 |
return np.array(img_resized)
|
35 |
|
36 |
# 📦 Construir base de datos de embeddings
|
37 |
def build_database():
|
|
|
38 |
if EMBEDDINGS_FILE.exists():
|
39 |
print("📂 Cargando embeddings desde el archivo...")
|
40 |
with open(EMBEDDINGS_FILE, 'rb') as f:
|
|
|
42 |
|
43 |
print("🔄 Calculando embeddings (esto puede tomar unos minutos)...")
|
44 |
database = []
|
45 |
+
batch_size = 10
|
46 |
|
47 |
for i in range(0, len(dataset), batch_size):
|
48 |
batch = dataset[i:i + batch_size]
|
49 |
+
print(f"📦 Procesando lote {i // batch_size + 1}/{(len(dataset) + batch_size - 1) // batch_size}")
|
50 |
|
51 |
for j, item in enumerate(batch):
|
52 |
try:
|
53 |
+
img = item["image"] # Ya es un objeto PIL.Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
img_processed = preprocess_image(img)
|
55 |
embedding = DeepFace.represent(
|
56 |
img_path=img_processed,
|
57 |
model_name="Facenet",
|
58 |
enforce_detection=False
|
59 |
)[0]["embedding"]
|
60 |
+
|
61 |
database.append((f"image_{i+j}", img, embedding))
|
62 |
print(f"✅ Procesada imagen {i+j+1}/{len(dataset)}")
|
63 |
|
64 |
# Liberar memoria
|
65 |
del img_processed
|
66 |
gc.collect()
|
67 |
+
|
68 |
except Exception as e:
|
69 |
print(f"❌ No se pudo procesar imagen {i+j}: {str(e)}")
|
|
|
70 |
continue
|
71 |
|
72 |
+
# Guardar progreso
|
73 |
+
if database:
|
74 |
print("💾 Guardando progreso...")
|
75 |
with open(EMBEDDINGS_FILE, 'wb') as f:
|
76 |
pickle.dump(database, f)
|
77 |
|
|
|
78 |
gc.collect()
|
79 |
|
80 |
return database
|
81 |
|
82 |
# 🔍 Buscar rostros similares
|
83 |
+
def find_similar_faces(uploaded_image: Image.Image):
|
84 |
try:
|
85 |
img_processed = preprocess_image(uploaded_image)
|
86 |
query_embedding = DeepFace.represent(
|
|
|
88 |
model_name="Facenet",
|
89 |
enforce_detection=False
|
90 |
)[0]["embedding"]
|
|
|
|
|
91 |
del img_processed
|
92 |
gc.collect()
|
|
|
93 |
except Exception as e:
|
94 |
print(f"Error al procesar imagen de consulta: {str(e)}")
|
95 |
return [], "⚠ No se detectó un rostro válido en la imagen."
|