Segizu commited on
Commit
016fe76
·
1 Parent(s): 6c43e7e

metadata v12

Browse files
Files changed (1) hide show
  1. app.py +40 -49
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import numpy as np
2
- from PIL import Image, UnidentifiedImageError
3
  import gradio as gr
4
  from deepface import DeepFace
5
  from datasets import load_dataset
@@ -10,25 +10,22 @@ import gc
10
  import requests
11
  from io import BytesIO
12
 
13
- # 📁 Directorio para almacenar embeddings
14
  EMBEDDINGS_DIR = Path("embeddings")
15
  EMBEDDINGS_DIR.mkdir(exist_ok=True)
16
  EMBEDDINGS_FILE = EMBEDDINGS_DIR / "embeddings.pkl"
17
 
18
- # ✅ Cargar dataset desde metadata.csv (con URLs absolutas)
19
  dataset = load_dataset(
20
  "csv",
21
  data_files="metadata.csv",
22
- split="train",
23
- column_names=["image"], # 👈 forzar el nombre de la columna
24
- header=0 # 👈 indicar que la primera fila es encabezado
25
  )
26
- print("Primeros 5 ítems:")
 
27
  for i in range(5):
28
  print(dataset[i])
29
 
30
- print("✅ Primer item:", dataset[0])
31
-
32
  # 🔄 Preprocesar imagen para DeepFace
33
  def preprocess_image(img: Image.Image) -> np.ndarray:
34
  img_rgb = img.convert("RGB")
@@ -50,49 +47,43 @@ def build_database():
50
  batch = dataset[i:i + batch_size]
51
  print(f"📦 Procesando lote {i // batch_size + 1}/{(len(dataset) + batch_size - 1) // batch_size}")
52
 
53
- for j, item in enumerate(batch):
54
- try:
55
- # Validar estructura
56
- if not isinstance(item, dict) or "image" not in item:
57
- print(f"⚠️ Saltando item {i + j} - estructura inválida: {item}")
58
- continue
59
-
60
- image_url = item["image"]
61
 
62
- # Validar tipo y formato
63
- if not isinstance(image_url, str) or not image_url.startswith("http"):
64
- print(f"⚠️ Saltando item {i + j} - URL inválida: {image_url}")
65
- continue
66
-
67
- # Descargar y procesar imagen
68
- response = requests.get(image_url, timeout=10)
69
- response.raise_for_status()
70
- img = Image.open(BytesIO(response.content)).convert("RGB")
71
 
72
- img_processed = preprocess_image(img)
73
- embedding = DeepFace.represent(
74
- img_path=img_processed,
75
- model_name="Facenet",
76
- enforce_detection=False
77
- )[0]["embedding"]
78
 
79
- database.append((f"image_{i + j}", img, embedding))
80
- print(f"✅ Procesada imagen {i + j + 1}/{len(dataset)}")
 
 
 
 
81
 
82
- del img_processed
83
- gc.collect()
84
 
85
- except Exception as e:
86
- print(f"❌ Error al procesar imagen {i + j}: {str(e)}")
87
- continue
88
 
89
- # Guardar después de cada batch
90
- if database:
91
- print("💾 Guardando embeddings...")
92
- with open(EMBEDDINGS_FILE, "wb") as f:
93
- pickle.dump(database, f)
94
 
95
- gc.collect()
 
 
 
 
96
 
97
  return database
98
 
@@ -129,21 +120,21 @@ def find_similar_faces(uploaded_image: Image.Image):
129
 
130
  return gallery_items, summary
131
 
132
- # 🚀 Inicializar app
133
  print("🚀 Iniciando aplicación...")
134
  database = build_database()
135
  print(f"✅ Base cargada con {len(database)} imágenes.")
136
 
137
- # 🎛️ Interfaz Gradio
138
  demo = gr.Interface(
139
  fn=find_similar_faces,
140
  inputs=gr.Image(label="📤 Sube una imagen", type="pil"),
141
  outputs=[
142
  gr.Gallery(label="📸 Rostros más similares"),
143
- gr.Textbox(label="🧠 Resumen de similitud", lines=6)
144
  ],
145
  title="🔍 Buscador de Rostros con DeepFace",
146
- description="Sube una imagen y se comparará contra los rostros del dataset `Segizu/facial-recognition`."
147
  )
148
 
149
  demo.launch()
 
1
  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
 
10
  import requests
11
  from io import BytesIO
12
 
13
+ # 📁 Directorio local para embeddings
14
  EMBEDDINGS_DIR = Path("embeddings")
15
  EMBEDDINGS_DIR.mkdir(exist_ok=True)
16
  EMBEDDINGS_FILE = EMBEDDINGS_DIR / "embeddings.pkl"
17
 
18
+ # ✅ Cargar el dataset remoto desde Hugging Face Datasets con metadata.csv
19
  dataset = load_dataset(
20
  "csv",
21
  data_files="metadata.csv",
22
+ split="train"
 
 
23
  )
24
+
25
+ print("✅ Primeros ítems de validación:")
26
  for i in range(5):
27
  print(dataset[i])
28
 
 
 
29
  # 🔄 Preprocesar imagen para DeepFace
30
  def preprocess_image(img: Image.Image) -> np.ndarray:
31
  img_rgb = img.convert("RGB")
 
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
+ image_url = item["image"]
57
+ if not isinstance(image_url, str) or not image_url.startswith("http") or image_url.strip().lower() == "image":
58
+ print(f"⚠️ Saltando item {i + j} - URL inválida: {image_url}")
59
+ continue
 
 
 
 
 
60
 
61
+ response = requests.get(image_url, timeout=10)
62
+ response.raise_for_status()
63
+ img = Image.open(BytesIO(response.content)).convert("RGB")
 
 
 
64
 
65
+ img_processed = preprocess_image(img)
66
+ embedding = DeepFace.represent(
67
+ img_path=img_processed,
68
+ model_name="Facenet",
69
+ enforce_detection=False
70
+ )[0]["embedding"]
71
 
72
+ database.append((f"image_{i + j}", img, embedding))
73
+ print(f"✅ Procesada imagen {i + j + 1}/{len(dataset)}")
74
 
75
+ del img_processed
76
+ gc.collect()
 
77
 
78
+ except Exception as e:
79
+ print(f"❌ Error al procesar imagen {i + j}: {str(e)}")
80
+ continue
 
 
81
 
82
+ # Guardar al final si hay datos
83
+ if database:
84
+ print("💾 Guardando embeddings finales...")
85
+ with open(EMBEDDINGS_FILE, "wb") as f:
86
+ pickle.dump(database, f)
87
 
88
  return database
89
 
 
120
 
121
  return gallery_items, summary
122
 
123
+ # 🚀 Iniciar aplicación
124
  print("🚀 Iniciando aplicación...")
125
  database = build_database()
126
  print(f"✅ Base cargada con {len(database)} imágenes.")
127
 
128
+ # 🎛️ Gradio UI
129
  demo = gr.Interface(
130
  fn=find_similar_faces,
131
  inputs=gr.Image(label="📤 Sube una imagen", type="pil"),
132
  outputs=[
133
  gr.Gallery(label="📸 Rostros más similares"),
134
+ gr.Textbox(label="🧠 Similitud", lines=6)
135
  ],
136
  title="🔍 Buscador de Rostros con DeepFace",
137
+ description="Sube una imagen y se comparará contra los rostros del dataset `Segizu/facial-recognition` almacenado en Hugging Face Datasets."
138
  )
139
 
140
  demo.launch()