Delete app.py
Browse files
app.py
DELETED
|
@@ -1,1340 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import pandas as pd
|
| 3 |
-
import numpy as np
|
| 4 |
-
from sentence_transformers import SentenceTransformer
|
| 5 |
-
from sklearn.neighbors import NearestNeighbors
|
| 6 |
-
from sklearn.decomposition import TruncatedSVD, NMF
|
| 7 |
-
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
|
| 8 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 9 |
-
from sklearn.cluster import KMeans
|
| 10 |
-
from sklearn.preprocessing import StandardScaler
|
| 11 |
-
from scipy.sparse import csr_matrix
|
| 12 |
-
from scipy.spatial.distance import pdist, squareform
|
| 13 |
-
import gradio as gr
|
| 14 |
-
import json
|
| 15 |
-
import re
|
| 16 |
-
from collections import defaultdict, Counter
|
| 17 |
-
import csv
|
| 18 |
-
import time
|
| 19 |
-
from datetime import datetime
|
| 20 |
-
import warnings
|
| 21 |
-
warnings.filterwarnings('ignore')
|
| 22 |
-
|
| 23 |
-
# Importar huggingface_hub para descargar archivos
|
| 24 |
-
from huggingface_hub import hf_hub_download
|
| 25 |
-
|
| 26 |
-
# ==================== CARGA DE DATOS DESDE HUGGING FACE ====================
|
| 27 |
-
|
| 28 |
-
def download_file_from_hf(filename, repo_id="aegarciaherrera/Sistema_Recomendador_Archivos"):
|
| 29 |
-
"""
|
| 30 |
-
Descarga un archivo específico desde el repositorio de Hugging Face
|
| 31 |
-
"""
|
| 32 |
-
try:
|
| 33 |
-
file_path = hf_hub_download(
|
| 34 |
-
repo_id=repo_id,
|
| 35 |
-
filename=filename,
|
| 36 |
-
repo_type="dataset"
|
| 37 |
-
)
|
| 38 |
-
print(f"✓ Archivo {filename} descargado exitosamente")
|
| 39 |
-
return file_path
|
| 40 |
-
except Exception as e:
|
| 41 |
-
print(f"✗ Error descargando {filename}: {str(e)}")
|
| 42 |
-
return None
|
| 43 |
-
|
| 44 |
-
# Descargar archivos principales
|
| 45 |
-
print("Descargando archivos desde Hugging Face...")
|
| 46 |
-
productos_path = download_file_from_hf("productos.csv")
|
| 47 |
-
mapping_path = download_file_from_hf("embedding_index_mapping.csv")
|
| 48 |
-
|
| 49 |
-
# Cargar datos principales
|
| 50 |
-
if productos_path and mapping_path:
|
| 51 |
-
df_productos = pd.read_csv(productos_path)
|
| 52 |
-
df_productos = df_productos.reset_index(drop=True)
|
| 53 |
-
df_mapping = pd.read_csv(mapping_path)
|
| 54 |
-
print(f"✓ Productos cargados: {len(df_productos):,} registros")
|
| 55 |
-
print(f"✓ Mapping cargado: {len(df_mapping):,} registros")
|
| 56 |
-
else:
|
| 57 |
-
raise FileNotFoundError("No se pudieron descargar los archivos principales")
|
| 58 |
-
|
| 59 |
-
# Cargar ratings (adaptable a ambos formatos)
|
| 60 |
-
try:
|
| 61 |
-
# Intentar cargar ratings agregados (V2)
|
| 62 |
-
ratings_agg_path = download_file_from_hf("ratings_aggregated.csv")
|
| 63 |
-
ratings_det_path = download_file_from_hf("ratings_detailed.csv")
|
| 64 |
-
|
| 65 |
-
if ratings_agg_path and ratings_det_path:
|
| 66 |
-
df_ratings_aggregated = pd.read_csv(ratings_agg_path)
|
| 67 |
-
df_ratings_detailed = pd.read_csv(ratings_det_path)
|
| 68 |
-
ratings_dict = df_ratings_aggregated.set_index('parent_asin')['average_rating'].to_dict()
|
| 69 |
-
print(f"✓ Ratings V2 cargados: {len(ratings_dict):,} productos con ratings")
|
| 70 |
-
HAS_DETAILED_RATINGS = True
|
| 71 |
-
else:
|
| 72 |
-
raise FileNotFoundError("Archivos V2 no encontrados")
|
| 73 |
-
|
| 74 |
-
except Exception as e:
|
| 75 |
-
print(f"No se pudieron cargar ratings V2: {str(e)}")
|
| 76 |
-
try:
|
| 77 |
-
# Fallback a ratings V1
|
| 78 |
-
ratings_path = download_file_from_hf("ratings.csv")
|
| 79 |
-
if ratings_path:
|
| 80 |
-
df_ratings = pd.read_csv(ratings_path)
|
| 81 |
-
ratings_dict = df_ratings.set_index('parent_asin')['rating'].to_dict()
|
| 82 |
-
df_ratings_detailed = df_ratings # Para compatibilidad
|
| 83 |
-
print(f"✓ Ratings V1 cargados: {len(ratings_dict):,} productos con ratings")
|
| 84 |
-
HAS_DETAILED_RATINGS = False
|
| 85 |
-
else:
|
| 86 |
-
raise FileNotFoundError("No se pudo cargar ratings V1")
|
| 87 |
-
except Exception as e2:
|
| 88 |
-
print(f"✗ Error cargando ratings: {str(e2)}")
|
| 89 |
-
ratings_dict = {}
|
| 90 |
-
df_ratings_detailed = pd.DataFrame()
|
| 91 |
-
HAS_DETAILED_RATINGS = False
|
| 92 |
-
|
| 93 |
-
print("=" * 50)
|
| 94 |
-
print("RESUMEN DE CARGA:")
|
| 95 |
-
print(f"- Productos: {len(df_productos):,} registros")
|
| 96 |
-
print(f"- Ratings: {len(ratings_dict):,} productos")
|
| 97 |
-
print(f"- Ratings detallados: {'Sí' if HAS_DETAILED_RATINGS else 'No'}")
|
| 98 |
-
print("=" * 50)
|
| 99 |
-
|
| 100 |
-
# ==================== PREPARACIÓN DE DATOS (SIN MERGE) ====================
|
| 101 |
-
# CRÍTICO: No hacer merge para preservar embeddings precargados
|
| 102 |
-
df_similars = df_productos[df_productos["parent_asin"].isin(df_mapping["parent_asin"])].reset_index(drop=True)
|
| 103 |
-
|
| 104 |
-
# Asegurarte de que el orden coincida
|
| 105 |
-
df_similars = df_similars.merge(df_mapping, on="parent_asin").sort_values("index").reset_index(drop=True)
|
| 106 |
-
|
| 107 |
-
# CRÍTICO: Resetear índices ANTES de cualquier operación
|
| 108 |
-
df_similars["description"] = df_similars["description"].fillna("").astype(str)
|
| 109 |
-
df_similars = df_similars.reset_index(drop=True)
|
| 110 |
-
|
| 111 |
-
print(f"Total de productos en df_similars: {len(df_similars):,}")
|
| 112 |
-
print(f"Productos únicos: {df_similars['parent_asin'].nunique():,}")
|
| 113 |
-
|
| 114 |
-
# ==================== CARGA DE EMBEDDINGS ====================
|
| 115 |
-
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 116 |
-
|
| 117 |
-
try:
|
| 118 |
-
description_embeddings = np.load("embeddings.npy")
|
| 119 |
-
descriptions = np.load("descriptions.npy", allow_pickle=True)
|
| 120 |
-
print(f"Embeddings precalculados cargados: {description_embeddings.shape}")
|
| 121 |
-
|
| 122 |
-
# VERIFICACIÓN CRÍTICA: Asegurar consistencia
|
| 123 |
-
if len(description_embeddings) != len(df_similars):
|
| 124 |
-
print(f"WARNING: Mismatch detectado!")
|
| 125 |
-
print(f" Embeddings: {len(description_embeddings)}")
|
| 126 |
-
print(f" df_similars: {len(df_similars)}")
|
| 127 |
-
print(" Recomiendo regenerar embeddings con el nuevo df_similars")
|
| 128 |
-
else:
|
| 129 |
-
print("Consistencia verificada: embeddings y df_similars coinciden")
|
| 130 |
-
|
| 131 |
-
except FileNotFoundError:
|
| 132 |
-
print("Embeddings no encontrados. Generando embeddings básicos...")
|
| 133 |
-
description_embeddings = model.encode(df_similars["description"].tolist())
|
| 134 |
-
descriptions = df_similars["description"].values
|
| 135 |
-
|
| 136 |
-
# ==================== SISTEMA DE MÉTRICAS Y EVALUACIÓN ====================
|
| 137 |
-
class RecommendationMetrics:
|
| 138 |
-
"""Sistema de métricas para evaluar y comparar diferentes enfoques de recomendación"""
|
| 139 |
-
|
| 140 |
-
def __init__(self):
|
| 141 |
-
self.metrics_history = defaultdict(list)
|
| 142 |
-
self.execution_times = defaultdict(list)
|
| 143 |
-
|
| 144 |
-
def calculate_diversity(self, recommendations_asins):
|
| 145 |
-
"""Calcula la diversidad de las recomendaciones basada en categorías"""
|
| 146 |
-
if not recommendations_asins:
|
| 147 |
-
return 0.0
|
| 148 |
-
|
| 149 |
-
categories = []
|
| 150 |
-
for asin in recommendations_asins:
|
| 151 |
-
product_row = df_similars[df_similars['parent_asin'] == asin]
|
| 152 |
-
if len(product_row) > 0:
|
| 153 |
-
category = product_row.iloc[0].get('main_category', 'Unknown')
|
| 154 |
-
categories.append(category)
|
| 155 |
-
|
| 156 |
-
if not categories:
|
| 157 |
-
return 0.0
|
| 158 |
-
|
| 159 |
-
unique_categories = len(set(categories))
|
| 160 |
-
total_items = len(categories)
|
| 161 |
-
return unique_categories / total_items
|
| 162 |
-
|
| 163 |
-
def calculate_novelty(self, recommendations_asins):
|
| 164 |
-
"""Calcula la novedad basada en popularidad (rating y frecuencia)"""
|
| 165 |
-
if not recommendations_asins:
|
| 166 |
-
return 0.0
|
| 167 |
-
|
| 168 |
-
novelty_scores = []
|
| 169 |
-
for asin in recommendations_asins:
|
| 170 |
-
rating = ratings_dict.get(asin, 0.0)
|
| 171 |
-
# Mayor rating = menor novedad (productos populares)
|
| 172 |
-
novelty_score = max(0, 5.0 - rating) / 5.0
|
| 173 |
-
novelty_scores.append(novelty_score)
|
| 174 |
-
|
| 175 |
-
return np.mean(novelty_scores) if novelty_scores else 0.0
|
| 176 |
-
|
| 177 |
-
def calculate_coverage(self, recommendations_asins, total_available_items):
|
| 178 |
-
"""Calcula el coverage como porcentaje de items únicos recomendados"""
|
| 179 |
-
unique_recommendations = len(set(recommendations_asins))
|
| 180 |
-
return unique_recommendations / min(total_available_items, 100) # Normalizar
|
| 181 |
-
|
| 182 |
-
def calculate_precision_at_k(self, recommendations_asins, relevant_items, k=5):
|
| 183 |
-
"""Calcula precision@k"""
|
| 184 |
-
if not recommendations_asins or not relevant_items:
|
| 185 |
-
return 0.0
|
| 186 |
-
|
| 187 |
-
top_k = recommendations_asins[:k]
|
| 188 |
-
relevant_in_top_k = len(set(top_k) & set(relevant_items))
|
| 189 |
-
return relevant_in_top_k / min(k, len(top_k))
|
| 190 |
-
|
| 191 |
-
def evaluate_recommendations(self, method_name, recommendations_asins, execution_time,
|
| 192 |
-
relevant_items=None, total_available=1000):
|
| 193 |
-
"""Evalúa un conjunto de recomendaciones con múltiples métricas"""
|
| 194 |
-
metrics = {
|
| 195 |
-
'method': method_name,
|
| 196 |
-
'timestamp': datetime.now(),
|
| 197 |
-
'execution_time': execution_time,
|
| 198 |
-
'num_recommendations': len(recommendations_asins),
|
| 199 |
-
'diversity': self.calculate_diversity(recommendations_asins),
|
| 200 |
-
'novelty': self.calculate_novelty(recommendations_asins),
|
| 201 |
-
'coverage': self.calculate_coverage(recommendations_asins, total_available)
|
| 202 |
-
}
|
| 203 |
-
|
| 204 |
-
if relevant_items:
|
| 205 |
-
metrics['precision_at_5'] = self.calculate_precision_at_k(recommendations_asins, relevant_items, 5)
|
| 206 |
-
|
| 207 |
-
# Almacenar métricas
|
| 208 |
-
for key, value in metrics.items():
|
| 209 |
-
if key not in ['method', 'timestamp']:
|
| 210 |
-
self.metrics_history[f"{method_name}_{key}"].append(value)
|
| 211 |
-
|
| 212 |
-
return metrics
|
| 213 |
-
|
| 214 |
-
def get_comparison_report(self):
|
| 215 |
-
"""Genera un reporte comparativo de todos los métodos evaluados"""
|
| 216 |
-
if not self.metrics_history:
|
| 217 |
-
return "No hay métricas disponibles"
|
| 218 |
-
|
| 219 |
-
report = "# 📊 REPORTE COMPARATIVO DE MÉTODOS\n\n"
|
| 220 |
-
|
| 221 |
-
# Agrupar métricas por tipo
|
| 222 |
-
methods = set()
|
| 223 |
-
for key in self.metrics_history.keys():
|
| 224 |
-
method = key.split('_')[0] + '_' + key.split('_')[1]
|
| 225 |
-
methods.add(method)
|
| 226 |
-
|
| 227 |
-
for method in sorted(methods):
|
| 228 |
-
report += f"## {method.replace('_', ' ').title()}\n"
|
| 229 |
-
|
| 230 |
-
# Buscar métricas de este método
|
| 231 |
-
method_metrics = {}
|
| 232 |
-
for key, values in self.metrics_history.items():
|
| 233 |
-
if key.startswith(method):
|
| 234 |
-
metric_name = '_'.join(key.split('_')[2:])
|
| 235 |
-
if values:
|
| 236 |
-
method_metrics[metric_name] = {
|
| 237 |
-
'mean': np.mean(values),
|
| 238 |
-
'std': np.std(values),
|
| 239 |
-
'count': len(values)
|
| 240 |
-
}
|
| 241 |
-
|
| 242 |
-
for metric, stats in method_metrics.items():
|
| 243 |
-
report += f"- **{metric.replace('_', ' ').title()}**: {stats['mean']:.4f} ± {stats['std']:.4f} (n={stats['count']})\n"
|
| 244 |
-
|
| 245 |
-
report += "\n"
|
| 246 |
-
|
| 247 |
-
return report
|
| 248 |
-
|
| 249 |
-
# Instancia global de métricas
|
| 250 |
-
metrics_evaluator = RecommendationMetrics()
|
| 251 |
-
|
| 252 |
-
# ==================== FUNCIONALIDAD 1: BÚSQUEDA POR DESCRIPCIÓN (3 MÉTODOS) ====================
|
| 253 |
-
|
| 254 |
-
class DescriptionSearcher:
|
| 255 |
-
"""Sistema de búsqueda por descripción con múltiples enfoques"""
|
| 256 |
-
|
| 257 |
-
def __init__(self, df_products, embeddings, model):
|
| 258 |
-
self.df_products = df_products
|
| 259 |
-
self.embeddings = embeddings
|
| 260 |
-
self.model = model
|
| 261 |
-
self.setup_methods()
|
| 262 |
-
|
| 263 |
-
def setup_methods(self):
|
| 264 |
-
"""Configura los diferentes métodos de búsqueda"""
|
| 265 |
-
# Método 1: KNN con embeddings (original)
|
| 266 |
-
self.knn = NearestNeighbors(n_neighbors=50, metric="cosine")
|
| 267 |
-
self.knn.fit(self.embeddings)
|
| 268 |
-
|
| 269 |
-
# Método 2: TF-IDF + Cosine Similarity
|
| 270 |
-
descriptions_text = self.df_products["description"].fillna("").tolist()
|
| 271 |
-
self.tfidf_vectorizer = TfidfVectorizer(
|
| 272 |
-
max_features=5000,
|
| 273 |
-
stop_words='english',
|
| 274 |
-
ngram_range=(1, 2),
|
| 275 |
-
min_df=2
|
| 276 |
-
)
|
| 277 |
-
self.tfidf_matrix = self.tfidf_vectorizer.fit_transform(descriptions_text)
|
| 278 |
-
|
| 279 |
-
# Método 3: Clustering + Embedding similarity
|
| 280 |
-
self.n_clusters = min(100, len(self.df_products) // 10)
|
| 281 |
-
self.kmeans = KMeans(n_clusters=self.n_clusters, random_state=42, n_init=10)
|
| 282 |
-
self.cluster_labels = self.kmeans.fit_predict(self.embeddings)
|
| 283 |
-
|
| 284 |
-
def search_method_1_knn(self, query, n_results=5):
|
| 285 |
-
"""Método 1: KNN con embeddings (original mejorado)"""
|
| 286 |
-
start_time = time.time()
|
| 287 |
-
|
| 288 |
-
query_embedding = self.model.encode([query])
|
| 289 |
-
distances, indices = self.knn.kneighbors(query_embedding, n_neighbors=min(50, len(self.df_products)))
|
| 290 |
-
|
| 291 |
-
results = []
|
| 292 |
-
seen_asins = set()
|
| 293 |
-
|
| 294 |
-
for i, idx in enumerate(indices[0]):
|
| 295 |
-
if len(results) >= n_results:
|
| 296 |
-
break
|
| 297 |
-
|
| 298 |
-
if idx >= len(self.df_products):
|
| 299 |
-
continue
|
| 300 |
-
|
| 301 |
-
row = self.df_products.iloc[idx]
|
| 302 |
-
asin = row.get("parent_asin", "N/A")
|
| 303 |
-
|
| 304 |
-
if asin in seen_asins:
|
| 305 |
-
continue
|
| 306 |
-
seen_asins.add(asin)
|
| 307 |
-
|
| 308 |
-
similarity_score = 1 - distances[0][i] # Convertir distancia a similitud
|
| 309 |
-
results.append({
|
| 310 |
-
'asin': asin,
|
| 311 |
-
'similarity_score': similarity_score,
|
| 312 |
-
'method': 'KNN_Embeddings'
|
| 313 |
-
})
|
| 314 |
-
|
| 315 |
-
execution_time = time.time() - start_time
|
| 316 |
-
|
| 317 |
-
# Evaluar con métricas
|
| 318 |
-
result_asins = [r['asin'] for r in results]
|
| 319 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 320 |
-
'search_knn', result_asins, execution_time
|
| 321 |
-
)
|
| 322 |
-
|
| 323 |
-
return results, metrics
|
| 324 |
-
|
| 325 |
-
def search_method_2_tfidf(self, query, n_results=5):
|
| 326 |
-
"""Método 2: TF-IDF + Cosine Similarity"""
|
| 327 |
-
start_time = time.time()
|
| 328 |
-
|
| 329 |
-
query_tfidf = self.tfidf_vectorizer.transform([query])
|
| 330 |
-
similarities = cosine_similarity(query_tfidf, self.tfidf_matrix).flatten()
|
| 331 |
-
|
| 332 |
-
# Obtener top resultados
|
| 333 |
-
top_indices = np.argsort(similarities)[::-1]
|
| 334 |
-
|
| 335 |
-
results = []
|
| 336 |
-
seen_asins = set()
|
| 337 |
-
|
| 338 |
-
for idx in top_indices:
|
| 339 |
-
if len(results) >= n_results:
|
| 340 |
-
break
|
| 341 |
-
|
| 342 |
-
if similarities[idx] < 0.01: # Umbral mínimo de similitud
|
| 343 |
-
continue
|
| 344 |
-
|
| 345 |
-
row = self.df_products.iloc[idx]
|
| 346 |
-
asin = row.get("parent_asin", "N/A")
|
| 347 |
-
|
| 348 |
-
if asin in seen_asins:
|
| 349 |
-
continue
|
| 350 |
-
seen_asins.add(asin)
|
| 351 |
-
|
| 352 |
-
results.append({
|
| 353 |
-
'asin': asin,
|
| 354 |
-
'similarity_score': similarities[idx],
|
| 355 |
-
'method': 'TF_IDF'
|
| 356 |
-
})
|
| 357 |
-
|
| 358 |
-
execution_time = time.time() - start_time
|
| 359 |
-
|
| 360 |
-
# Evaluar con métricas
|
| 361 |
-
result_asins = [r['asin'] for r in results]
|
| 362 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 363 |
-
'search_tfidf', result_asins, execution_time
|
| 364 |
-
)
|
| 365 |
-
|
| 366 |
-
return results, metrics
|
| 367 |
-
|
| 368 |
-
def search_method_3_cluster(self, query, n_results=5):
|
| 369 |
-
"""Método 3: Clustering + Embedding similarity"""
|
| 370 |
-
start_time = time.time()
|
| 371 |
-
|
| 372 |
-
query_embedding = self.model.encode([query])
|
| 373 |
-
|
| 374 |
-
# Encontrar cluster más similar
|
| 375 |
-
query_cluster = self.kmeans.predict(query_embedding)[0]
|
| 376 |
-
|
| 377 |
-
# Filtrar productos del mismo cluster
|
| 378 |
-
cluster_mask = self.cluster_labels == query_cluster
|
| 379 |
-
cluster_indices = np.where(cluster_mask)[0]
|
| 380 |
-
|
| 381 |
-
if len(cluster_indices) == 0:
|
| 382 |
-
execution_time = time.time() - start_time
|
| 383 |
-
return [], {'method': 'Cluster_Search', 'execution_time': execution_time}
|
| 384 |
-
|
| 385 |
-
# Calcular similitudes dentro del cluster
|
| 386 |
-
cluster_embeddings = self.embeddings[cluster_indices]
|
| 387 |
-
similarities = cosine_similarity(query_embedding, cluster_embeddings).flatten()
|
| 388 |
-
|
| 389 |
-
# Ordenar por similitud
|
| 390 |
-
sorted_cluster_indices = cluster_indices[np.argsort(similarities)[::-1]]
|
| 391 |
-
|
| 392 |
-
results = []
|
| 393 |
-
seen_asins = set()
|
| 394 |
-
|
| 395 |
-
for idx in sorted_cluster_indices:
|
| 396 |
-
if len(results) >= n_results:
|
| 397 |
-
break
|
| 398 |
-
|
| 399 |
-
row = self.df_products.iloc[idx]
|
| 400 |
-
asin = row.get("parent_asin", "N/A")
|
| 401 |
-
|
| 402 |
-
if asin in seen_asins:
|
| 403 |
-
continue
|
| 404 |
-
seen_asins.add(asin)
|
| 405 |
-
|
| 406 |
-
similarity_idx = np.where(cluster_indices == idx)[0][0]
|
| 407 |
-
similarity_score = similarities[similarity_idx]
|
| 408 |
-
|
| 409 |
-
results.append({
|
| 410 |
-
'asin': asin,
|
| 411 |
-
'similarity_score': similarity_score,
|
| 412 |
-
'method': 'Cluster_Search'
|
| 413 |
-
})
|
| 414 |
-
|
| 415 |
-
execution_time = time.time() - start_time
|
| 416 |
-
|
| 417 |
-
# Evaluar con métricas
|
| 418 |
-
result_asins = [r['asin'] for r in results]
|
| 419 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 420 |
-
'search_cluster', result_asins, execution_time
|
| 421 |
-
)
|
| 422 |
-
|
| 423 |
-
return results, metrics
|
| 424 |
-
|
| 425 |
-
# ==================== FUNCIONALIDAD 2: RECOMENDACIÓN COLABORATIVA (3 MÉTODOS) ====================
|
| 426 |
-
|
| 427 |
-
class CollaborativeRecommender:
|
| 428 |
-
"""Sistema de recomendación colaborativa con múltiples enfoques"""
|
| 429 |
-
|
| 430 |
-
def __init__(self, ratings_df, min_ratings_per_user=5, min_ratings_per_item=5):
|
| 431 |
-
self.ratings_df = ratings_df.copy()
|
| 432 |
-
self.min_ratings_per_user = min_ratings_per_user
|
| 433 |
-
self.min_ratings_per_item = min_ratings_per_item
|
| 434 |
-
self.user_item_matrix = None
|
| 435 |
-
self.item_similarity_matrix = None
|
| 436 |
-
self.svd_model = None
|
| 437 |
-
self.nmf_model = None
|
| 438 |
-
self.user_encoder = {}
|
| 439 |
-
self.item_encoder = {}
|
| 440 |
-
self.user_decoder = {}
|
| 441 |
-
self.item_decoder = {}
|
| 442 |
-
|
| 443 |
-
self._prepare_data()
|
| 444 |
-
self._build_matrices()
|
| 445 |
-
|
| 446 |
-
def _prepare_data(self):
|
| 447 |
-
"""Prepara los datos filtrando usuarios e items con pocas interacciones"""
|
| 448 |
-
print("Preparando datos para filtrado colaborativo...")
|
| 449 |
-
|
| 450 |
-
# Filtrar usuarios con al menos min_ratings_per_user ratings
|
| 451 |
-
user_counts = self.ratings_df['user_id'].value_counts()
|
| 452 |
-
valid_users = user_counts[user_counts >= self.min_ratings_per_user].index
|
| 453 |
-
|
| 454 |
-
# Filtrar items con al menos min_ratings_per_item ratings
|
| 455 |
-
item_counts = self.ratings_df['parent_asin'].value_counts()
|
| 456 |
-
valid_items = item_counts[item_counts >= self.min_ratings_per_item].index
|
| 457 |
-
|
| 458 |
-
# Aplicar filtros
|
| 459 |
-
self.ratings_df = self.ratings_df[
|
| 460 |
-
(self.ratings_df['user_id'].isin(valid_users)) &
|
| 461 |
-
(self.ratings_df['parent_asin'].isin(valid_items))
|
| 462 |
-
]
|
| 463 |
-
|
| 464 |
-
print(f"Datos filtrados: {len(self.ratings_df):,} ratings, "
|
| 465 |
-
f"{self.ratings_df['user_id'].nunique():,} usuarios, "
|
| 466 |
-
f"{self.ratings_df['parent_asin'].nunique():,} productos")
|
| 467 |
-
|
| 468 |
-
# Crear encoders
|
| 469 |
-
unique_users = self.ratings_df['user_id'].unique()
|
| 470 |
-
unique_items = self.ratings_df['parent_asin'].unique()
|
| 471 |
-
|
| 472 |
-
self.user_encoder = {user: idx for idx, user in enumerate(unique_users)}
|
| 473 |
-
self.item_encoder = {item: idx for idx, item in enumerate(unique_items)}
|
| 474 |
-
self.user_decoder = {idx: user for user, idx in self.user_encoder.items()}
|
| 475 |
-
self.item_decoder = {idx: item for item, idx in self.item_encoder.items()}
|
| 476 |
-
|
| 477 |
-
def _build_matrices(self):
|
| 478 |
-
"""Construye las matrices necesarias para la recomendación"""
|
| 479 |
-
print("Construyendo matrices de interacción...")
|
| 480 |
-
|
| 481 |
-
n_users = len(self.user_encoder)
|
| 482 |
-
n_items = len(self.item_encoder)
|
| 483 |
-
|
| 484 |
-
# Mapear a índices numéricos
|
| 485 |
-
user_indices = self.ratings_df['user_id'].map(self.user_encoder)
|
| 486 |
-
item_indices = self.ratings_df['parent_asin'].map(self.item_encoder)
|
| 487 |
-
ratings = self.ratings_df['rating'].values
|
| 488 |
-
|
| 489 |
-
# Crear matriz sparse
|
| 490 |
-
self.user_item_matrix = csr_matrix(
|
| 491 |
-
(ratings, (user_indices, item_indices)),
|
| 492 |
-
shape=(n_users, n_items)
|
| 493 |
-
)
|
| 494 |
-
|
| 495 |
-
# Método 1: SVD para similitud entre items
|
| 496 |
-
print("Calculando similitudes SVD...")
|
| 497 |
-
self.svd_model = TruncatedSVD(
|
| 498 |
-
n_components=min(50, min(n_users, n_items)-1),
|
| 499 |
-
random_state=42
|
| 500 |
-
)
|
| 501 |
-
item_features_svd = self.svd_model.fit_transform(self.user_item_matrix.T)
|
| 502 |
-
self.item_similarity_matrix = cosine_similarity(item_features_svd)
|
| 503 |
-
|
| 504 |
-
# Método 2: NMF para factorización
|
| 505 |
-
print("Calculando factorización NMF...")
|
| 506 |
-
self.nmf_model = NMF(
|
| 507 |
-
n_components=min(30, min(n_users, n_items)-1),
|
| 508 |
-
random_state=42,
|
| 509 |
-
max_iter=200
|
| 510 |
-
)
|
| 511 |
-
self.user_features_nmf = self.nmf_model.fit_transform(self.user_item_matrix)
|
| 512 |
-
self.item_features_nmf = self.nmf_model.components_.T
|
| 513 |
-
|
| 514 |
-
# Método 3: Item-based cosine similarity directo
|
| 515 |
-
print("Calculando similitud directa...")
|
| 516 |
-
self.item_similarity_direct = cosine_similarity(self.user_item_matrix.T)
|
| 517 |
-
|
| 518 |
-
print("Matrices construidas exitosamente")
|
| 519 |
-
|
| 520 |
-
def recommend_method_1_svd(self, target_item, n_recommendations=4):
|
| 521 |
-
"""Método 1: Recomendaciones basadas en SVD"""
|
| 522 |
-
start_time = time.time()
|
| 523 |
-
|
| 524 |
-
if target_item not in self.item_encoder:
|
| 525 |
-
return [], {'method': 'SVD_Collaborative', 'execution_time': 0}
|
| 526 |
-
|
| 527 |
-
target_idx = self.item_encoder[target_item]
|
| 528 |
-
similarities = self.item_similarity_matrix[target_idx]
|
| 529 |
-
|
| 530 |
-
# Obtener items más similares (excluyendo el item objetivo)
|
| 531 |
-
similar_indices = np.argsort(similarities)[::-1][1:n_recommendations+1]
|
| 532 |
-
|
| 533 |
-
recommendations = []
|
| 534 |
-
for idx in similar_indices:
|
| 535 |
-
item_id = self.item_decoder[idx]
|
| 536 |
-
similarity_score = similarities[idx]
|
| 537 |
-
recommendations.append({
|
| 538 |
-
'asin': item_id,
|
| 539 |
-
'similarity_score': similarity_score,
|
| 540 |
-
'method': 'SVD_Collaborative'
|
| 541 |
-
})
|
| 542 |
-
|
| 543 |
-
execution_time = time.time() - start_time
|
| 544 |
-
|
| 545 |
-
# Evaluar con métricas
|
| 546 |
-
result_asins = [r['asin'] for r in recommendations]
|
| 547 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 548 |
-
'collab_svd', result_asins, execution_time
|
| 549 |
-
)
|
| 550 |
-
|
| 551 |
-
return recommendations, metrics
|
| 552 |
-
|
| 553 |
-
def recommend_method_2_nmf(self, target_item, n_recommendations=4):
|
| 554 |
-
"""Método 2: Recomendaciones basadas en NMF"""
|
| 555 |
-
start_time = time.time()
|
| 556 |
-
|
| 557 |
-
if target_item not in self.item_encoder:
|
| 558 |
-
return [], {'method': 'NMF_Collaborative', 'execution_time': 0}
|
| 559 |
-
|
| 560 |
-
target_idx = self.item_encoder[target_item]
|
| 561 |
-
target_features = self.item_features_nmf[target_idx]
|
| 562 |
-
|
| 563 |
-
# Calcular similitudes con todos los items
|
| 564 |
-
similarities = cosine_similarity([target_features], self.item_features_nmf).flatten()
|
| 565 |
-
|
| 566 |
-
# Obtener items más similares (excluyendo el item objetivo)
|
| 567 |
-
similar_indices = np.argsort(similarities)[::-1][1:n_recommendations+1]
|
| 568 |
-
|
| 569 |
-
recommendations = []
|
| 570 |
-
for idx in similar_indices:
|
| 571 |
-
item_id = self.item_decoder[idx]
|
| 572 |
-
similarity_score = similarities[idx]
|
| 573 |
-
recommendations.append({
|
| 574 |
-
'asin': item_id,
|
| 575 |
-
'similarity_score': similarity_score,
|
| 576 |
-
'method': 'NMF_Collaborative'
|
| 577 |
-
})
|
| 578 |
-
|
| 579 |
-
execution_time = time.time() - start_time
|
| 580 |
-
|
| 581 |
-
# Evaluar con métricas
|
| 582 |
-
result_asins = [r['asin'] for r in recommendations]
|
| 583 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 584 |
-
'collab_nmf', result_asins, execution_time
|
| 585 |
-
)
|
| 586 |
-
|
| 587 |
-
return recommendations, metrics
|
| 588 |
-
|
| 589 |
-
def recommend_method_3_direct(self, target_item, n_recommendations=4):
|
| 590 |
-
"""Método 3: Similitud directa item-to-item"""
|
| 591 |
-
start_time = time.time()
|
| 592 |
-
|
| 593 |
-
if target_item not in self.item_encoder:
|
| 594 |
-
return [], {'method': 'Direct_Collaborative', 'execution_time': 0}
|
| 595 |
-
|
| 596 |
-
target_idx = self.item_encoder[target_item]
|
| 597 |
-
similarities = self.item_similarity_direct[target_idx]
|
| 598 |
-
|
| 599 |
-
# Obtener items más similares (excluyendo el item objetivo)
|
| 600 |
-
similar_indices = np.argsort(similarities)[::-1][1:n_recommendations+1]
|
| 601 |
-
|
| 602 |
-
recommendations = []
|
| 603 |
-
for idx in similar_indices:
|
| 604 |
-
item_id = self.item_decoder[idx]
|
| 605 |
-
similarity_score = similarities[idx]
|
| 606 |
-
recommendations.append({
|
| 607 |
-
'asin': item_id,
|
| 608 |
-
'similarity_score': similarity_score,
|
| 609 |
-
'method': 'Direct_Collaborative'
|
| 610 |
-
})
|
| 611 |
-
|
| 612 |
-
execution_time = time.time() - start_time
|
| 613 |
-
|
| 614 |
-
# Evaluar con métricas
|
| 615 |
-
result_asins = [r['asin'] for r in recommendations]
|
| 616 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 617 |
-
'collab_direct', result_asins, execution_time
|
| 618 |
-
)
|
| 619 |
-
|
| 620 |
-
return recommendations, metrics
|
| 621 |
-
|
| 622 |
-
def get_available_items(self):
|
| 623 |
-
"""Retorna lista de items disponibles para recomendación"""
|
| 624 |
-
return list(self.item_encoder.keys())
|
| 625 |
-
|
| 626 |
-
# ==================== FUNCIONALIDAD 3: RECOMENDACIÓN BASADA EN CLIENTE (3 MÉTODOS) ====================
|
| 627 |
-
|
| 628 |
-
class ClientBasedRecommender:
|
| 629 |
-
"""Sistema de recomendación basado en productos seleccionados por un cliente"""
|
| 630 |
-
|
| 631 |
-
def __init__(self, df_products, embeddings, ratings_dict):
|
| 632 |
-
self.df_products = df_products
|
| 633 |
-
self.embeddings = embeddings
|
| 634 |
-
self.ratings_dict = ratings_dict
|
| 635 |
-
self.setup_methods()
|
| 636 |
-
|
| 637 |
-
def setup_methods(self):
|
| 638 |
-
"""Configura mapeo ASIN -> índice posicional"""
|
| 639 |
-
self.asin_to_idx = {}
|
| 640 |
-
|
| 641 |
-
parent_asins = self.df_products["parent_asin"].values
|
| 642 |
-
|
| 643 |
-
for idx, asin in enumerate(parent_asins):
|
| 644 |
-
if pd.notna(asin):
|
| 645 |
-
self.asin_to_idx[asin] = idx
|
| 646 |
-
|
| 647 |
-
self.prepare_content_features()
|
| 648 |
-
|
| 649 |
-
# Verificación crítica
|
| 650 |
-
assert len(self.embeddings) == len(self.df_products), \
|
| 651 |
-
f"ERROR: embeddings ({len(self.embeddings)}) y dataframe ({len(self.df_products)}) NO coinciden."
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
def prepare_content_features(self):
|
| 655 |
-
"""Prepara características de contenido para recomendaciones"""
|
| 656 |
-
# Extraer categorías principales
|
| 657 |
-
categories = self.df_products.get('main_category', pd.Series(['Unknown'] * len(self.df_products)))
|
| 658 |
-
self.unique_categories = list(set(categories.fillna('Unknown')))
|
| 659 |
-
|
| 660 |
-
# Crear matriz de características categóricas
|
| 661 |
-
self.category_features = np.zeros((len(self.df_products), len(self.unique_categories)))
|
| 662 |
-
for idx, category in enumerate(categories.fillna('Unknown')):
|
| 663 |
-
if category in self.unique_categories:
|
| 664 |
-
cat_idx = self.unique_categories.index(category)
|
| 665 |
-
self.category_features[idx, cat_idx] = 1
|
| 666 |
-
|
| 667 |
-
def recommend_method_1_profile_similarity(self, selected_asins, n_recommendations=5):
|
| 668 |
-
"""Método 1: Perfil de usuario basado en similitud de embeddings"""
|
| 669 |
-
start_time = time.time()
|
| 670 |
-
|
| 671 |
-
if not selected_asins:
|
| 672 |
-
return [], {'method': 'Profile_Similarity', 'execution_time': 0}
|
| 673 |
-
|
| 674 |
-
# Obtener embeddings de productos seleccionados
|
| 675 |
-
selected_embeddings = []
|
| 676 |
-
valid_asins = []
|
| 677 |
-
|
| 678 |
-
for asin in selected_asins:
|
| 679 |
-
if asin in self.asin_to_idx:
|
| 680 |
-
idx = self.asin_to_idx[asin]
|
| 681 |
-
selected_embeddings.append(self.embeddings[idx])
|
| 682 |
-
valid_asins.append(asin)
|
| 683 |
-
|
| 684 |
-
if not selected_embeddings:
|
| 685 |
-
return [], {'method': 'Profile_Similarity', 'execution_time': 0}
|
| 686 |
-
|
| 687 |
-
# Crear perfil de usuario como promedio de embeddings
|
| 688 |
-
user_profile = np.mean(selected_embeddings, axis=0)
|
| 689 |
-
|
| 690 |
-
# Calcular similitudes con todos los productos
|
| 691 |
-
similarities = cosine_similarity([user_profile], self.embeddings).flatten()
|
| 692 |
-
|
| 693 |
-
# Excluir productos ya seleccionados
|
| 694 |
-
excluded_indices = [self.asin_to_idx[asin] for asin in valid_asins if asin in self.asin_to_idx]
|
| 695 |
-
for idx in excluded_indices:
|
| 696 |
-
similarities[idx] = -1
|
| 697 |
-
|
| 698 |
-
# Obtener top recomendaciones
|
| 699 |
-
top_indices = np.argsort(similarities)[::-1][:n_recommendations]
|
| 700 |
-
|
| 701 |
-
recommendations = []
|
| 702 |
-
for idx in top_indices:
|
| 703 |
-
if similarities[idx] <= 0:
|
| 704 |
-
continue
|
| 705 |
-
|
| 706 |
-
row = self.df_products.iloc[idx]
|
| 707 |
-
asin = row.get('parent_asin')
|
| 708 |
-
if asin:
|
| 709 |
-
recommendations.append({
|
| 710 |
-
'asin': asin,
|
| 711 |
-
'similarity_score': similarities[idx],
|
| 712 |
-
'method': 'Profile_Similarity'
|
| 713 |
-
})
|
| 714 |
-
|
| 715 |
-
execution_time = time.time() - start_time
|
| 716 |
-
|
| 717 |
-
# Evaluar con métricas
|
| 718 |
-
result_asins = [r['asin'] for r in recommendations]
|
| 719 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 720 |
-
'client_profile', result_asins, execution_time
|
| 721 |
-
)
|
| 722 |
-
|
| 723 |
-
return recommendations, metrics
|
| 724 |
-
|
| 725 |
-
def recommend_method_2_weighted_categories(self, selected_asins, n_recommendations=5):
|
| 726 |
-
"""Método 2: Recomendación basada en categorías ponderadas"""
|
| 727 |
-
start_time = time.time()
|
| 728 |
-
|
| 729 |
-
if not selected_asins:
|
| 730 |
-
return [], {'method': 'Weighted_Categories', 'execution_time': 0}
|
| 731 |
-
|
| 732 |
-
# Contar categorías en productos seleccionados
|
| 733 |
-
category_weights = defaultdict(float)
|
| 734 |
-
valid_selections = 0
|
| 735 |
-
|
| 736 |
-
for asin in selected_asins:
|
| 737 |
-
if asin in self.asin_to_idx:
|
| 738 |
-
idx = self.asin_to_idx[asin]
|
| 739 |
-
row = self.df_products.iloc[idx]
|
| 740 |
-
category = row.get('main_category', 'Unknown')
|
| 741 |
-
|
| 742 |
-
# Ponderar por rating del producto
|
| 743 |
-
rating = self.ratings_dict.get(asin, 3.0)
|
| 744 |
-
category_weights[category] += rating / 5.0 # Normalizar rating
|
| 745 |
-
valid_selections += 1
|
| 746 |
-
|
| 747 |
-
if not category_weights:
|
| 748 |
-
return [], {'method': 'Weighted_Categories', 'execution_time': 0}
|
| 749 |
-
|
| 750 |
-
# Normalizar pesos
|
| 751 |
-
total_weight = sum(category_weights.values())
|
| 752 |
-
for category in category_weights:
|
| 753 |
-
category_weights[category] /= total_weight
|
| 754 |
-
|
| 755 |
-
# Calcular scores para todos los productos
|
| 756 |
-
product_scores = []
|
| 757 |
-
excluded_asins = set(selected_asins)
|
| 758 |
-
|
| 759 |
-
for idx, row in self.df_products.iterrows():
|
| 760 |
-
asin = row.get('parent_asin')
|
| 761 |
-
if not asin or asin in excluded_asins:
|
| 762 |
-
continue
|
| 763 |
-
|
| 764 |
-
category = row.get('main_category', 'Unknown')
|
| 765 |
-
category_score = category_weights.get(category, 0.0)
|
| 766 |
-
|
| 767 |
-
# Combinar con rating del producto
|
| 768 |
-
product_rating = self.ratings_dict.get(asin, 0.0)
|
| 769 |
-
final_score = category_score * 0.7 + (product_rating / 5.0) * 0.3
|
| 770 |
-
|
| 771 |
-
product_scores.append({
|
| 772 |
-
'asin': asin,
|
| 773 |
-
'similarity_score': final_score,
|
| 774 |
-
'method': 'Weighted_Categories'
|
| 775 |
-
})
|
| 776 |
-
|
| 777 |
-
# Ordenar por score y tomar top N
|
| 778 |
-
product_scores.sort(key=lambda x: x['similarity_score'], reverse=True)
|
| 779 |
-
recommendations = product_scores[:n_recommendations]
|
| 780 |
-
|
| 781 |
-
execution_time = time.time() - start_time
|
| 782 |
-
|
| 783 |
-
# Evaluar con métricas
|
| 784 |
-
result_asins = [r['asin'] for r in recommendations]
|
| 785 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 786 |
-
'client_categories', result_asins, execution_time
|
| 787 |
-
)
|
| 788 |
-
|
| 789 |
-
return recommendations, metrics
|
| 790 |
-
|
| 791 |
-
def recommend_method_3_hybrid_approach(self, selected_asins, n_recommendations=5):
|
| 792 |
-
"""Método 3: Enfoque híbrido combinando embeddings, categorías y ratings"""
|
| 793 |
-
start_time = time.time()
|
| 794 |
-
|
| 795 |
-
if not selected_asins:
|
| 796 |
-
return [], {'method': 'Hybrid_Approach', 'execution_time': 0}
|
| 797 |
-
|
| 798 |
-
# Paso 1: Crear perfil de embeddings
|
| 799 |
-
selected_embeddings = []
|
| 800 |
-
selected_categories = []
|
| 801 |
-
selected_ratings = []
|
| 802 |
-
valid_asins = []
|
| 803 |
-
|
| 804 |
-
for asin in selected_asins:
|
| 805 |
-
if asin in self.asin_to_idx:
|
| 806 |
-
idx = self.asin_to_idx[asin]
|
| 807 |
-
row = self.df_products.iloc[idx]
|
| 808 |
-
|
| 809 |
-
selected_embeddings.append(self.embeddings[idx])
|
| 810 |
-
selected_categories.append(row.get('main_category', 'Unknown'))
|
| 811 |
-
selected_ratings.append(self.ratings_dict.get(asin, 3.0))
|
| 812 |
-
valid_asins.append(asin)
|
| 813 |
-
|
| 814 |
-
if not selected_embeddings:
|
| 815 |
-
return [], {'method': 'Hybrid_Approach', 'execution_time': 0}
|
| 816 |
-
|
| 817 |
-
# Crear perfil promedio ponderado por rating
|
| 818 |
-
weights = np.array(selected_ratings) / 5.0 # Normalizar ratings
|
| 819 |
-
weights = weights / np.sum(weights) # Normalizar pesos
|
| 820 |
-
|
| 821 |
-
user_profile = np.average(selected_embeddings, axis=0, weights=weights)
|
| 822 |
-
|
| 823 |
-
# Paso 2: Calcular preferencias de categoría
|
| 824 |
-
category_preferences = Counter(selected_categories)
|
| 825 |
-
total_selections = len(selected_categories)
|
| 826 |
-
|
| 827 |
-
# Paso 3: Evaluar todos los productos candidatos
|
| 828 |
-
candidate_scores = []
|
| 829 |
-
excluded_asins = set(selected_asins)
|
| 830 |
-
|
| 831 |
-
for idx, row in self.df_products.iterrows():
|
| 832 |
-
asin = row.get('parent_asin')
|
| 833 |
-
if not asin or asin in excluded_asins:
|
| 834 |
-
continue
|
| 835 |
-
|
| 836 |
-
# Score de similitud de embedding
|
| 837 |
-
embedding_similarity = cosine_similarity([user_profile], [self.embeddings[idx]])[0][0]
|
| 838 |
-
|
| 839 |
-
# Score de categoría
|
| 840 |
-
category = row.get('main_category', 'Unknown')
|
| 841 |
-
category_score = category_preferences.get(category, 0) / total_selections
|
| 842 |
-
|
| 843 |
-
# Score de rating
|
| 844 |
-
product_rating = self.ratings_dict.get(asin, 0.0)
|
| 845 |
-
rating_score = product_rating / 5.0
|
| 846 |
-
|
| 847 |
-
# Combinación ponderada
|
| 848 |
-
hybrid_score = (
|
| 849 |
-
embedding_similarity * 0.5 +
|
| 850 |
-
category_score * 0.3 +
|
| 851 |
-
rating_score * 0.2
|
| 852 |
-
)
|
| 853 |
-
|
| 854 |
-
candidate_scores.append({
|
| 855 |
-
'asin': asin,
|
| 856 |
-
'similarity_score': hybrid_score,
|
| 857 |
-
'method': 'Hybrid_Approach',
|
| 858 |
-
'embedding_sim': embedding_similarity,
|
| 859 |
-
'category_score': category_score,
|
| 860 |
-
'rating_score': rating_score
|
| 861 |
-
})
|
| 862 |
-
|
| 863 |
-
# Ordenar y tomar top N
|
| 864 |
-
candidate_scores.sort(key=lambda x: x['similarity_score'], reverse=True)
|
| 865 |
-
recommendations = candidate_scores[:n_recommendations]
|
| 866 |
-
|
| 867 |
-
execution_time = time.time() - start_time
|
| 868 |
-
|
| 869 |
-
# Evaluar con métricas
|
| 870 |
-
result_asins = [r['asin'] for r in recommendations]
|
| 871 |
-
metrics = metrics_evaluator.evaluate_recommendations(
|
| 872 |
-
'client_hybrid', result_asins, execution_time
|
| 873 |
-
)
|
| 874 |
-
|
| 875 |
-
return recommendations, metrics
|
| 876 |
-
|
| 877 |
-
# ==================== FUNCIONES DE UTILIDAD ====================
|
| 878 |
-
def clean_description(description):
|
| 879 |
-
"""Limpia la descripción eliminando corchetes y su contenido"""
|
| 880 |
-
if not description or description == "":
|
| 881 |
-
return "Sin descripción"
|
| 882 |
-
|
| 883 |
-
if description.strip().startswith('[') and description.strip().endswith(']'):
|
| 884 |
-
cleaned = description.strip()[1:-1].strip()
|
| 885 |
-
else:
|
| 886 |
-
cleaned = re.sub(r'\[.*?\]', '', description)
|
| 887 |
-
|
| 888 |
-
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
|
| 889 |
-
return cleaned if cleaned else "Sin descripción"
|
| 890 |
-
|
| 891 |
-
def get_best_image_url(row):
|
| 892 |
-
"""Extrae la mejor URL de imagen disponible"""
|
| 893 |
-
image_columns = ['image_urls_best', 'image_urls_large', 'image_urls_all']
|
| 894 |
-
|
| 895 |
-
for col in image_columns:
|
| 896 |
-
if col in row:
|
| 897 |
-
try:
|
| 898 |
-
images = json.loads(row[col]) if isinstance(row[col], str) else row[col]
|
| 899 |
-
if isinstance(images, list) and images:
|
| 900 |
-
for img_url in images:
|
| 901 |
-
if img_url and isinstance(img_url, str) and img_url.startswith("http"):
|
| 902 |
-
return img_url
|
| 903 |
-
except (json.JSONDecodeError, TypeError, ValueError):
|
| 904 |
-
continue
|
| 905 |
-
|
| 906 |
-
return "https://via.placeholder.com/300x300.png?text=No+Image"
|
| 907 |
-
|
| 908 |
-
def get_product_rating(asin):
|
| 909 |
-
"""Obtiene el rating de un producto desde el diccionario de ratings"""
|
| 910 |
-
return ratings_dict.get(asin, 0.0)
|
| 911 |
-
|
| 912 |
-
def get_product_info_by_asin(asin):
|
| 913 |
-
"""Obtiene información de un producto por su ASIN"""
|
| 914 |
-
product_row = df_similars[df_similars['parent_asin'] == asin]
|
| 915 |
-
if len(product_row) == 0:
|
| 916 |
-
return None
|
| 917 |
-
|
| 918 |
-
row = product_row.iloc[0]
|
| 919 |
-
return {
|
| 920 |
-
'asin': asin,
|
| 921 |
-
'title': row.get('title', 'Sin título'),
|
| 922 |
-
'description': clean_description(row.get('description', '')),
|
| 923 |
-
'rating': get_product_rating(asin),
|
| 924 |
-
'image_url': get_best_image_url(row),
|
| 925 |
-
'category': row.get('main_category', 'Unknown')
|
| 926 |
-
}
|
| 927 |
-
|
| 928 |
-
# ==================== INICIALIZACIÓN DE SISTEMAS ====================
|
| 929 |
-
|
| 930 |
-
# Inicializar sistema de búsqueda por descripción
|
| 931 |
-
description_searcher = DescriptionSearcher(df_similars, description_embeddings, model)
|
| 932 |
-
|
| 933 |
-
# Inicializar sistema colaborativo solo si hay ratings detallados
|
| 934 |
-
if HAS_DETAILED_RATINGS:
|
| 935 |
-
print("Inicializando sistema de recomendación colaborativo...")
|
| 936 |
-
collaborative_recommender = CollaborativeRecommender(df_ratings_detailed)
|
| 937 |
-
else:
|
| 938 |
-
print("Sistema colaborativo no disponible (requiere ratings detallados)")
|
| 939 |
-
collaborative_recommender = None
|
| 940 |
-
|
| 941 |
-
# Inicializar sistema basado en cliente
|
| 942 |
-
client_recommender = ClientBasedRecommender(df_similars, description_embeddings, ratings_dict)
|
| 943 |
-
|
| 944 |
-
# ==================== FUNCIONES DE INTERFAZ MEJORADAS ====================
|
| 945 |
-
|
| 946 |
-
def search_products_enhanced(descripcion_input, method_choice, max_images_per_product=2, target_products=5):
|
| 947 |
-
"""Búsqueda mejorada con selección de método"""
|
| 948 |
-
if not descripcion_input.strip():
|
| 949 |
-
return [("https://via.placeholder.com/300.png?text=Vacío", "Por favor escribe algo para buscar...")]
|
| 950 |
-
|
| 951 |
-
# Seleccionar método de búsqueda
|
| 952 |
-
if method_choice == "KNN + Embeddings":
|
| 953 |
-
results, metrics = description_searcher.search_method_1_knn(descripcion_input, target_products)
|
| 954 |
-
elif method_choice == "TF-IDF + Cosine":
|
| 955 |
-
results, metrics = description_searcher.search_method_2_tfidf(descripcion_input, target_products)
|
| 956 |
-
elif method_choice == "Clustering + Embeddings":
|
| 957 |
-
results, metrics = description_searcher.search_method_3_cluster(descripcion_input, target_products)
|
| 958 |
-
else:
|
| 959 |
-
# Comparar todos los métodos
|
| 960 |
-
results_knn, metrics_knn = description_searcher.search_method_1_knn(descripcion_input, 2)
|
| 961 |
-
results_tfidf, metrics_tfidf = description_searcher.search_method_2_tfidf(descripcion_input, 2)
|
| 962 |
-
results_cluster, metrics_cluster = description_searcher.search_method_3_cluster(descripcion_input, 2)
|
| 963 |
-
|
| 964 |
-
# Combinar resultados
|
| 965 |
-
all_results = results_knn + results_tfidf + results_cluster
|
| 966 |
-
results = sorted(all_results, key=lambda x: x['similarity_score'], reverse=True)[:target_products]
|
| 967 |
-
|
| 968 |
-
metrics = {
|
| 969 |
-
'method': 'All_Methods_Combined',
|
| 970 |
-
'knn_time': metrics_knn.get('execution_time', 0),
|
| 971 |
-
'tfidf_time': metrics_tfidf.get('execution_time', 0),
|
| 972 |
-
'cluster_time': metrics_cluster.get('execution_time', 0)
|
| 973 |
-
}
|
| 974 |
-
|
| 975 |
-
# Convertir resultados a formato de galería
|
| 976 |
-
gallery_results = []
|
| 977 |
-
for result in results:
|
| 978 |
-
product_info = get_product_info_by_asin(result['asin'])
|
| 979 |
-
if product_info:
|
| 980 |
-
texto = f"🔍 Método: {result['method']}\n"
|
| 981 |
-
texto += f"📦 {product_info['title']}\n"
|
| 982 |
-
texto += f"⭐ Rating: {product_info['rating']:.2f}\n"
|
| 983 |
-
texto += f"🎯 Similitud: {result['similarity_score']:.3f}\n"
|
| 984 |
-
texto += f"📂 Categoría: {product_info['category']}\n\n"
|
| 985 |
-
texto += f"📝 {product_info['description'][:200]}{'...' if len(product_info['description']) > 200 else ''}"
|
| 986 |
-
|
| 987 |
-
gallery_results.append((product_info['image_url'], texto))
|
| 988 |
-
|
| 989 |
-
return gallery_results
|
| 990 |
-
|
| 991 |
-
def get_collaborative_recommendations_enhanced(selected_product_asin, method_choice):
|
| 992 |
-
"""Recomendaciones colaborativas mejoradas con selección de método"""
|
| 993 |
-
if not collaborative_recommender:
|
| 994 |
-
return [("https://via.placeholder.com/300.png?text=No+Disponible", "Sistema colaborativo no disponible")]
|
| 995 |
-
|
| 996 |
-
if not selected_product_asin:
|
| 997 |
-
return [("https://via.placeholder.com/300.png?text=Vacío", "Por favor selecciona un producto...")]
|
| 998 |
-
|
| 999 |
-
# Seleccionar método colaborativo
|
| 1000 |
-
if method_choice == "SVD":
|
| 1001 |
-
recommendations, metrics = collaborative_recommender.recommend_method_1_svd(selected_product_asin)
|
| 1002 |
-
elif method_choice == "NMF":
|
| 1003 |
-
recommendations, metrics = collaborative_recommender.recommend_method_2_nmf(selected_product_asin)
|
| 1004 |
-
elif method_choice == "Direct Similarity":
|
| 1005 |
-
recommendations, metrics = collaborative_recommender.recommend_method_3_direct(selected_product_asin)
|
| 1006 |
-
else:
|
| 1007 |
-
# Comparar todos los métodos
|
| 1008 |
-
rec_svd, met_svd = collaborative_recommender.recommend_method_1_svd(selected_product_asin, 2)
|
| 1009 |
-
rec_nmf, met_nmf = collaborative_recommender.recommend_method_2_nmf(selected_product_asin, 2)
|
| 1010 |
-
rec_direct, met_direct = collaborative_recommender.recommend_method_3_direct(selected_product_asin, 1)
|
| 1011 |
-
|
| 1012 |
-
recommendations = rec_svd + rec_nmf + rec_direct
|
| 1013 |
-
metrics = {'method': 'All_Collaborative_Methods'}
|
| 1014 |
-
|
| 1015 |
-
if not recommendations:
|
| 1016 |
-
return [("https://via.placeholder.com/300.png?text=Sin+Recomendaciones", "No se encontraron recomendaciones para este producto.")]
|
| 1017 |
-
|
| 1018 |
-
# Convertir a formato de galería
|
| 1019 |
-
gallery_results = []
|
| 1020 |
-
for rec in recommendations:
|
| 1021 |
-
product_info = get_product_info_by_asin(rec['asin'])
|
| 1022 |
-
if product_info:
|
| 1023 |
-
texto = f"🤝 Método: {rec['method']}\n"
|
| 1024 |
-
texto += f"📦 {product_info['title']}\n"
|
| 1025 |
-
texto += f"⭐ Rating: {product_info['rating']:.2f}\n"
|
| 1026 |
-
texto += f"🎯 Similitud: {rec['similarity_score']:.3f}\n"
|
| 1027 |
-
texto += f"📂 Categoría: {product_info['category']}\n\n"
|
| 1028 |
-
texto += f"📝 {product_info['description'][:200]}{'...' if len(product_info['description']) > 200 else ''}"
|
| 1029 |
-
|
| 1030 |
-
gallery_results.append((product_info['image_url'], texto))
|
| 1031 |
-
|
| 1032 |
-
return gallery_results
|
| 1033 |
-
|
| 1034 |
-
def get_client_recommendations(selected_asins_text, method_choice, n_recommendations=5):
|
| 1035 |
-
"""Recomendaciones basadas en cliente con selección de método"""
|
| 1036 |
-
if not selected_asins_text.strip():
|
| 1037 |
-
return [("https://via.placeholder.com/300.png?text=Vacío", "Por favor ingresa ASINs de productos...")]
|
| 1038 |
-
|
| 1039 |
-
# Parsear ASINs (separados por comas, espacios o nuevas líneas)
|
| 1040 |
-
selected_asins = []
|
| 1041 |
-
for asin in re.split(r'[,\s\n]+', selected_asins_text.strip()):
|
| 1042 |
-
asin = asin.strip()
|
| 1043 |
-
if asin:
|
| 1044 |
-
selected_asins.append(asin)
|
| 1045 |
-
|
| 1046 |
-
if not selected_asins:
|
| 1047 |
-
return [("https://via.placeholder.com/300.png?text=Error", "No se pudieron parsear los ASINs")]
|
| 1048 |
-
|
| 1049 |
-
# Seleccionar método de recomendación basada en cliente
|
| 1050 |
-
if method_choice == "Profile Similarity":
|
| 1051 |
-
recommendations, metrics = client_recommender.recommend_method_1_profile_similarity(selected_asins, n_recommendations)
|
| 1052 |
-
elif method_choice == "Weighted Categories":
|
| 1053 |
-
recommendations, metrics = client_recommender.recommend_method_2_weighted_categories(selected_asins, n_recommendations)
|
| 1054 |
-
elif method_choice == "Hybrid Approach":
|
| 1055 |
-
recommendations, metrics = client_recommender.recommend_method_3_hybrid_approach(selected_asins, n_recommendations)
|
| 1056 |
-
else:
|
| 1057 |
-
# Comparar todos los métodos
|
| 1058 |
-
rec_profile, met_profile = client_recommender.recommend_method_1_profile_similarity(selected_asins, 2)
|
| 1059 |
-
rec_categories, met_categories = client_recommender.recommend_method_2_weighted_categories(selected_asins, 2)
|
| 1060 |
-
rec_hybrid, met_hybrid = client_recommender.recommend_method_3_hybrid_approach(selected_asins, 1)
|
| 1061 |
-
|
| 1062 |
-
recommendations = rec_profile + rec_categories + rec_hybrid
|
| 1063 |
-
metrics = {'method': 'All_Client_Methods'}
|
| 1064 |
-
|
| 1065 |
-
if not recommendations:
|
| 1066 |
-
return [("https://via.placeholder.com/300.png?text=Sin+Recomendaciones", "No se encontraron recomendaciones para los productos seleccionados.")]
|
| 1067 |
-
|
| 1068 |
-
# Convertir a formato de galería
|
| 1069 |
-
gallery_results = []
|
| 1070 |
-
for rec in recommendations:
|
| 1071 |
-
product_info = get_product_info_by_asin(rec['asin'])
|
| 1072 |
-
if product_info:
|
| 1073 |
-
texto = f"👤 Método: {rec['method']}\n"
|
| 1074 |
-
texto += f"📦 {product_info['title']}\n"
|
| 1075 |
-
texto += f"⭐ Rating: {product_info['rating']:.2f}\n"
|
| 1076 |
-
texto += f"🎯 Score: {rec['similarity_score']:.3f}\n"
|
| 1077 |
-
texto += f"📂 Categoría: {product_info['category']}\n\n"
|
| 1078 |
-
|
| 1079 |
-
# Información adicional para método híbrido
|
| 1080 |
-
if 'embedding_sim' in rec:
|
| 1081 |
-
texto += f"🔗 Sim. Embedding: {rec['embedding_sim']:.3f}\n"
|
| 1082 |
-
texto += f"📂 Score Categoría: {rec['category_score']:.3f}\n"
|
| 1083 |
-
texto += f"⭐ Score Rating: {rec['rating_score']:.3f}\n\n"
|
| 1084 |
-
|
| 1085 |
-
texto += f"📝 {product_info['description'][:150]}{'...' if len(product_info['description']) > 150 else ''}"
|
| 1086 |
-
|
| 1087 |
-
gallery_results.append((product_info['image_url'], texto))
|
| 1088 |
-
|
| 1089 |
-
return gallery_results
|
| 1090 |
-
|
| 1091 |
-
def get_product_options():
|
| 1092 |
-
"""Obtiene lista de productos disponibles para el dropdown"""
|
| 1093 |
-
if not collaborative_recommender:
|
| 1094 |
-
return [("Sistema no disponible", "")]
|
| 1095 |
-
|
| 1096 |
-
available_asins = collaborative_recommender.get_available_items()
|
| 1097 |
-
options = []
|
| 1098 |
-
|
| 1099 |
-
for asin in available_asins[:100]: # Limitar para performance
|
| 1100 |
-
product_info = get_product_info_by_asin(asin)
|
| 1101 |
-
if product_info and product_info['rating'] > 0:
|
| 1102 |
-
label = f"{product_info['title'][:50]}... (Rating: {product_info['rating']:.1f})"
|
| 1103 |
-
options.append((label, asin))
|
| 1104 |
-
|
| 1105 |
-
return options
|
| 1106 |
-
|
| 1107 |
-
def get_metrics_report():
|
| 1108 |
-
"""Genera reporte de métricas para mostrar en la interfaz"""
|
| 1109 |
-
return metrics_evaluator.get_comparison_report()
|
| 1110 |
-
|
| 1111 |
-
# ==================== INTERFAZ GRADIO MEJORADA ====================
|
| 1112 |
-
def create_enhanced_interface():
|
| 1113 |
-
"""Crea la interfaz mejorada con todas las funcionalidades y métricas"""
|
| 1114 |
-
|
| 1115 |
-
with gr.Blocks(title="🚀 Advanced Product Recommendaation System", theme=gr.themes.Soft()) as demo:
|
| 1116 |
-
gr.Markdown("""
|
| 1117 |
-
# 🚀 Advanced Product Recommendaation System
|
| 1118 |
-
|
| 1119 |
-
**Funcionalidades disponibles:**
|
| 1120 |
-
- 🔍 **Búsqueda por Descripción** (3 métodos: KNN+Embeddings, TF-IDF+Cosine, Clustering+Embeddings)
|
| 1121 |
-
- 🤝 **Recomendación Colaborativa** (3 métodos: SVD, NMF, Direct Similarity)
|
| 1122 |
-
- 👤 **Recomendación Basada en Cliente** (3 métodos: Profile Similarity, Weighted Categories, Hybrid Approach)
|
| 1123 |
-
- 📊 **Métricas y Comparación** en tiempo real
|
| 1124 |
-
""")
|
| 1125 |
-
|
| 1126 |
-
with gr.Tabs():
|
| 1127 |
-
# TAB 1: Búsqueda por descripción mejorada
|
| 1128 |
-
with gr.TabItem("🔍 Búsqueda por Descripción"):
|
| 1129 |
-
gr.Markdown("### Describe el producto que buscas en inglés y selecciona el método de búsqueda")
|
| 1130 |
-
|
| 1131 |
-
with gr.Row():
|
| 1132 |
-
with gr.Column(scale=1):
|
| 1133 |
-
descripcion_input = gr.Textbox(
|
| 1134 |
-
label="Describe your ideal product",
|
| 1135 |
-
placeholder="exp: Handmade shungite bead bracelet, Silver necklace, etc."
|
| 1136 |
-
)
|
| 1137 |
-
search_method = gr.Dropdown(
|
| 1138 |
-
choices=["KNN + Embeddings", "TF-IDF + Cosine", "Clustering + Embeddings", "Comparar Todos"],
|
| 1139 |
-
value="KNN + Embeddings",
|
| 1140 |
-
label="Método de búsqueda"
|
| 1141 |
-
)
|
| 1142 |
-
max_images = gr.Slider(
|
| 1143 |
-
minimum=1, maximum=3, value=2, step=1,
|
| 1144 |
-
label="Máximo de imágenes por producto"
|
| 1145 |
-
)
|
| 1146 |
-
num_products = gr.Slider(
|
| 1147 |
-
minimum=1, maximum=10, value=5, step=1,
|
| 1148 |
-
label="Número de productos a mostrar"
|
| 1149 |
-
)
|
| 1150 |
-
search_btn = gr.Button("🔍 Buscar Productos", variant="primary", size="lg")
|
| 1151 |
-
|
| 1152 |
-
with gr.Column(scale=2):
|
| 1153 |
-
search_gallery = gr.Gallery(
|
| 1154 |
-
label="Productos Encontrados",
|
| 1155 |
-
columns=3,
|
| 1156 |
-
rows=2,
|
| 1157 |
-
height="auto"
|
| 1158 |
-
)
|
| 1159 |
-
|
| 1160 |
-
# TAB 2: Recomendaciones colaborativas mejoradas
|
| 1161 |
-
if collaborative_recommender:
|
| 1162 |
-
with gr.TabItem("🤝 Recomendaciones Colaborativas"):
|
| 1163 |
-
gr.Markdown("### Selecciona un producto base y el método de recomendación colaborativa")
|
| 1164 |
-
|
| 1165 |
-
with gr.Row():
|
| 1166 |
-
with gr.Column(scale=1):
|
| 1167 |
-
product_dropdown = gr.Dropdown(
|
| 1168 |
-
choices=get_product_options(),
|
| 1169 |
-
label="Selecciona un producto base",
|
| 1170 |
-
value=None
|
| 1171 |
-
)
|
| 1172 |
-
collab_method = gr.Dropdown(
|
| 1173 |
-
choices=["SVD", "NMF", "Direct Similarity", "Comparar Todos"],
|
| 1174 |
-
value="SVD",
|
| 1175 |
-
label="Método colaborativo"
|
| 1176 |
-
)
|
| 1177 |
-
recommend_btn = gr.Button("🤝 Obtener Recomendaciones", variant="primary", size="lg")
|
| 1178 |
-
refresh_products_btn = gr.Button("🔄 Actualizar Lista")
|
| 1179 |
-
|
| 1180 |
-
with gr.Column(scale=2):
|
| 1181 |
-
recommendations_gallery = gr.Gallery(
|
| 1182 |
-
label="Recomendaciones Colaborativas",
|
| 1183 |
-
columns=2,
|
| 1184 |
-
rows=2,
|
| 1185 |
-
height="auto"
|
| 1186 |
-
)
|
| 1187 |
-
|
| 1188 |
-
# TAB 3: Recomendaciones basadas en cliente (NUEVA FUNCIONALIDAD)
|
| 1189 |
-
with gr.TabItem("👤 Recomendaciones Basadas en Cliente"):
|
| 1190 |
-
gr.Markdown("""
|
| 1191 |
-
### Ingresa los ASINs de productos que un cliente ha seleccionado
|
| 1192 |
-
**Formato:** Separa los ASINs con comas, espacios o nuevas líneas
|
| 1193 |
-
**Ejemplo 1:** B07NTK7T5P, B0751M85FV, B01HYNE114, B0BKBJT5MM.
|
| 1194 |
-
**Ejemplo 2:** B01BAN3CBE, B0754TWHPT, B079KM6HDM, B097B8WH61.
|
| 1195 |
-
**Ejemplo 3:** B0B8WK62Z3, B01BYCH44W, B0BGNQ3CLH, B084L4PF4M.
|
| 1196 |
-
|
| 1197 |
-
""")
|
| 1198 |
-
|
| 1199 |
-
with gr.Row():
|
| 1200 |
-
with gr.Column(scale=1):
|
| 1201 |
-
client_asins_input = gr.Textbox(
|
| 1202 |
-
label="ASINs de productos seleccionados por el cliente",
|
| 1203 |
-
placeholder="Insert here the product´s ID´s to get other products you might enjoy!",
|
| 1204 |
-
lines=3
|
| 1205 |
-
)
|
| 1206 |
-
client_method = gr.Dropdown(
|
| 1207 |
-
choices=["Profile Similarity", "Weighted Categories", "Hybrid Approach", "Comparar Todos"],
|
| 1208 |
-
value="Hybrid Approach",
|
| 1209 |
-
label="Método de recomendación"
|
| 1210 |
-
)
|
| 1211 |
-
client_num_recs = gr.Slider(
|
| 1212 |
-
minimum=1, maximum=10, value=5, step=1,
|
| 1213 |
-
label="Número de recomendaciones"
|
| 1214 |
-
)
|
| 1215 |
-
client_recommend_btn = gr.Button("👤 Generar Recomendaciones", variant="primary", size="lg")
|
| 1216 |
-
|
| 1217 |
-
with gr.Accordion("ℹ️ Información de Métodos", open=False):
|
| 1218 |
-
gr.Markdown("""
|
| 1219 |
-
**Profile Similarity:** Crea un perfil promedio basado en los embeddings de los productos seleccionados
|
| 1220 |
-
|
| 1221 |
-
**Weighted Categories:** Recomienda basándose en las categorías más frecuentes, ponderadas por rating
|
| 1222 |
-
|
| 1223 |
-
**Hybrid Approach:** Combina embeddings, categorías y ratings con pesos optimizados
|
| 1224 |
-
""")
|
| 1225 |
-
|
| 1226 |
-
with gr.Column(scale=2):
|
| 1227 |
-
client_gallery = gr.Gallery(
|
| 1228 |
-
label="Recomendaciones para el Cliente",
|
| 1229 |
-
columns=3,
|
| 1230 |
-
rows=2,
|
| 1231 |
-
height="auto"
|
| 1232 |
-
)
|
| 1233 |
-
|
| 1234 |
-
# TAB 4: Métricas y comparación
|
| 1235 |
-
with gr.TabItem("📊 Métricas y Comparación"):
|
| 1236 |
-
gr.Markdown("### Análisis de rendimiento y comparación de métodos")
|
| 1237 |
-
|
| 1238 |
-
with gr.Row():
|
| 1239 |
-
with gr.Column():
|
| 1240 |
-
metrics_btn = gr.Button("📊 Actualizar Métricas", variant="secondary")
|
| 1241 |
-
clear_metrics_btn = gr.Button("🗑️ Limpiar Historial")
|
| 1242 |
-
|
| 1243 |
-
metrics_output = gr.Markdown("Ejecuta algunas recomendaciones para ver las métricas...")
|
| 1244 |
-
|
| 1245 |
-
# Estadísticas del sistema
|
| 1246 |
-
with gr.Accordion("📈 Estadísticas del Sistema", open=False):
|
| 1247 |
-
collab_stats = ""
|
| 1248 |
-
if collaborative_recommender:
|
| 1249 |
-
collab_stats = f"""
|
| 1250 |
-
- 🤝 Productos disponibles para recomendación colaborativa: {len(collaborative_recommender.get_available_items()):,}
|
| 1251 |
-
- 🧮 Dimensiones de matriz SVD: {collaborative_recommender.item_similarity_matrix.shape}
|
| 1252 |
-
"""
|
| 1253 |
-
|
| 1254 |
-
stats_text = f"""
|
| 1255 |
-
**Estadísticas del Sistema Completo:**
|
| 1256 |
-
- 📊 Total de productos: {len(df_similars):,}
|
| 1257 |
-
- ⭐ Productos con ratings: {len(ratings_dict):,}
|
| 1258 |
-
- 🔍 Embeddings precalculados: {len(description_embeddings):,}
|
| 1259 |
-
- ✅ Consistencia verificada: {len(description_embeddings) == len(df_similars)}
|
| 1260 |
-
- 🎯 Métodos de búsqueda: 3 implementados
|
| 1261 |
-
- 🤝 Métodos colaborativos: {"3 implementados" if collaborative_recommender else "No disponible"}
|
| 1262 |
-
- 👤 Métodos basados en cliente: 3 implementados
|
| 1263 |
-
{collab_stats}
|
| 1264 |
-
"""
|
| 1265 |
-
gr.Markdown(stats_text)
|
| 1266 |
-
|
| 1267 |
-
# ==================== EVENTOS ====================
|
| 1268 |
-
|
| 1269 |
-
# Búsqueda por descripción
|
| 1270 |
-
search_btn.click(
|
| 1271 |
-
fn=search_products_enhanced,
|
| 1272 |
-
inputs=[descripcion_input, search_method, max_images, num_products],
|
| 1273 |
-
outputs=search_gallery
|
| 1274 |
-
)
|
| 1275 |
-
|
| 1276 |
-
# Recomendaciones colaborativas (solo si está disponible)
|
| 1277 |
-
if collaborative_recommender:
|
| 1278 |
-
recommend_btn.click(
|
| 1279 |
-
fn=get_collaborative_recommendations_enhanced,
|
| 1280 |
-
inputs=[product_dropdown, collab_method],
|
| 1281 |
-
outputs=recommendations_gallery
|
| 1282 |
-
)
|
| 1283 |
-
|
| 1284 |
-
refresh_products_btn.click(
|
| 1285 |
-
fn=lambda: gr.Dropdown(choices=get_product_options()),
|
| 1286 |
-
outputs=product_dropdown
|
| 1287 |
-
)
|
| 1288 |
-
|
| 1289 |
-
# Recomendaciones basadas en cliente
|
| 1290 |
-
client_recommend_btn.click(
|
| 1291 |
-
fn=get_client_recommendations,
|
| 1292 |
-
inputs=[client_asins_input, client_method, client_num_recs],
|
| 1293 |
-
outputs=client_gallery
|
| 1294 |
-
)
|
| 1295 |
-
|
| 1296 |
-
# Métricas
|
| 1297 |
-
metrics_btn.click(
|
| 1298 |
-
fn=get_metrics_report,
|
| 1299 |
-
outputs=metrics_output
|
| 1300 |
-
)
|
| 1301 |
-
|
| 1302 |
-
def clear_metrics():
|
| 1303 |
-
global metrics_evaluator
|
| 1304 |
-
metrics_evaluator = RecommendationMetrics()
|
| 1305 |
-
return "Historial de métricas limpiado."
|
| 1306 |
-
|
| 1307 |
-
clear_metrics_btn.click(
|
| 1308 |
-
fn=clear_metrics,
|
| 1309 |
-
outputs=metrics_output
|
| 1310 |
-
)
|
| 1311 |
-
|
| 1312 |
-
return demo
|
| 1313 |
-
|
| 1314 |
-
# ==================== LANZAMIENTO ====================
|
| 1315 |
-
if __name__ == "__main__":
|
| 1316 |
-
print("🚀 Iniciando sistema avanzado de recomendación...")
|
| 1317 |
-
|
| 1318 |
-
# Verificar configuración
|
| 1319 |
-
print(f"✅ DataFrame: {len(df_similars):,} productos")
|
| 1320 |
-
print(f"✅ Embeddings: {description_embeddings.shape}")
|
| 1321 |
-
print(f"✅ Consistencia: {len(description_embeddings) == len(df_similars)}")
|
| 1322 |
-
print(f"✅ Búsqueda por descripción: 3 métodos disponibles")
|
| 1323 |
-
|
| 1324 |
-
if collaborative_recommender:
|
| 1325 |
-
print(f"✅ Sistema colaborativo: 3 métodos con {len(collaborative_recommender.get_available_items()):,} productos")
|
| 1326 |
-
else:
|
| 1327 |
-
print("⚠️ Sistema colaborativo no disponible")
|
| 1328 |
-
|
| 1329 |
-
print(f"✅ Sistema basado en cliente: 3 métodos disponibles")
|
| 1330 |
-
print(f"✅ Sistema de métricas: Inicializado")
|
| 1331 |
-
|
| 1332 |
-
# Crear y lanzar interfaz
|
| 1333 |
-
demo = create_enhanced_interface()
|
| 1334 |
-
demo.launch(
|
| 1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