Spaces:
Runtime error
Runtime error
Download frontend/web/utils/image_generator.py from DesarrolloTT/DataSuitePro: direct link, hf CLI and curl.
- Browser
- Download file 24.5 kB
-
https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/frontend/web/utils/image_generator.py
- Command line
-
hf download hf://spaces/DesarrolloTT/DataSuitePro/frontend/web/utils/image_generator.py
-
curl -L -o image_generator.py https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/frontend/web/utils/image_generator.py
24.5 kB
| ############# 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 | |