Segizu commited on
Commit
fff17ea
·
1 Parent(s): d771ba3
Files changed (1) hide show
  1. app.py +25 -18
app.py CHANGED
@@ -2,45 +2,49 @@ 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
6
 
7
- # Cargar el dataset de Hugging Face
8
- dataset = load_dataset("Segizu/dataset_faces")
 
9
  if "train" in dataset:
10
  dataset = dataset["train"]
11
 
12
- # Cargar embeddings de todas las imágenes del dataset
13
  def build_database():
14
  database = []
15
  for i, item in enumerate(dataset):
16
  try:
17
  img = item["image"]
18
- # Convertir a RGB y np.array
19
  img_rgb = img.convert("RGB")
20
  img_np = np.array(img_rgb)
21
- # Obtener representación (embedding)
22
- representation = DeepFace.represent(img_path=img_np, model_name="Facenet", enforce_detection=False)[0]["embedding"]
23
- database.append((f"image_{i}", img_rgb, representation))
 
 
 
24
  except Exception as e:
25
  print(f"❌ No se pudo procesar imagen {i}: {e}")
26
  return database
27
 
28
- # Inicializamos base de datos de embeddings
29
- database = build_database()
30
-
31
- # Comparar imagen cargada con la base
32
  def find_similar_faces(uploaded_image):
33
  try:
34
  img_np = np.array(uploaded_image.convert("RGB"))
35
- query_representation = DeepFace.represent(img_path=img_np, model_name="Facenet", enforce_detection=False)[0]["embedding"]
 
 
 
 
36
  except:
37
  return [], "⚠ No se detectó un rostro válido en la imagen."
38
 
39
  similarities = []
40
- for name, db_img, rep in database:
41
- distance = np.linalg.norm(np.array(query_representation) - np.array(rep))
42
- similarity = 1 / (1 + distance) # Normalizado
43
- similarities.append((similarity, name, db_img))
44
 
45
  similarities.sort(reverse=True)
46
  top_matches = similarities[:5]
@@ -54,7 +58,10 @@ def find_similar_faces(uploaded_image):
54
 
55
  return gallery_items, text_summary
56
 
57
- # Interfaz Gradio
 
 
 
58
  demo = gr.Interface(
59
  fn=find_similar_faces,
60
  inputs=gr.Image(label="📤 Sube una imagen", type="pil"),
 
2
  from PIL import Image
3
  import gradio as gr
4
  from deepface import DeepFace
5
+ from datasets import load_dataset, DownloadConfig
6
 
7
+ # Cargar el dataset de Hugging Face forzando la descarga limpia
8
+ download_config = DownloadConfig(force_download=True)
9
+ dataset = load_dataset("Segizu/dataset_faces", download_config=download_config)
10
  if "train" in dataset:
11
  dataset = dataset["train"]
12
 
13
+ # 📦 Construir base de datos de embeddings
14
  def build_database():
15
  database = []
16
  for i, item in enumerate(dataset):
17
  try:
18
  img = item["image"]
 
19
  img_rgb = img.convert("RGB")
20
  img_np = np.array(img_rgb)
21
+ embedding = DeepFace.represent(
22
+ img_path=img_np,
23
+ model_name="Facenet",
24
+ enforce_detection=False
25
+ )[0]["embedding"]
26
+ database.append((f"image_{i}", img_rgb, embedding))
27
  except Exception as e:
28
  print(f"❌ No se pudo procesar imagen {i}: {e}")
29
  return database
30
 
31
+ # 🔍 Buscar rostros similares
 
 
 
32
  def find_similar_faces(uploaded_image):
33
  try:
34
  img_np = np.array(uploaded_image.convert("RGB"))
35
+ query_embedding = DeepFace.represent(
36
+ img_path=img_np,
37
+ model_name="Facenet",
38
+ enforce_detection=False
39
+ )[0]["embedding"]
40
  except:
41
  return [], "⚠ No se detectó un rostro válido en la imagen."
42
 
43
  similarities = []
44
+ for name, db_img, embedding in database:
45
+ dist = np.linalg.norm(np.array(query_embedding) - np.array(embedding))
46
+ sim_score = 1 / (1 + dist)
47
+ similarities.append((sim_score, name, db_img))
48
 
49
  similarities.sort(reverse=True)
50
  top_matches = similarities[:5]
 
58
 
59
  return gallery_items, text_summary
60
 
61
+ # ⚙️ Inicializar base
62
+ database = build_database()
63
+
64
+ # 🎛️ Interfaz Gradio
65
  demo = gr.Interface(
66
  fn=find_similar_faces,
67
  inputs=gr.Image(label="📤 Sube una imagen", type="pil"),