""" Cloudflare Workers AI Image Generation - SDXL + FLUX via Cloudflare Free tier: 10,000 requests/dia por conta Multi-conta via CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN com sufixos _2, _3, ... Modelo mais potente do free plan: @cf/stabilityai/stable-diffusion-xl-base-1.0 (SDXL) Fallback interno: @cf/black-forest-labs/flux-1-schnell (se disponível) """ import os import base64 import requests from loguru import logger from typing import Dict, Any, Optional, List, Tuple class CloudflareImageGen: CF_MODELS = [ "@cf/black-forest-labs/flux-1-schnell", "@cf/stabilityai/stable-diffusion-xl-base-1.0", "@cf/bytedance/stable-diffusion-xl-lightning", ] def __init__(self): self._rotation = None self._load_rotation() def _load_rotation(self): try: from .cloudflare_rotation import get_cloudflare_rotation self._rotation = get_cloudflare_rotation() logger.info("🌐 [CLOUDFLARE] Cloudflare Image Gen inicializado com rotation") except Exception as e: logger.warning(f"⚠️ [CLOUDFLARE] Falha ao carregar rotation: {e}") self._rotation = None def _get_all_credentials(self) -> List[Tuple[str, str]]: if self._rotation: return self._rotation.get_all_credentials() acc_id = os.getenv("CLOUDFLARE_ACCOUNT_ID") api_token = os.getenv("CLOUDFLARE_API_TOKEN") return [(acc_id, api_token)] if acc_id and api_token else [] def _generate_with_creds( self, account_id: str, api_token: str, prompt: str, width: int, height: int ) -> Dict[str, Any]: for cf_model in self.CF_MODELS: try: logger.info(f"🌐 [CLOUDFLARE] {cf_model}: '{prompt[:50]}...' [{width}x{height}]") response = requests.post( f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{cf_model}", headers={"Authorization": f"Bearer {api_token}"}, json={ "prompt": prompt, "width": width, "height": height, "num_steps": 30, "guidance_scale": 7.5, }, timeout=60 ) if response.status_code == 200: data = response.json() if data.get("success") and data.get("result", {}).get("image"): img_b64 = data["result"]["image"] logger.success(f"✅ [CLOUDFLARE] Imagem via {cf_model}") return { "success": True, "image_data": img_b64, "mime_type": "image/png", "model": f"cloudflare-{cf_model.split('/')[-1]}", "prompt": prompt } error_detail = data.get("errors", data.get("messages", ["unknown"])) logger.warning(f"⚠️ [CLOUDFLARE] {cf_model} API error: {error_detail}") if any("not found" in str(e).lower() or "not available" in str(e).lower() for e in error_detail): logger.info(f"⏭️ [CLOUDFLARE] {cf_model} não disponível nesta conta, pulando") continue return {"success": False, "error": str(error_detail)} error_str = f"Status {response.status_code}: {response.text[:200]}" logger.warning(f"⚠️ [CLOUDFLARE] {cf_model} {error_str}") if response.status_code in (401, 403): return {"success": False, "error": error_str} if response.status_code == 429: return {"success": False, "error": "429 Rate Limited"} continue except requests.exceptions.Timeout: logger.warning(f"⚠️ [CLOUDFLARE] {cf_model} timeout") continue except Exception as e: logger.warning(f"⚠️ [CLOUDFLARE] {cf_model} erro: {e}") continue return {"success": False, "error": "Todos os modelos Cloudflare falharam para esta conta"} def generate( self, prompt: str, aspect_ratio: str = "1:1", model: str = "flux" ) -> Dict[str, Any]: all_creds = self._get_all_credentials() if not all_creds: logger.warning("⚠️ [CLOUDFLARE] Nenhuma conta Cloudflare configurada") return {"success": False, "error": "Cloudflare não configurado"} width, height = 1024, 1024 if aspect_ratio == "16:9": width, height = 1344, 756 elif aspect_ratio == "9:16": width, height = 756, 1344 elif aspect_ratio == "4:3": width, height = 1024, 768 elif aspect_ratio == "3:4": width, height = 768, 1024 logger.info(f"🌐 [CLOUDFLARE] {len(all_creds)} conta(s), {len(self.CF_MODELS)} modelo(s)") for cred_idx, (account_id, api_token) in enumerate(all_creds): logger.info(f"🌐 [CLOUDFLARE] Tentando conta {cred_idx + 1}/{len(all_creds)}...") result = self._generate_with_creds( account_id=account_id, api_token=api_token, prompt=prompt, width=width, height=height ) if result.get("success"): return result error_msg = result.get("error", "") if "429" in error_msg: logger.warning(f"⚠️ [CLOUDFLARE] Conta {cred_idx + 1} rate limited") if self._rotation: self._rotation.handle_rate_limit_error(error_msg) continue elif "401" in error_msg or "403" in error_msg: logger.error(f"❌ [CLOUDFLARE] Conta {cred_idx + 1} credenciais inválidas") if self._rotation: self._rotation.handle_rate_limit_error(error_msg) continue logger.error("❌ [CLOUDFLARE] Todas as contas Cloudflare falharam") return {"success": False, "error": "Todas as contas Cloudflare falharam"} _instance = None def get_cloudflare_image_gen() -> CloudflareImageGen: global _instance if _instance is None: _instance = CloudflareImageGen() return _instance