Segizu commited on
Commit
6773de5
·
1 Parent(s): d3af2e5

metadata v12

Browse files
Files changed (1) hide show
  1. app.py +27 -33
app.py CHANGED
@@ -8,25 +8,24 @@ import pickle
8
  from pathlib import Path
9
  import gc
10
 
11
- # 🔐 Token automático (si es necesario)
12
- HF_TOKEN = os.getenv("HF_TOKEN")
13
-
14
- # 📁 Directorio para embeddings
15
  EMBEDDINGS_DIR = Path("embeddings")
16
  EMBEDDINGS_DIR.mkdir(exist_ok=True)
17
  EMBEDDINGS_FILE = EMBEDDINGS_DIR / "embeddings.pkl"
18
 
19
- # ✅ Cargar dataset directamente desde Hugging Face Hub
20
  dataset = load_dataset(
21
  "csv",
22
  data_files="metadata.csv",
23
- split="train",
24
- )
 
25
  print("✅ Primer item:", dataset[0])
26
 
 
27
  dataset = dataset.cast_column("image", HfImage())
28
 
29
- # 🔄 Preprocesar imagen para Facenet
30
  def preprocess_image(img: Image.Image) -> np.ndarray:
31
  img_rgb = img.convert("RGB")
32
  img_resized = img_rgb.resize((160, 160), Image.Resampling.LANCZOS)
@@ -35,11 +34,11 @@ def preprocess_image(img: Image.Image) -> np.ndarray:
35
  # 📦 Construir base de datos de embeddings
36
  def build_database():
37
  if EMBEDDINGS_FILE.exists():
38
- print("📂 Cargando embeddings desde el archivo...")
39
- with open(EMBEDDINGS_FILE, 'rb') as f:
40
  return pickle.load(f)
41
 
42
- print("🔄 Calculando embeddings (esto puede tomar unos minutos)...")
43
  database = []
44
  batch_size = 10
45
 
@@ -47,15 +46,10 @@ def build_database():
47
  batch = dataset[i:i + batch_size]
48
  print(f"📦 Procesando lote {i // batch_size + 1}/{(len(dataset) + batch_size - 1) // batch_size}")
49
 
50
- for j, item in enumerate(batch):
51
  try:
52
- if not isinstance(item, dict) or "image" not in item:
53
- print(f"⚠️ Saltando item {i+j} - estructura inválida: {item}")
54
- continue
55
-
56
- img = item["image"]
57
  if not isinstance(img, Image.Image):
58
- print(f"⚠️ Saltando item {i+j} - no es imagen: {type(img)}")
59
  continue
60
 
61
  img_processed = preprocess_image(img)
@@ -65,20 +59,20 @@ def build_database():
65
  enforce_detection=False
66
  )[0]["embedding"]
67
 
68
- database.append((f"image_{i+j}", img, embedding))
69
- print(f"✅ Procesada imagen {i+j+1}/{len(dataset)}")
70
 
71
  del img_processed
72
  gc.collect()
73
 
74
  except Exception as e:
75
- print(f"❌ Error al procesar imagen {i+j}: {str(e)}")
76
  continue
77
 
78
- # Guardar después de cada lote
79
  if database:
80
- print("💾 Guardando progreso...")
81
- with open(EMBEDDINGS_FILE, 'wb') as f:
82
  pickle.dump(database, f)
83
 
84
  gc.collect()
@@ -97,8 +91,8 @@ def find_similar_faces(uploaded_image: Image.Image):
97
  del img_processed
98
  gc.collect()
99
  except Exception as e:
100
- print(f"Error al procesar imagen de consulta: {str(e)}")
101
- return [], "⚠ No se detectó un rostro válido en la imagen."
102
 
103
  similarities = []
104
  for name, db_img, embedding in database:
@@ -110,18 +104,18 @@ def find_similar_faces(uploaded_image: Image.Image):
110
  top_matches = similarities[:5]
111
 
112
  gallery_items = []
113
- text_summary = ""
114
  for sim, name, img in top_matches:
115
  caption = f"{name} - Similitud: {sim:.2f}"
116
  gallery_items.append((img, caption))
117
- text_summary += caption + "\n"
118
 
119
- return gallery_items, text_summary
120
 
121
- # ⚙️ Iniciar la aplicación
122
  print("🚀 Iniciando aplicación...")
123
  database = build_database()
124
- print(f"✅ Base de datos cargada con {len(database)} imágenes")
125
 
126
  # 🎛️ Interfaz Gradio
