Spaces:
Runtime error
Runtime error
File size: 24,516 Bytes
68e9069 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | ############# lexica agregado v2
import requests
import random
import time
import hashlib
from typing import Optional, Dict, List
import streamlit as st
from urllib.parse import quote
import os
class ImageGenerator:
"""Generador de URLs de imágenes con ORDEN CORREGIDO: Lexica → Pollinations → Pixabay → Pexels → Placeholder"""
def __init__(self, pexels_api_key: str = None, pixabay_api_key: str = None):
# ✅ CORREGIDO: Sistema robusto para obtener API keys
self.pexels_api_key = self._get_api_key('pexels', pexels_api_key)
self.pixabay_api_key = self._get_api_key('pixabay', pixabay_api_key)
self.cache = {}
self.request_delay = 0.5 # Reducido porque Lexica es más estable
self.request_count = 0
self.fallback_count = 0
print(f"🔧 ImageGenerator CONFIGURADO")
print(f" 🥇 Lexica: ✅ PÚBLICA (sin API key)")
print(f" 🥈 Pollinations: ✅ Siempre disponible")
print(f" 🥉 Pixabay: {'✅ CONFIGURADA' if self._is_pixabay_configured() else '❌ No configurada'}")
print(f" 📸 Pexels: {'✅ CONFIGURADA' if self._is_pexels_configured() else '❌ No configurada'}")
print(f" 🪄 Placeholder: ✅ Siempre disponible")
self.priority_order = ["lexica", "pollinations", "pixabay", "pexels", "placeholder"]
# Sistema de búsqueda HIPER-ESPECÍFICO
self.product_specific_queries = {
# ELECTRÓNICA
'Auriculares Inalámbricos Premium': 'wireless headphones product photography isolated',
'Smartwatch Deportivo Avanzado': 'sports smartwatch fitness tracker wearable',
'Tablet 10 Pulgadas Pro': 'tablet device screen technology',
'Altavoz Bluetooth Potente': 'bluetooth speaker audio sound',
'Cámara Digital 4K Profesional': 'digital camera photography 4k',
'Drone Profesional GPS': 'drone aerial camera flying',
'Consola Videojuegos Next-Gen': 'gaming console video games',
'Smart TV 55" 4K UHD': 'smart tv television screen',
'Laptop Ultradelgada Gaming': 'gaming laptop computer thin',
'Smartphone Flagship': 'smartphone mobile phone',
'Reloj Inteligente Fitness': 'fitness smartwatch health',
'Cámara Deportiva Resistente': 'sports camera action waterproof',
# TECNOLOGÍA
'Monitor Curvo 27" Gaming': 'gaming monitor curved screen',
'Teclado Mecánico RGB Pro': 'mechanical keyboard rgb gaming',
'Ratón Gaming Precision': 'gaming mouse computer precision',
'Disco SSD 1TB NVMe': 'ssd storage computer hardware',
'Router WiFi 6 AX': 'wifi router internet network',
'Impresora Láser Color': 'laser printer office color',
'Webcam 4K Streaming': 'webcam streaming video conference',
'Micrófono Estudio USB': 'microphone studio recording usb',
'Silla Ergonómica Ejecutiva': 'ergonomic chair office executive',
# HOGAR
'Robot Aspirador Inteligente': 'robot vacuum cleaner smart home',
'Batidora Potente Profesional': 'blender kitchen appliance professional',
'Cafetera Automática Premium': 'coffee maker automatic premium',
'Licuadora Profesional': 'blender professional kitchen',
'Tostadora Digital LCD': 'toaster digital kitchen',
'Horno Eléctrico Multifunción': 'electric oven kitchen multi-function',
'Freidora de Aire Digital': 'air fryer digital kitchen',
'Plancha de Vapor Professional': 'steam iron clothing professional',
'Purificador Aire HEPA': 'air purifier hepa filter',
# ROPA
'Camiseta Algodón Orgánico': 'cotton t-shirt organic clothing',
'Jeans Elásticos Premium': 'jeans denim pants stretch',
'Zapatillas Running Tech': 'running shoes athletic sneakers',
'Chaqueta Impermeable Outdoor': 'waterproof jacket outdoor',
'Sudadera con Capucha Algodón': 'hoodie sweatshirt cotton',
'Vestido Elegante Noche': 'elegant dress evening night',
'Falda Plisada Casual': 'pleated skirt casual',
'Chándal Deportivo Performance': 'tracksuit sportswear performance',
'Abrigo Invierno Lana': 'wool coat winter',
# DEPORTES
'Pelota Fútbol Profesional': 'soccer ball football professional',
'Raqueta Tenis Competición': 'tennis racket competition',
'Balón Baloncesto Official': 'basketball official sports',
'Bicicleta Montaña Suspensión': 'mountain bike suspension',
'Pesas Ajustables Hex': 'dumbbells weights hex adjustable',
'Cinta Correr Plegable': 'treadmill running foldable',
'Eliptica Casa Magnetic': 'elliptical machine magnetic home',
'Mancuernas Acero Cromado': 'dumbbells chrome steel',
'Pelota Yoga Anti-Burst': 'yoga ball anti-burst',
# ALIMENTOS
'Aceite Oliva Extra Virgen': 'olive oil extra virgin bottle',
'Miel Natural Pura': 'honey natural jar',
'Café Molido Premium': 'coffee ground premium bag',
'Chocolate Negro 70% Cacao': 'dark chocolate 70% cocoa',
'Mermelada Fresa Artesanal': 'strawberry jam artisanal jar',
'Pasta Integral Orgánica': 'pasta organic whole wheat',
'Salsa Tomate Natural': 'tomato sauce natural jar',
'Galletas Integrales Sin Azúcar': 'cookies whole grain sugar-free',
'Cereal Energético Natural': 'cereal energy natural box',
# BEBIDAS
'Vino Tinto Reserva': 'red wine bottle reserve',
'Cerveza Artesanal IPA': 'craft beer IPA bottle',
'Jugo Naranja Natural': 'orange juice natural bottle',
'Agua Mineral Con Gas': 'sparkling water mineral bottle',
'Refresco Cola Zero': 'cola soda zero can',
'Té Verde Matcha': 'matcha green tea powder',
'Café Molido Expresso': 'espresso coffee ground',
'Batido Proteínas Natural': 'protein shake natural bottle',
'Agua Saborizada Limón': 'lemon flavored water bottle'
}
def _get_api_key(self, service: str, provided_key: str = None) -> str:
"""Sistema robusto para obtener API keys desde múltiples fuentes"""
# 1. Prioridad: clave proporcionada directamente
if provided_key and provided_key != f"TU_API_KEY_{service.upper()}_AQUI":
return provided_key
# 2. Intentar desde session_state de Streamlit
try:
if service == 'pexels' and 'pexels_api_key' in st.session_state:
key = st.session_state.pexels_api_key
if key and key != "TU_API_KEY_PEXELS_AQUI":
return key
elif service == 'pixabay' and 'pixabay_api_key' in st.session_state:
key = st.session_state.pixabay_api_key
if key and key != "TU_API_KEY_PIXABAY_AQUI":
return key
except:
pass
# 3. Intentar desde variables de entorno
env_key = os.getenv(f"{service.upper()}_API_KEY")
if env_key:
return env_key
# 4. Fallback a valor por defecto
return f"TU_API_KEY_{service.upper()}_AQUI"
def _is_pixabay_configured(self):
"""Verificar si Pixabay está configurado correctamente"""
return (self.pixabay_api_key and
self.pixabay_api_key != "TU_API_KEY_PIXABAY_AQUI" and
len(self.pixabay_api_key) > 10)
def _is_pexels_configured(self):
"""Verificar si Pexels está configurado correctamente"""
return (self.pexels_api_key and
self.pexels_api_key != "TU_API_KEY_PEXELS_AQUI" and
len(self.pexels_api_key) > 10)
def get_hyper_specific_query(self, product_name: str, category: str) -> str:
"""Generar query HIPER-ESPECÍFICA basada en el nombre exacto del producto"""
# Primero buscar coincidencia exacta en el mapeo
for product_key, query in self.product_specific_queries.items():
if product_key.lower() in product_name.lower():
print(f"🎯 Query ESPECÍFICA encontrada: '{query}' para '{product_name}'")
return query
# Si no hay coincidencia, extraer palabras clave del nombre
words = product_name.lower().split()
# Filtrar palabras genéricas y marcas
generic_words = {'de', 'con', 'para', 'y', 'o', 'la', 'el', 'los', 'las', 'un', 'una',
'premium', 'profesional', 'avanzado', 'digital', 'inteligente', 'natural'}
brands = {'zara', 'nike', 'adidas', 'samsung', 'sony', 'lg', 'apple', 'bose', 'jbl',
'philips', 'dell', 'hp', 'lenovo', 'logitech', 'bosch', 'black+decker',
'miele', 'rowenta', 'tefal', 'nestlé', 'coca-cola', 'pepsi'}
# Tomar las 3-4 palabras más relevantes
relevant_words = [word for word in words if (word not in generic_words and
word not in brands and
len(word) > 2)]
if len(relevant_words) >= 2:
specific_query = ' '.join(relevant_words[:3])
else:
# Fallback: usar categoría + primera palabra relevante
first_relevant = relevant_words[0] if relevant_words else category.lower()
specific_query = f"{first_relevant} {category.lower()}"
print(f"🔍 Query GENERADA: '{specific_query}' para '{product_name}'")
return specific_query
def get_lexica_image(self, product_name: str, category: str) -> Optional[str]:
"""🥇 PRIORIDAD 1: Lexica.art - API PÚBLICA CORREGIDA"""
try:
search_query = self.get_hyper_specific_query(product_name, category)
cache_key = f"lexica_{hashlib.md5(product_name.encode()).hexdigest()[:10]}"
if cache_key in self.cache:
return self.cache[cache_key]
time.sleep(self.request_delay)
print(f"🔍 Lexica 🥇 BUSCANDO: '{product_name}' -> '{search_query}'")
# ✅ CORREGIDO: Usar la API pública de Lexica correctamente
encoded_query = quote(search_query)
url = f"https://lexica.art/api/v1/search?q={encoded_query}"
response = requests.get(url, timeout=15)
if response.status_code == 200:
data = response.json()
images = data.get("images", [])
if images:
# Seleccionar una imagen aleatoria de las primeras 5
selected_image = random.choice(images[:5])
image_url = selected_image.get("src")
if image_url:
self.cache[cache_key] = image_url
self.request_count += 1
print(f"✅ Lexica 🥇 ENCONTRADO: '{product_name}'")
return image_url
print(f"⚠️ Lexica: Sin resultados para '{search_query}'")
return None
else:
print(f"❌ Lexica API error {response.status_code}")
return None
except requests.exceptions.Timeout:
print("⏰ Lexica timeout")
return None
except requests.exceptions.ConnectionError:
print("🔌 Lexica connection error")
return None
except Exception as e:
print(f"❌ Error Lexica: {str(e)}")
return None
def get_pollinations_image(self, product_name: str, category: str) -> str:
"""🥈 PRIORIDAD 2: Pollinations - Imágenes generadas coherentes"""
try:
# Prompts MEJORADOS y más específicos
prompt_variations = [
f"professional ecommerce product photo of {product_name}, studio lighting, high quality, detailed, 8K, commercial product photography, sharp focus, attractive composition",
f"{product_name} in realistic setting, professional product photography, high detail, commercial use, appealing composition, natural lighting",
f"modern ecommerce product shot of {product_name}, clean background, professional photography, high quality, detailed texture, commercial use",
f"{product_name} product photography, professional studio shot, high detail, commercial quality, attractive lighting, clean composition"
]
prompt = random.choice(prompt_variations)
encoded_prompt = quote(prompt)
seed = int(hashlib.md5(product_name.encode()).hexdigest()[:8], 16) % 10000
image_url = f"https://image.pollinations.ai/prompt/{encoded_prompt}?width=800&height=800&seed={seed}&nofilter=true"
self.request_count += 1
print(f"🤖 Pollinations 🥈 GENERANDO: '{product_name}'")
return image_url
except Exception as e:
print(f"❌ Error Pollinations: {e}")
return self.get_placeholder_image(product_name, category)
def get_pixabay_image(self, product_name: str, category: str) -> Optional[str]:
"""🥉 PRIORIDAD 3: Pixabay - Fotos reales libres"""
if not self._is_pixabay_configured():
print(f"❌ Pixabay: API Key no configurada para '{product_name}'")
return None
search_query = self.get_hyper_specific_query(product_name, category)
cache_key = f"pixabay_{hashlib.md5(product_name.encode()).hexdigest()[:10]}"
if cache_key in self.cache:
return self.cache[cache_key]
try:
url = "https://pixabay.com/api/"
params = {
"key": self.pixabay_api_key,
"q": search_query,
"image_type": "photo",
"orientation": "horizontal",
"per_page": 15,
"safesearch": "true",
"editors_choice": "true",
"category": "objects"
}
self.request_count += 1
time.sleep(0.3)
print(f"🔍 Pixabay 🥉 BUSCANDO: '{product_name}' -> '{search_query}'")
response = requests.get(url, params=params, timeout=15)
if response.status_code == 200:
data = response.json()
hits = data.get("hits", [])
if hits:
# Filtrar imágenes que parezcan productos
product_like_hits = []
for hit in hits:
tags = hit.get('tags', '').lower()
if any(keyword in tags for keyword in ['product', 'object', 'item', 'white background', 'isolated']):
product_like_hits.append(hit)
usable_hits = product_like_hits if product_like_hits else hits
if usable_hits:
selected_hit = random.choice(usable_hits[:5])
image_url = selected_hit["largeImageURL"]
self.cache[cache_key] = image_url
print(f"✅ Pixabay 🥉 ENCONTRADO: '{product_name}'")
return image_url
print(f"⚠️ Pixabay: Sin resultados para '{search_query}'")
return None
else:
print(f"❌ Pixabay API error {response.status_code}")
return None
except Exception as e:
print(f"❌ Error Pixabay: {str(e)}")
return None
def get_pexels_image(self, product_name: str, category: str) -> Optional[str]:
"""📸 PRIORIDAD 4: Pexels - Backup calidad alta"""
if not self._is_pexels_configured():
print(f"❌ Pexels: API Key no configurada para '{product_name}'")
return None
search_query = self.get_hyper_specific_query(product_name, category)
cache_key = f"pexels_{hashlib.md5(product_name.encode()).hexdigest()[:10]}"
if cache_key in self.cache:
return self.cache[cache_key]
try:
url = "https://api.pexels.com/v1/search"
headers = {"Authorization": self.pexels_api_key}
params = {
"query": search_query,
"per_page": 10,
"orientation": "square"
}
self.request_count += 1
time.sleep(0.4)
print(f"🔍 Pexels 📸 BUSCANDO: '{product_name}' -> '{search_query}'")
response = requests.get(url, headers=headers, params=params, timeout=15)
if response.status_code == 200:
data = response.json()
photos = data.get("photos", [])
if photos:
# Filtrar fotos que parezcan productos
product_photos = []
for photo in photos:
alt = photo.get('alt', '').lower()
if any(keyword in alt for keyword in ['product', 'object', 'item']):
product_photos.append(photo)
usable_photos = product_photos if product_photos else photos
if usable_photos:
selected_photo = random.choice(usable_photos[:5])
image_url = selected_photo["src"]["large"]
self.cache[cache_key] = image_url
print(f"✅ Pexels 📸 ENCONTRADO: '{product_name}'")
return image_url
print(f"⚠️ Pexels: Sin resultados para '{search_query}'")
return None
else:
print(f"❌ Pexels API error {response.status_code}")
return None
except Exception as e:
print(f"❌ Error Pexels: {str(e)}")
return None
def get_placeholder_image(self, product_name: str, category: str) -> str:
"""🪄 PRIORIDAD 5: Placeholder - Último recurso"""
category_colors = {
'Electrónica': '2563EB', 'Tecnología': '059669', 'Hogar': 'DC2626',
'Ropa': '7C3AED', 'Deportes': 'EA580C', 'Alimentos': 'D97706',
'Bebidas': '0369A1', 'Comidas Dulces': 'FF6B6B', 'Comidas Saladas': '4ECDC4'
}
color = category_colors.get(category, '4F46E5')
icon = '📱' if 'electrón' in category.lower() else '👕' if 'ropa' in category.lower() else '🍎' if 'aliment' in category.lower() else '🥤' if 'bebida' in category.lower() else '📦'
display_text = f"{icon} {product_name}"
if len(display_text) > 30:
display_text = f"{icon} {category}"
encoded_text = quote(display_text)
self.request_count += 1
return f"https://placehold.co/800x800/{color}/FFFFFF?font=montserrat&text={encoded_text}"
def generate_product_image(self, product_name: str, category: str,
image_source: str = "priority") -> str:
"""Sistema PRINCIPAL con orden corregido"""
print(f"🎨 Generando imagen para: '{product_name}'")
try:
if image_source == "priority":
# 🥇 PRIORIDAD 1: Lexica (API pública)
print(f"🚀 Intentando Lexica 🥇...")
lexica_image = self.get_lexica_image(product_name, category)
if lexica_image:
print(f"✅ ÉXITO Lexica 🥇 para '{product_name}'")
return lexica_image
else:
print(f"🔄 Lexica no encontró imagen")
# 🥈 PRIORIDAD 2: Pollinations (IA coherente)
print(f"🚀 Generando con Pollinations 🥈...")
pollinations_image = self.get_pollinations_image(product_name, category)
if pollinations_image and "pollinations.ai" in pollinations_image:
print(f"✅ ÉXITO Pollinations 🥈 para '{product_name}'")
return pollinations_image
# 🥉 PRIORIDAD 3: Pixabay (fotos reales libres)
if self._is_pixabay_configured():
print(f"🔄 Intentando Pixabay 🥉...")
pixabay_image = self.get_pixabay_image(product_name, category)
if pixabay_image:
print(f"✅ ÉXITO Pixabay 🥉 para '{product_name}'")
return pixabay_image
# 📸 PRIORIDAD 4: Pexels (backup calidad alta)
if self._is_pexels_configured():
print(f"🔄 Intentando Pexels 📸...")
pexels_image = self.get_pexels_image(product_name, category)
if pexels_image:
print(f"✅ ÉXITO Pexels 📸 para '{product_name}'")
return pexels_image
# 🪄 PRIORIDAD 5: Placeholder (último recurso)
print(f"📦 Usando placeholder 🪄 para '{product_name}'")
return self.get_placeholder_image(product_name, category)
else:
# Modo específico para compatibilidad
if image_source.lower() == "lexica":
return self.get_lexica_image(product_name, category) or self.get_pollinations_image(product_name, category)
elif image_source.lower() == "pollinations":
return self.get_pollinations_image(product_name, category)
elif image_source.lower() == "pixabay":
return self.get_pixabay_image(product_name, category) or self.get_pollinations_image(product_name, category)
elif image_source.lower() == "pexels":
return self.get_pexels_image(product_name, category) or self.get_pollinations_image(product_name, category)
else:
return self.get_placeholder_image(product_name, category)
except Exception as e:
print(f"💥 Error crítico: {str(e)}")
return self.get_placeholder_image(product_name, category)
def get_stats(self) -> Dict:
"""Obtener estadísticas"""
return {
"total_requests": self.request_count,
"fallbacks": self.fallback_count,
"cache_size": len(self.cache),
"cached_products": list(self.cache.keys()),
"pixabay_configured": self._is_pixabay_configured(),
"pexels_configured": self._is_pexels_configured(),
"priority_order": self.priority_order
}
# Instancia global
image_generator = ImageGenerator()
def get_image_generator() -> ImageGenerator:
return image_generator
def configure_image_generator(pexels_api_key: str = None, pixabay_api_key: str = None):
global image_generator
image_generator = ImageGenerator(
pexels_api_key=pexels_api_key,
pixabay_api_key=pixabay_api_key
)
print(f"🔧 ImageGenerator CONFIGURADO")
print(f" 🥇 Lexica: ✅ PÚBLICA (sin API key)")
print(f" 🥈 Pollinations: ✅ Siempre disponible")
print(f" 🥉 Pixabay: {'✅ CONFIGURADA' if image_generator._is_pixabay_configured() else '❌ No configurada'}")
print(f" 📸 Pexels: {'✅ CONFIGURADA' if image_generator._is_pexels_configured() else '❌ No configurada'}")
return image_generator
|