""" ================================================================================ CELLCOG INTEGRATION - MULTI-MODAL AI CAPABILITIES ================================================================================ Integração com CellCog para geração de imagens, vídeos, áudio, pesquisa, análise. TIER 1: Primário — CellCog API (se disponível) TIER 2: HuggingFace Inference (rotação de tokens) TIER 3: Google Imagen 3 (Gemini API, free tier) TIER 4: Cloudflare Workers AI (10k req/dia grátis, FLUX melhor qualidade) TIER 5: Stability AI SD3.5 (25 créditos grátis, fallback) TIER 6: Pollinations Flux (completamente grátis, sem key) ================================================================================ """ import os import json import io import base64 import time import requests from typing import Dict, Any, Optional, List from loguru import logger from PIL import Image, ImageDraw, ImageFont import textwrap class CellCogClient: """ Cliente para integração com CellCog. Suporta: Image, Video, Audio, Research, Data Analysis, e mais. """ def __init__(self, api_key: Optional[str] = None): """ Inicializa cliente CellCog. Args: api_key: Chave da API CellCog (obtém de env se não fornecido) """ self.api_key = api_key or os.getenv("CELLCOG_API_KEY") self.base_url = os.getenv("CELLCOG_BASE_URL", "https://api.cellcog.ai/v1") self.available = bool(self.api_key) if self.available: logger.success("✅ CellCog integrado com sucesso") else: logger.warning("⚠️ CellCog não configurado - usando fallbacks") def generate_image( self, prompt: str, model: str = "image", aspect_ratio: str = "1:1", quality: str = "high" ) -> Dict[str, Any]: """ Gera imagem via CellCog Image Cog. Args: prompt: Descrição da imagem model: Tipo de geração (image, anime, photo, 3d, etc.) aspect_ratio: Proporção (1:1, 16:9, 9:16, 4:3, etc.) quality: Qualidade (low, medium, high, ultra) Returns: Dict com imagem gerada ou erro """ if not self.available: logger.warning("⚠️ CellCog não configurado, pulando para Flux...") return {"success": False, "error": "CellCog não disponível"} try: logger.info(f"🖼️ [CellCog] Gerando imagem: '{prompt[:50]}...'") payload = { "prompt": prompt, "model": model, "aspect_ratio": aspect_ratio, "quality": quality, "format": "url" # Retorna URL ao invés de base64 } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/image", json=payload, headers=headers, timeout=60 ) if response.status_code == 200: result = response.json() image_url = result.get("url") if image_url: # Download da imagem para retornar como buffer try: img_response = requests.get(image_url, timeout=30) if img_response.status_code == 200 and len(img_response.content) > 1000: logger.success(f"✅ [CellCog] Imagem gerada e baixada com sucesso") return { "success": True, "image_data": base64.b64encode(img_response.content).decode('utf-8'), "mime_type": "image/png", "model": "cellcog", "prompt": prompt } except Exception as dl_err: logger.warning(f"⚠️ [CellCog] Falha ao baixar imagem: {dl_err}") return {"success": False, "error": f"Falha ao baixar: {str(dl_err)}"} return {"success": False, "error": "URL de imagem não retornada"} else: logger.error(f"❌ [CellCog] Status {response.status_code}: {response.text[:200]}") return {"success": False, "error": f"Status {response.status_code}"} except requests.exceptions.Timeout: logger.error(f"❌ [CellCog] Timeout na requisição") return {"success": False, "error": "Timeout - CellCog lento"} except requests.exceptions.ConnectionError as e: logger.error(f"❌ [CellCog] Erro de conexão: {str(e)[:100]}") return {"success": False, "error": "Erro de conexão - CellCog indisponível"} except Exception as e: logger.error(f"❌ [CellCog Image] Erro: {str(e)[:150]}") return {"success": False, "error": str(e)[:100]} def generate_video( self, prompt: str, duration: int = 10, resolution: str = "1080p" ) -> Dict[str, Any]: """ Gera vídeo via CellCog Video Cog. Args: prompt: Descrição do vídeo duration: Duração em segundos (5-240) resolution: Resolução (720p, 1080p, 4k) Returns: Dict com vídeo gerado ou erro """ if not self.available: return {"success": False, "error": "CellCog não disponível"} try: logger.info(f"🎬 [CellCog] Gerando vídeo: '{prompt[:50]}...' ({duration}s)") payload = { "prompt": prompt, "duration": min(duration, 240), # Máximo 4 minutos "resolution": resolution, "format": "url" } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/video", json=payload, headers=headers, timeout=120 # Videos levam mais tempo ) if response.status_code == 200: result = response.json() logger.success(f"✅ [CellCog] Vídeo gerado com sucesso") return { "success": True, "video_url": result.get("url"), "model": "cellcog", "prompt": prompt, "duration": duration } else: logger.error(f"❌ [CellCog] Status {response.status_code}: {response.text}") return {"success": False, "error": f"Status {response.status_code}"} except Exception as e: logger.error(f"❌ [CellCog Video] Erro: {e}") return {"success": False, "error": str(e)} def generate_audio( self, text: str, voice: str = "default", language: str = "pt-PT" ) -> Dict[str, Any]: """ Gera áudio/TTS via CellCog Audio Cog. Args: text: Texto a converter voice: Voz a usar language: Idioma (pt-PT, pt-BR, en-US, etc.) Returns: Dict com áudio gerado ou erro """ if not self.available: return {"success": False, "error": "CellCog não disponível"} try: logger.info(f"🎙️ [CellCog] Gerando áudio ({language}): '{text[:40]}...'") payload = { "text": text, "voice": voice, "language": language, "format": "mp3" } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/audio", json=payload, headers=headers, timeout=60 ) if response.status_code == 200: result = response.json() logger.success(f"✅ [CellCog] Áudio gerado com sucesso") return { "success": True, "audio_url": result.get("url"), "model": "cellcog", "duration": result.get("duration"), "language": language } else: logger.error(f"❌ [CellCog] Status {response.status_code}") return {"success": False, "error": f"Status {response.status_code}"} except Exception as e: logger.error(f"❌ [CellCog Audio] Erro: {e}") return {"success": False, "error": str(e)} def research( self, query: str, depth: str = "medium" ) -> Dict[str, Any]: """ Realiza pesquisa profunda via CellCog Research Cog. Args: query: Pergunta ou tópico depth: Profundidade (quick, medium, thorough) Returns: Dict com resultados da pesquisa """ if not self.available: return {"success": False, "error": "CellCog não disponível"} try: logger.info(f"🔬 [CellCog] Pesquisando: '{query}'") payload = { "query": query, "depth": depth, "sources": 10, "format": "json" } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/research", json=payload, headers=headers, timeout=90 ) if response.status_code == 200: result = response.json() logger.success(f"✅ [CellCog] Pesquisa concluída") return { "success": True, "findings": result.get("findings"), "sources": result.get("sources", []), "model": "cellcog" } else: logger.error(f"❌ [CellCog] Status {response.status_code}") return {"success": False, "error": f"Status {response.status_code}"} except Exception as e: logger.error(f"❌ [CellCog Research] Erro: {e}") return {"success": False, "error": str(e)} def analyze_data( self, csv_data: str, analysis_type: str = "exploratory" ) -> Dict[str, Any]: """ Analisa dados via CellCog Data Cog. Args: csv_data: Dados em formato CSV analysis_type: Tipo (exploratory, statistical, predictive) Returns: Dict com análise """ if not self.available: return {"success": False, "error": "CellCog não disponível"} try: logger.info(f"📊 [CellCog] Analisando dados ({analysis_type})") payload = { "data": csv_data, "analysis_type": analysis_type, "format": "json" } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/analyze", json=payload, headers=headers, timeout=90 ) if response.status_code == 200: result = response.json() logger.success(f"✅ [CellCog] Análise concluída") return { "success": True, "analysis": result.get("analysis"), "insights": result.get("insights", []), "model": "cellcog" } else: logger.error(f"❌ [CellCog] Status {response.status_code}") return {"success": False, "error": f"Status {response.status_code}"} except Exception as e: logger.error(f"❌ [CellCog Data] Erro: {e}") return {"success": False, "error": str(e)} def think_brainstorm( self, prompt: str, depth: str = "medium" ) -> Dict[str, Any]: """ Raciocínio avançado e brainstorming via CellCog Think Cog. Args: prompt: Pergunta ou problema a resolver depth: Profundidade (quick, medium, thorough) Returns: Dict com ideias e soluções """ if not self.available: return {"success": False, "error": "CellCog não disponível"} try: logger.info(f"💭 [CellCog] Brainstorming: '{prompt[:50]}...'") payload = { "prompt": prompt, "depth": depth, "format": "json" } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/think", json=payload, headers=headers, timeout=90 ) if response.status_code == 200: result = response.json() logger.success(f"✅ [CellCog] Raciocínio concluído") return { "success": True, "ideas": result.get("ideas", []), "reasoning": result.get("reasoning", ""), "solutions": result.get("solutions", []), "model": "cellcog" } else: logger.error(f"❌ [CellCog] Status {response.status_code}") return {"success": False, "error": f"Status {response.status_code}"} except Exception as e: logger.error(f"❌ [CellCog Think] Erro: {e}") return {"success": False, "error": str(e)} def generate_document( self, content: str, doc_type: str = "report", format: str = "pdf" ) -> Dict[str, Any]: """ Gera documentos (PDF/DOCX) via CellCog Docs Cog. Args: content: Conteúdo do documento doc_type: Tipo (report, contract, invoice, resume, letter) format: Formato (pdf, docx) Returns: Dict com documento gerado """ if not self.available: return {"success": False, "error": "CellCog não disponível"} try: logger.info(f"📄 [CellCog] Gerando documento ({doc_type})...") payload = { "content": content, "doc_type": doc_type, "format": format } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/document", json=payload, headers=headers, timeout=120 ) if response.status_code == 200: result = response.json() doc_url = result.get("url") if doc_url: # Download do documento try: doc_response = requests.get(doc_url, timeout=30) if doc_response.status_code == 200: logger.success(f"✅ [CellCog] Documento gerado e baixado") return { "success": True, "buffer": doc_response.content, "mime_type": f"application/{format}" if format == "pdf" else "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "filename": result.get("filename", f"documento.{format}"), "model": "cellcog" } except Exception as dl_err: logger.warning(f"⚠️ [CellCog] Falha ao baixar documento: {dl_err}") return {"success": False, "error": "URL de documento não retornada"} else: logger.error(f"❌ [CellCog] Status {response.status_code}") return {"success": False, "error": f"Status {response.status_code}"} except Exception as e: logger.error(f"❌ [CellCog Document] Erro: {e}") return {"success": False, "error": str(e)} def generate_presentation( self, title: str, content: str, slides: int = 10, style: str = "professional" ) -> Dict[str, Any]: """ Gera apresentações (PPTX) via CellCog Slides Cog. Args: title: Título da apresentação content: Conteúdo/tópicos slides: Número de slides style: Estilo (professional, creative, minimal) Returns: Dict com apresentação gerada """ if not self.available: return {"success": False, "error": "CellCog não disponível"} try: logger.info(f"📊 [CellCog] Gerando apresentação: '{title[:40]}...'") payload = { "title": title, "content": content, "num_slides": slides, "style": style, "format": "pptx" } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/presentation", json=payload, headers=headers, timeout=120 ) if response.status_code == 200: result = response.json() pptx_url = result.get("url") if pptx_url: # Download da apresentação try: pptx_response = requests.get(pptx_url, timeout=30) if pptx_response.status_code == 200: logger.success(f"✅ [CellCog] Apresentação gerada e baixada") return { "success": True, "buffer": pptx_response.content, "mime_type": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "filename": f"{title}.pptx", "num_slides": slides, "model": "cellcog" } except Exception as dl_err: logger.warning(f"⚠️ [CellCog] Falha ao baixar apresentação: {dl_err}") return {"success": False, "error": "URL de apresentação não retornada"} else: logger.error(f"❌ [CellCog] Status {response.status_code}") return {"success": False, "error": f"Status {response.status_code}"} except Exception as e: logger.error(f"❌ [CellCog Presentation] Erro: {e}") return {"success": False, "error": str(e)} @staticmethod def _add_text_to_logo(image_bytes: bytes, brand_name: str, slogan: str = "") -> bytes: """Sobrepoe texto PERFEITO (sem erros de IA) sobre imagem de logo.""" try: img = Image.open(io.BytesIO(image_bytes)).convert("RGBA") w, h = img.size overlay = Image.new("RGBA", img.size, (0, 0, 0, 0)) draw = ImageDraw.Draw(overlay) font_size = max(w // 16, 24) slogan_font_size = max(w // 28, 14) try: font_bold = ImageFont.truetype("arial.ttf", font_size) font_slogan = ImageFont.truetype("arial.ttf", slogan_font_size) except (IOError, OSError): try: font_bold = ImageFont.truetype("DejaVuSans-Bold.ttf", font_size) font_slogan = ImageFont.truetype("DejaVuSans.ttf", slogan_font_size) except (IOError, OSError): font_bold = ImageFont.load_default() font_slogan = font_bold # Nome da marca no topo bb = draw.textbbox((0, 0), brand_name, font=font_bold) tw, th = bb[2] - bb[0], bb[3] - bb[1] tx = (w - tw) // 2 ty = int(h * 0.06) # Sombra para legibilidade for dx, dy in [(2, 2), (-2, -2), (0, 0)]: draw.text((tx + dx, ty + dy), brand_name, font=font_bold, fill=(0, 0, 0, 200) if dx != 0 or dy != 0 else (255, 255, 255, 230)) # Slogan no rodapé if slogan: wrapper = textwrap.TextWrapper(width=w // slogan_font_size - 2) lines = wrapper.wrap(slogan) line_h = slogan_font_size + 6 total_text_h = len(lines) * line_h sy = h - total_text_h - int(h * 0.06) for line in lines: bb = draw.textbbox((0, 0), line, font=font_slogan) lw = bb[2] - bb[0] sx = (w - lw) // 2 for dx, dy in [(1, 1), (-1, -1), (0, 0)]: draw.text((sx + dx, sy + dy), line, font=font_slogan, fill=(0, 0, 0, 200) if dx != 0 or dy != 0 else (255, 255, 255, 230)) sy += line_h img = Image.alpha_composite(img, overlay) buf = io.BytesIO() img.convert("RGB").save(buf, format="JPEG", quality=95) return buf.getvalue() except Exception as e: logger.warning(f"⚠️ [LOGO TEXT] Falha ao adicionar texto: {e}") return image_bytes def generate_brand_identity( self, brand_name: str, description: str, industry: str = "general" ) -> Dict[str, Any]: """ Gera identidade de marca completa via CellCog Brand Cog. Fallback: HF Image Gen → Media Factory (Cloudflare → Stability → Pollinations). O texto é sobreposto por código (PIL) para evitar erros de rendering da IA. """ if self.available: try: logger.info(f"🎨 [CellCog] Gerando branding para '{brand_name}'...") payload = { "brand_name": brand_name, "description": description, "industry": industry } headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } response = requests.post( f"{self.base_url}/brand", json=payload, headers=headers, timeout=30 ) if response.status_code == 200: result = response.json() logger.success(f"✅ [CellCog] Identidade de marca gerada") logo_url = result.get("logo_url") logo_buffer = None if logo_url: try: logo_response = requests.get(logo_url, timeout=30) if logo_response.status_code == 200: logo_buffer = logo_response.content except: pass if logo_buffer: logo_buffer = self._add_text_to_logo(logo_buffer, brand_name, description) return { "type": "media_response", "media_response": { "tipo": "imagem", "buffer": logo_buffer, "caption": f"Logo '{brand_name}' — {description}", "model": "cellcog" } } return { "success": True, "brand_name": brand_name, "colors": result.get("color_palette", []), "guidelines": result.get("guidelines", ""), "model": "cellcog" } else: logger.warning(f"⚠️ [CellCog] Status {response.status_code} — tentando HF fallback") except Exception as e: logger.warning(f"⚠️ [CellCog Brand] Falhou: {e}") # FALLBACK 1: Gera logo via HF Image Gen logger.info(f"🔄 [HF IMAGE] Fallback: gerando logo via HuggingFace...") hf_gen = HuggingFaceImageGen() hf_result = hf_gen.generate( prompt=f"Professional logo for '{brand_name}', {description}, {industry} industry, clean design, minimalist, no text in image", model="photo" ) if hf_result.get("success"): img_b64 = hf_result.get("image_data", "") img_bytes = base64.b64decode(img_b64) if img_b64 else None if img_bytes and len(img_bytes) > 1000: img_bytes = self._add_text_to_logo(img_bytes, brand_name, description) return { "type": "media_response", "media_response": { "tipo": "imagem", "buffer": img_bytes, "caption": f"Logo '{brand_name}' — {description}", "model": "hf_fallback" } } # FALLBACK 2: Media Factory (Cloudflare → Stability → Pollinations) logger.info(f"🔄 [MEDIA FACTORY] Fallback: gerando logo via factory chain...") try: factory = get_media_factory() factory_result = factory.generate_image( prompt=f"Minimalist professional logo for '{brand_name}', {description}, {industry} industry, clean sleek design, NO TEXT in image, high quality 8K", model="flux", aspect_ratio="1:1" ) if factory_result.get("success"): img_b64 = factory_result.get("image_data", "") img_bytes = base64.b64decode(img_b64) if img_b64 else None if img_bytes and len(img_bytes) > 1000: img_bytes = self._add_text_to_logo(img_bytes, brand_name, description) return { "type": "media_response", "media_response": { "tipo": "imagem", "buffer": img_bytes, "caption": f"Logo '{brand_name}' — {description}", "model": factory_result.get("model", "factory_fallback") } } except Exception as e: logger.warning(f"⚠️ [MEDIA FACTORY] Fallback branding falhou: {e}") return {"success": False, "error": f"Todos os providers falharam para branding: {brand_name}"} # ============================================================================ # HuggingFace Inference API - Image Generation (Tier 2) # ============================================================================ class HuggingFaceImageGen: """ Geração de imagens usando HuggingFace Inference API. Suporta FLUX, Stable Diffusion, SD3, etc. """ # FIX 2026-08-28: Usar HF Router (router.huggingface.co) com providers free potentes # Provider: nscale = free tier FLUX.1-schnell, fal-ai = paid, hyperbolic, nebius # ATENÇÃO (2026-10-07): os 5 primeiros são GATED — exigem aceitar a licença # na página do modelo com a MESMA conta do token, senão dão 403 mesmo com # quota. Os 3 últimos são checkpoints comunitários SEM gate: funcionam só # com o token, sem aceitar nada. IMAGE_MODELS = { "flux": "black-forest-labs/FLUX.1-schnell", "flux-dev": "black-forest-labs/FLUX.1-dev", "flux-2-klein": "black-forest-labs/FLUX.2-klein-9B", # BFL klein 9B, mais potente "stable-diffusion": "stabilityai/stable-diffusion-xl-base-1.0", "stable-diffusion-3": "stabilityai/stable-diffusion-3-medium-diffusers", "sd3-turbo": "stabilityai/sd3.5-turbo", "playground": "playground-v2.5", "realistic-vision": "SG161222/Realistic_Vision_V5.1_noVAE", # sem gate "dreamshaper": "Lykon/DreamShaper", # sem gate "openjourney": "prompthero/openjourney", # sem gate } # Provider routing no HF Router PROVIDER_ROUTES = { "black-forest-labs/FLUX.1-schnell": "nscale", # free "black-forest-labs/FLUX.1-dev": "nscale", # free "black-forest-labs/FLUX.2-klein-9B": "nscale", # free "stabilityai/stable-diffusion-xl-base-1.0": "nscale", "stabilityai/stable-diffusion-3-medium-diffusers": "nscale", "stabilityai/sd3.5-turbo": "nscale", "playground-v2.5": "nscale", "SG161222/Realistic_Vision_V5.1_noVAE": "nscale", "Lykon/DreamShaper": "nscale", "prompthero/openjourney": "nscale", } # 402 (sem créditos) é POR MODELO/PROVIDER — guarda-o durante 10 min para não # repetir a chamada paga a cada pedido, sem bloquear os modelos gratuitos. PAYMENT_CACHE_TTL = 600.0 def __init__(self): self._rotation = None self._payment_limited: Dict[str, float] = {} self._load_rotation() def _load_rotation(self): try: from modules.hf_inference_rotation import get_hf_inference_rotation self._rotation = get_hf_inference_rotation() logger.info("🤗 [HF IMAGE] HuggingFace Image Gen inicializado") except Exception as e: logger.warning(f"⚠️ [HF IMAGE] Falha ao carregar rotation: {e}") self._rotation = None def _get_client(self, token_override=None): try: from huggingface_hub import InferenceClient token = token_override if not token and self._rotation: token = self._rotation.get_current_api_token() if not token: token = os.getenv("HF_TOKEN") if not token: logger.warning("⚠️ [HF IMAGE] Nenhum token disponível") return None return InferenceClient(token=token) except Exception as e: logger.error(f"❌ [HF IMAGE] Erro ao criar client: {e}") return None def _get_account_tokens(self) -> list: """[(conta, token)] de TODAS as contas configuradas, incluindo HF_TOKEN do env. Contas já marcadas como limitadas passam para o FIM da lista mas nunca são descartadas: um limite (429/402) é temporário e o token limitado é a última hipótese antes do fallback. Nada é removido de forma preventiva.""" entries = [] seen = set() if self._rotation: for acc_name in self._rotation.account_order: t = os.getenv(self._rotation.accounts.get(acc_name, "")) if t and t not in seen: seen.add(t) entries.append((acc_name, t)) main_token = os.getenv("HF_TOKEN") if main_token and main_token not in seen: entries.append(("hf_main", main_token)) if self._rotation: # estável: preserva a ordem das contas dentro de cada grupo entries.sort(key=lambda e: 1 if self._rotation.is_account_limited(e[0]) else 0) return entries def _get_fallback_tokens(self): return [token for _, token in self._get_account_tokens()] @staticmethod def _classify_error(err: str) -> str: """rate_limit / payment = erro HTTP real de quota (justifica marcar conta). gated / coverage = problema do MODELO (não marca nada, tenta o próximo). transient / other = falha sem quota (não marca nada).""" low = (err or "").lower() if "429" in low or "rate limit" in low or "too many requests" in low: return "rate_limit" if "403" in low and any(k in low for k in ("quota", "rate limit", "credit")): return "rate_limit" if any(k in low for k in ("402", "payment required", "no remaining credits", "remaining credits", "included credits", "insufficient credits", "quota exceeded")): return "payment" if "gated" in low or "license" in low or "licence" in low or "403" in low: return "gated" if any(k in low for k in ("stopiteration", "no provider", "not supported", "repository not found", "not found", " 404", "410 gone")): return "coverage" if any(k in low for k in ("503", "capacity", "overloaded", "timed out", "timeout")): return "transient" return "other" def _is_payment_blocked(self, account: str, model_id: str) -> bool: until = self._payment_limited.get(f"{account}|{model_id}") if until is None: return False if until > time.time(): return True self._payment_limited.pop(f"{account}|{model_id}", None) return False def _mark_payment_blocked(self, account: str, model_id: str): self._payment_limited[f"{account}|{model_id}"] = time.time() + self.PAYMENT_CACHE_TTL def _mark_account_limited(self, account: str, err: str): if not self._rotation: return mark = getattr(self._rotation, "mark_account_limited", None) if mark: mark(account, err) else: self._rotation.handle_rate_limit_error(err) @staticmethod def _is_gated_error(status_code: int, body: str) -> bool: """403 de repo GATED: a conta do token não aceitou a licença do modelo. Quota não resolve — só aceitando em https://huggingface.co/.""" if status_code != 403: return False low = (body or "").lower() return any(k in low for k in ("gated", "license", "licence", "restricted", "access", "forbidden")) def generate(self, prompt: str, aspect_ratio: str = "1:1", model: str = "flux") -> Dict[str, Any]: hf_model = self.IMAGE_MODELS.get(model, self.IMAGE_MODELS.get("flux")) # FIX 2026-10-07: o POST manual p/ router.huggingface.co/{provider}/{model} # com provider "nscale" devolve 400 "Model not supported by provider nscale" # para TODOS os modelos (testado ao vivo com token real, incluindo os modelos # sem gate) — o tier HF falhava sempre e caía no Pollinations mesmo com quota # ativa. Usa o InferenceClient oficial, que resolve sozinho o provider certo. # Ordem: modelo PEDIDO primeiro (só ele devolve hf-FLUX.1-dev se a conta tiver # créditos), depois os gratuitos (FLUX.1-schnell/nscale, SD3-medium) e por fim # os pagos (FLUX.1-dev e SDXL-base só têm fal-ai/replicate → 402 em conta free). # FIX: um 402 num modelo já NÃO aborta a lista nem marca a conta — tenta-se # sempre o resto dos modelos/tokens (antes, dev+402 dava break e o schnell # gratuito nunca era chamado → "cai sempre no Pollinations"). # NOTA: FLUX.2-klein-9B é image-to-image (não serve de texto→imagem) e os # checkpoints SD1.5 (Realistic Vision/DreamShaper/OpenJourney) não têm # provider T2I (StopIteration/404) — por isso ficam fora da lista. base_models = [ self.IMAGE_MODELS["flux"], self.IMAGE_MODELS["stable-diffusion-3"], self.IMAGE_MODELS["flux-dev"], self.IMAGE_MODELS["stable-diffusion"], ] priority_models = [] for m in [hf_model] + base_models: if m and m not in priority_models and "klein" not in m: priority_models.append(m) _ar = {"1:1": (1024, 1024), "16:9": (1024, 576), "9:16": (576, 1024), "4:3": (1024, 768), "3:4": (768, 1024), "3:2": (1024, 683), "2:3": (683, 1024)} width, height = _ar.get(aspect_ratio or "1:1", (1024, 1024)) account_tokens = self._get_account_tokens() if not account_tokens: logger.error("❌ [HF IMAGE] Nenhum token HF configurado (HF_TOKEN / ANN_HF_TOKEN / ...)") return { "success": False, "error": "Nenhum token HF configurado", "quota_exhausted": False, "attempts_exhausted": True, } logger.info(f"🤗 [HF IMAGE] {len(account_tokens)} tokens, {len(priority_models)} modelos via InferenceClient") _last_err = "" attempts = 0 quota_failures = 0 for token_idx, (account, token) in enumerate(account_tokens): if priority_models and all(self._is_payment_blocked(account, m) for m in priority_models): if not _last_err: _last_err = "conta sem créditos (402 recente, em cache)" logger.info(f"⏭️ [HF IMAGE] Conta {account} sem créditos para todos os modelos (402 recente) — a seguir") continue token_attempts = 0 token_quota = 0 for model_id in priority_models: if self._is_payment_blocked(account, model_id): continue attempts += 1 token_attempts += 1 try: logger.info(f"🤗 [HF IMAGE] Gerando com {model_id} (conta {account}, token {token_idx + 1}/{len(account_tokens)})...") from huggingface_hub import InferenceClient client = InferenceClient(token=token, timeout=90) image = client.text_to_image(prompt, model=model_id, width=width, height=height) if image is None: raise RuntimeError("resposta vazia do InferenceClient") buf = io.BytesIO() image.save(buf, format="PNG") raw = buf.getvalue() if len(raw) <= 1000: raise RuntimeError(f"imagem inválida ({len(raw)}B)") logger.success(f"✅ [HF IMAGE] Imagem gerada via {model_id} ({len(raw)}B, {image.size[0]}x{image.size[1]})") return { "success": True, "image_data": base64.b64encode(raw).decode('utf-8'), "mime_type": "image/png", "model": f"hf-{model_id.split('/')[-1]}", "prompt": prompt } except Exception as model_err: err = str(model_err) or type(model_err).__name__ _last_err = f"{model_id}: {err[:150]}" kind = self._classify_error(err) if kind == "gated": logger.warning( f"🔒 [HF IMAGE] {model_id} recusado (403/gated) — a conta do token " f"ainda não aceitou a licença. Aceita em https://huggingface.co/{model_id} " f"(a quota não resolve). A seguir: outros modelos da lista." ) continue if kind == "coverage": logger.warning(f"⚠️ [HF IMAGE] {model_id} sem cobertura T2I — a seguir p/ próximo modelo") continue if kind == "transient": logger.warning(f"⚠️ [HF IMAGE] {model_id} instável ({_last_err[:120]}) — a seguir p/ próximo modelo") continue if kind == "rate_limit": quota_failures += 1 token_quota += 1 logger.warning(f"⚠️ [HF IMAGE] {account} rate-limited em {model_id} — conta marcada, a seguir p/ próximo token") self._mark_account_limited(account, err) break if kind == "payment": # 402 é POR MODELO (fal-ai/replicate não têm créditos, o # nscale gratuito continua acessível) — não marca a conta # nem interrompe: tenta os restantes modelos da mesma conta. quota_failures += 1 token_quota += 1 self._mark_payment_blocked(account, model_id) logger.warning(f"⚠️ [HF IMAGE] {model_id} sem créditos (402) na conta {account} — a seguir p/ próximo modelo") continue logger.warning(f"⚠️ [HF IMAGE] {model_id} falhou: {err[:150]}") continue else: # Modelos TODOS tentados sem break: se cada um devolveu quota (402/429), # é a CONTA que está sem créditos — erro HTTP real desta conta, marca-a. if token_attempts and token_quota == token_attempts: logger.warning( f"⚠️ [HF IMAGE] Conta {account} sem créditos em todos os modelos " f"({token_quota}/{token_attempts} com quota) — conta marcada" ) self._mark_account_limited(account, _last_err) return { "success": False, "error": f"HuggingFace Image Gen falhou ({_last_err or 'sem tentativas'})", "quota_exhausted": bool(attempts) and quota_failures == attempts, "attempts_exhausted": True, } # ============================================================================ # FALLBACK: Pollinations Flux (quando CellCog e HF não estão disponíveis) # ============================================================================ class PollinationsFluxFallback: """ Fallback para geração de imagens usando Pollinations Flux. Sempre usa model='flux' (melhor qualidade da Pollinations). """ BASE_URL = "https://image.pollinations.ai/prompt" MODEL_MAP = { "flux": "flux", "flux-realism": "flux-realism", "flux-anime": "flux-anime", "anime": "flux-anime", "realistic": "flux-realism", "sdxl": "flux", "sd3": "flux", } @staticmethod def generate( prompt: str, aspect_ratio: str = "1:1", model: str = "flux" ) -> Dict[str, Any]: """ Gera imagem via Pollinations Flux com retry em 429 e seed aleatório. model é mapeado para modelos suportados pela Pollinations. """ import urllib.parse import random import time try: logger.info(f"🔄 [Flux Fallback] Gerando imagem: '{prompt[:50]}...'") ratio_map = { "1:1": (1024, 1024), "16:9": (1344, 756), "9:16": (756, 1344), "4:3": (1024, 768), "3:4": (768, 1024) } width, height = ratio_map.get(aspect_ratio, (1024, 1024)) actual_model = PollinationsFluxFallback.MODEL_MAP.get(model, "flux") encoded_prompt = urllib.parse.quote(prompt) url = f"{PollinationsFluxFallback.BASE_URL}/{encoded_prompt}" params = { "width": width, "height": height, "model": actual_model, "nologo": "true", "seed": random.randint(1, 999999) } max_retries = 2 for attempt in range(max_retries): image_url = f"{url}?{'&'.join(f'{k}={v}' for k, v in params.items())}" response = requests.get(image_url, timeout=90) if response.status_code == 200 and len(response.content) > 1000: logger.success(f"✅ [Flux Fallback] Imagem gerada via {actual_model}") return { "success": True, "image_data": base64.b64encode(response.content).decode('utf-8'), "mime_type": "image/png", "model": f"pollinations-{actual_model}", "prompt": prompt } if response.status_code == 429 and attempt < max_retries - 1: logger.warning(f"⚠️ [Flux Fallback] 429, retry {attempt + 1}/{max_retries}...") time.sleep(1.5) params["seed"] = random.randint(1, 999999) else: return {"success": False, "error": f"Flux retornou status {response.status_code}"} return {"success": False, "error": "Flux falhou após retentativas"} except Exception as e: logger.error(f"❌ [Flux Fallback] Erro: {e}") return {"success": False, "error": str(e)} # ============================================================================ # FACTORY: Escolhe melhor provider com múltiplos fallbacks # ============================================================================ class AIMediaFactory: """ Factory que escolhe o melhor provider disponível. Chain de prioridade: 1. HuggingFace Inference (best quality - FLUX.2-klein-9B/FLUX.1-dev via Router, 3 accounts rotation) 2. Pollinations Flux (grátis — último recurso, só depois de o HF esgotar tokens/modelos) 3. CellCog (se disponível) 4. Cloudflare Workers AI 5. Stability AI SD3.5 """ @staticmethod def _extract_and_render_text(image_data: str, prompt: str) -> str: """ Extrai texto entre aspas do prompt e sobrepõe na imagem via PIL. Retorna image_data (base64) com ou sem overlay. """ import re matches = re.findall(r'[""]([^""]{2,})[""]', prompt) if not matches: return image_data text = matches[-1] if len(text) < 3 or len(text) > 200: return image_data try: import base64 as b64 img = Image.open(io.BytesIO(b64.b64decode(image_data))).convert("RGBA") w, h = img.size overlay = Image.new("RGBA", img.size, (0, 0, 0, 0)) draw = ImageDraw.Draw(overlay) font_size = max(w // 18, 20) try: font = ImageFont.truetype("arialbd.ttf", font_size) except (IOError, OSError): try: font = ImageFont.truetype("arial.ttf", font_size) except (IOError, OSError): font = ImageFont.load_default() bb = draw.textbbox((0, 0), text, font=font) tw, th = bb[2] - bb[0], bb[3] - bb[1] padding = int(h * 0.03) bar_h = th + padding * 2 bar_y = h - bar_h - int(h * 0.04) draw.rectangle( [0, bar_y, w, bar_y + bar_h], fill=(0, 0, 0, 160) ) tx = (w - tw) // 2 ty = bar_y + padding + 1 line_color = (255, 200, 50, 220) draw.text((tx + 2, ty + 2), text, font=font, fill=(0, 0, 0, 200)) draw.text((tx, ty), text, font=font, fill=line_color) img = Image.alpha_composite(img, overlay) buf = io.BytesIO() img.convert("RGB").save(buf, format="JPEG", quality=92) logger.success(f"✅ [TEXT OVERLAY] Texto renderizado: '{text[:60]}'") return b64.b64encode(buf.getvalue()).decode('utf-8') except Exception as e: logger.warning(f"⚠️ [TEXT OVERLAY] Falha ao renderizar texto: {e}") return image_data def __init__(self): self.cellcog = CellCogClient() self.hf_image = HuggingFaceImageGen() self.flux = PollinationsFluxFallback() def _try_provider(self, name: str, prompt: str, aspect_ratio: str, model: str, provider_instance, method: str = "generate", retries: int = 1) -> Optional[Dict[str, Any]]: import time as _t logger.info(f"🔄 [MEDIA FACTORY] Tentando {name}...") for attempt in range(retries + 1): try: gen_method = getattr(provider_instance, method, provider_instance.generate) result = gen_method(prompt=prompt, aspect_ratio=aspect_ratio, model=model) if result.get("success"): logger.info(f"✅ [MEDIA FACTORY] {name} respondeu com sucesso (tentativa {attempt+1})") return result logger.warning(f"⚠️ [MEDIA FACTORY] {name} falhou: {result.get('error', 'unknown')[:80]}") except Exception as e: logger.warning(f"⚠️ [MEDIA FACTORY] {name} erro: {e}") if attempt < retries: _t.sleep(1) return None def generate_image( self, prompt: str, model: str = "flux", aspect_ratio: str = "1:1" ) -> Dict[str, Any]: providers_tried = [] # TIER 1: HuggingFace Inference (FLUX.1-schnell free primeiro; dev/SDLX pagos depois) providers_tried.append("hf_inference") try: logger.info("🔄 [MEDIA FACTORY] Tentando HuggingFace antes dos fallbacks...") hf_result = self.hf_image.generate( prompt=prompt, aspect_ratio=aspect_ratio, model=model, ) except Exception as e: logger.warning(f"⚠️ [MEDIA FACTORY] HuggingFace erro: {e}") hf_result = { "success": False, "error": f"Erro HuggingFace: {str(e)[:200]}", "quota_exhausted": False, "attempts_exhausted": False, } if hf_result and hf_result.get("success"): hf_result["image_data"] = self._extract_and_render_text( hf_result["image_data"], prompt ) return hf_result # Pollinations só depois de o HF ter ESGOTADO as tentativas (todos os tokens # × modelos, com os 402/429 reais registados) ou de a quota estar gasta. # Se o HF nem chegou a tentar (exceção inesperada), não se finge quota gasta. if not (hf_result.get("quota_exhausted") or hf_result.get("attempts_exhausted")): error = hf_result.get("error", "falha antes de esgotar as tentativas") logger.error(f"❌ [MEDIA FACTORY] HF falhou antes de esgotar as tentativas; não usar fallback: {error[:160]}") return { "success": False, "error": f"HuggingFace falhou sem esgotar as tentativas; Pollinations não foi usado. {error}", } logger.warning( f"⚠️ [MEDIA FACTORY] HuggingFace esgotou as tentativas/quota: " f"{hf_result.get('error', 'limite atingido')[:100]} — a usar Pollinations (último recurso)." ) # TIER 2: Pollinations Flux (FREE, only after HF quota exhaustion) providers_tried.append("pollinations") pollinations_model = model keywords_realistas = ["realistic", "photo", "cinematic", "8k", "photorealistic", "ultra realistic", "realista", "foto", "cinematográfico", "shape", "gym", "angulo", "feições"] if any(kw in prompt.lower() for kw in keywords_realistas): pollinations_model = "flux-realism" flux_result = self._try_provider("Pollinations Flux", prompt, aspect_ratio, pollinations_model, self.flux) if flux_result and flux_result.get("success"): flux_result["image_data"] = self._extract_and_render_text( flux_result["image_data"], prompt ) return flux_result # TIER 3: CellCog (se disponível) if self.cellcog.available: providers_tried.append("cellcog") result = self.cellcog.generate_image( prompt=prompt, aspect_ratio=aspect_ratio, quality="high" ) if result.get("success"): logger.info("✅ [MEDIA FACTORY] CellCog respondeu com sucesso") return result logger.warning(f"⚠️ [MEDIA FACTORY] CellCog falhou: {result.get('error', 'unknown')[:80]}") # TIER 4: Cloudflare Workers AI providers_tried.append("cloudflare") try: from .cloudflare_image_gen import get_cloudflare_image_gen cf_result = self._try_provider("Cloudflare", prompt, aspect_ratio, model, get_cloudflare_image_gen()) if cf_result: return cf_result except Exception as e: logger.warning(f"⚠️ [MEDIA FACTORY] Cloudflare não disponível: {e}") # TIER 5: Stability AI SD3.5 (skip content moderation filter) # Stability bloqueia "inferno" etc por moderation — usar só como último recurso providers_tried.append("stability") try: from .stability_image_gen import get_stability_image_gen stability_result = self._try_provider("Stability AI", prompt, aspect_ratio, model, get_stability_image_gen()) if stability_result: return stability_result except Exception as e: logger.warning(f"⚠️ [MEDIA FACTORY] Stability AI não disponível: {e}") logger.error(f"❌ [MEDIA FACTORY] TODOS os providers falharam: {', '.join(providers_tried)}") return {"success": False, "error": f"Todos os providers de imagem falharam: {', '.join(providers_tried)}"} # Instância global _media_factory = None def get_media_factory() -> AIMediaFactory: """Retorna instância singleton do factory.""" global _media_factory if _media_factory is None: _media_factory = AIMediaFactory() return _media_factory