127
  demo = gr.Interface(
@@ -129,10 +123,10 @@ demo = gr.Interface(
129
  inputs=gr.Image(label="📤 Sube una imagen", type="pil"),
130
  outputs=[
131
  gr.Gallery(label="📸 Rostros más similares"),
132
- gr.Textbox(label="🧠 Similitud", lines=6)
133
  ],
134
  title="🔍 Buscador de Rostros con DeepFace",
135
- description="Sube una imagen y se comparará contra los rostros del dataset alojado en Hugging Face (`Segizu/facial-recognition`)."
136
  )
137
 
138
  demo.launch()
 
8
  from pathlib import Path
9
  import gc
10
 
11
+ # 📁 Directorio para almacenar embeddings
 
 
 
12
  EMBEDDINGS_DIR = Path("embeddings")
13
  EMBEDDINGS_DIR.mkdir(exist_ok=True)
14
  EMBEDDINGS_FILE = EMBEDDINGS_DIR / "embeddings.pkl"
15
 
16
+ # ✅ Cargar dataset desde metadata.csv (con URLs absolutas)
17
  dataset = load_dataset(
18
  "csv",
19
  data_files="metadata.csv",
20
+ split="train"
21
+ )
22
+
23
  print("✅ Primer item:", dataset[0])
24
 
25
+ # 🖼️ Convertir columna a imágenes usando HfImage (PIL)
26
  dataset = dataset.cast_column("image", HfImage())
27
 
28
+ # 🔄 Preprocesar imagen para DeepFace
29
  def preprocess_image(img: Image.Image) -> np.ndarray:
30
  img_rgb = img.convert("RGB")
31
  img_resized = img_rgb.resize((160, 160), Image.Resampling.LANCZOS)
 
34
  # 📦 Construir base de datos de embeddings
35
  def build_database():
36
  if EMBEDDINGS_FILE.exists():
37
+ print("📂 Cargando embeddings desde archivo...")
38
+ with open(EMBEDDINGS_FILE, "rb") as f:
39
  return pickle.load(f)
40
 
41
+ print("🔄 Calculando embeddings...")
42
  database = []
43
  batch_size = 10
44
 
 
46
  batch = dataset[i:i + batch_size]
47
  print(f"📦 Procesando lote {i // batch_size + 1}/{(len(dataset) + batch_size - 1) // batch_size}")
48
 
49
+ for j, img in enumerate(batch):
50
  try:
 
 
 
 
 
51
  if not isinstance(img, Image.Image):
52
+ print(f"⚠️ Saltando item {i + j} - no es imagen: {type(img)}")
53
  continue
54
 
55
  img_processed = preprocess_image(img)
 
59
  enforce_detection=False
60
  )[0]["embedding"]
61
 
62
+ database.append((f"image_{i + j}", img, embedding))
63
+ print(f"✅ Procesada imagen {i + j + 1}/{len(dataset)}")
64
 
65
  del img_processed
66
  gc.collect()
67
 
68
  except Exception as e:
69
+ print(f"❌ Error al procesar imagen {i + j}: {str(e)}")
70
  continue
71
 
72
+ # Guardar después de cada batch
73
  if database:
74
+ print("💾 Guardando embeddings...")
75
+ with open(EMBEDDINGS_FILE, "wb") as f:
76
  pickle.dump(database, f)
77
 
78
  gc.collect()
 
91
  del img_processed
92
  gc.collect()
93
  except Exception as e:
94
+ print(f"Error al procesar imagen de entrada: {str(e)}")
95
+ return [], "⚠ No se detectó un rostro válido."
96
 
97
  similarities = []
98
  for name, db_img, embedding in database:
 
104
  top_matches = similarities[:5]
105
 
106
  gallery_items = []
107
+ summary = ""
108
  for sim, name, img in top_matches:
109
  caption = f"{name} - Similitud: {sim:.2f}"
110
  gallery_items.append((img, caption))
111
+ summary += caption + "\n"
112
 
113
+ return gallery_items, summary
114
 
115
+ # 🚀 Inicializar app
116
  print("🚀 Iniciando aplicación...")
117
  database = build_database()
118
+ print(f"✅ Base cargada con {len(database)} imágenes.")
119
 
120
  # 🎛️ Interfaz Gradio
121
  demo = gr.Interface(
 
123
  inputs=gr.Image(label="📤 Sube una imagen", type="pil"),
124
  outputs=[
125
  gr.Gallery(label="📸 Rostros más similares"),
126
+ gr.Textbox(label="🧠 Resumen de similitud", lines=6)
127
  ],
128
  title="🔍 Buscador de Rostros con DeepFace",
129
+ description="Sube una imagen y se comparará contra los rostros del dataset `Segizu/facial-recognition`."
130
  )
131
 
132
  demo.launch()