Isaac Quarenta commited on
Commit ·
d3b8ccb
1
Parent(s): b3571b6
fix(quality): Pollinations flux-realism before Stability, stable-image-ultra fallback, CLOUDFALRE_API_KEY typo fix
Browse files- modules/cellcog_integration.py +114 -31
- modules/cloudflare_rotation.py +20 -4
- modules/stability_image_gen.py +70 -59
modules/cellcog_integration.py
CHANGED
|
@@ -866,10 +866,21 @@ class HuggingFaceImageGen:
|
|
| 866 |
class PollinationsFluxFallback:
|
| 867 |
"""
|
| 868 |
Fallback para geração de imagens usando Pollinations Flux.
|
|
|
|
| 869 |
"""
|
| 870 |
|
| 871 |
BASE_URL = "https://image.pollinations.ai/prompt"
|
| 872 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 873 |
@staticmethod
|
| 874 |
def generate(
|
| 875 |
prompt: str,
|
|
@@ -877,12 +888,16 @@ class PollinationsFluxFallback:
|
|
| 877 |
model: str = "flux"
|
| 878 |
) -> Dict[str, Any]:
|
| 879 |
"""
|
| 880 |
-
Gera imagem via Pollinations Flux
|
|
|
|
| 881 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 882 |
try:
|
| 883 |
logger.info(f"🔄 [Flux Fallback] Gerando imagem: '{prompt[:50]}...'")
|
| 884 |
|
| 885 |
-
# Converte aspect_ratio para width/height
|
| 886 |
ratio_map = {
|
| 887 |
"1:1": (1024, 1024),
|
| 888 |
"16:9": (1344, 756),
|
|
@@ -892,34 +907,42 @@ class PollinationsFluxFallback:
|
|
| 892 |
}
|
| 893 |
|
| 894 |
width, height = ratio_map.get(aspect_ratio, (1024, 1024))
|
|
|
|
| 895 |
|
| 896 |
-
# Monta URL com parâmetros
|
| 897 |
-
import urllib.parse
|
| 898 |
encoded_prompt = urllib.parse.quote(prompt)
|
| 899 |
url = f"{PollinationsFluxFallback.BASE_URL}/{encoded_prompt}"
|
|
|
|
| 900 |
params = {
|
| 901 |
"width": width,
|
| 902 |
"height": height,
|
| 903 |
-
"model":
|
| 904 |
-
"nologo": "true"
|
|
|
|
| 905 |
}
|
| 906 |
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 921 |
|
| 922 |
-
return {"success": False, "error":
|
| 923 |
|
| 924 |
except Exception as e:
|
| 925 |
logger.error(f"❌ [Flux Fallback] Erro: {e}")
|
|
@@ -937,10 +960,60 @@ class AIMediaFactory:
|
|
| 937 |
1. CellCog (se disponível e funcional)
|
| 938 |
2. HuggingFace Inference (rotação de tokens)
|
| 939 |
3. Google Imagen 3 (Gemini API, free tier)
|
| 940 |
-
4.
|
| 941 |
-
5.
|
| 942 |
-
6.
|
| 943 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 944 |
|
| 945 |
def __init__(self):
|
| 946 |
self.cellcog = CellCogClient()
|
|
@@ -998,6 +1071,7 @@ class AIMediaFactory:
|
|
| 998 |
logger.warning(f"⚠️ [MEDIA FACTORY] Google Imagen não disponível: {e}")
|
| 999 |
|
| 1000 |
# TIER 4: Cloudflare Workers AI (10k req/dia grátis, FLUX melhor qualidade)
|
|
|
|
| 1001 |
try:
|
| 1002 |
from .cloudflare_image_gen import get_cloudflare_image_gen
|
| 1003 |
cf_result = self._try_provider("Cloudflare", prompt, aspect_ratio, model, get_cloudflare_image_gen())
|
|
@@ -1006,7 +1080,22 @@ class AIMediaFactory:
|
|
| 1006 |
except Exception as e:
|
| 1007 |
logger.warning(f"⚠️ [MEDIA FACTORY] Cloudflare não disponível: {e}")
|
| 1008 |
|
| 1009 |
-
# TIER 5:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1010 |
try:
|
| 1011 |
from .stability_image_gen import get_stability_image_gen
|
| 1012 |
stability_result = self._try_provider("Stability AI", prompt, aspect_ratio, model, get_stability_image_gen())
|
|
@@ -1015,12 +1104,6 @@ class AIMediaFactory:
|
|
| 1015 |
except Exception as e:
|
| 1016 |
logger.warning(f"⚠️ [MEDIA FACTORY] Stability AI não disponível: {e}")
|
| 1017 |
|
| 1018 |
-
# TIER 6: Pollinations Flux (completamente grátis, sem key)
|
| 1019 |
-
providers_tried.append("pollinations")
|
| 1020 |
-
flux_result = self._try_provider("Pollinations Flux", prompt, aspect_ratio, model, self.flux)
|
| 1021 |
-
if flux_result:
|
| 1022 |
-
return flux_result
|
| 1023 |
-
|
| 1024 |
logger.error(f"❌ [MEDIA FACTORY] TODOS os providers falharam: {', '.join(providers_tried)}")
|
| 1025 |
return {"success": False, "error": f"Todos os providers de imagem falharam: {', '.join(providers_tried)}"}
|
| 1026 |
|
|
|
|
| 866 |
class PollinationsFluxFallback:
|
| 867 |
"""
|
| 868 |
Fallback para geração de imagens usando Pollinations Flux.
|
| 869 |
+
Sempre usa model='flux' (melhor qualidade da Pollinations).
|
| 870 |
"""
|
| 871 |
|
| 872 |
BASE_URL = "https://image.pollinations.ai/prompt"
|
| 873 |
|
| 874 |
+
MODEL_MAP = {
|
| 875 |
+
"flux": "flux",
|
| 876 |
+
"flux-realism": "flux-realism",
|
| 877 |
+
"flux-anime": "flux-anime",
|
| 878 |
+
"anime": "flux-anime",
|
| 879 |
+
"realistic": "flux-realism",
|
| 880 |
+
"sdxl": "flux",
|
| 881 |
+
"sd3": "flux",
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
@staticmethod
|
| 885 |
def generate(
|
| 886 |
prompt: str,
|
|
|
|
| 888 |
model: str = "flux"
|
| 889 |
) -> Dict[str, Any]:
|
| 890 |
"""
|
| 891 |
+
Gera imagem via Pollinations Flux com retry em 429 e seed aleatório.
|
| 892 |
+
model é mapeado para modelos suportados pela Pollinations.
|
| 893 |
"""
|
| 894 |
+
import urllib.parse
|
| 895 |
+
import random
|
| 896 |
+
import time
|
| 897 |
+
|
| 898 |
try:
|
| 899 |
logger.info(f"🔄 [Flux Fallback] Gerando imagem: '{prompt[:50]}...'")
|
| 900 |
|
|
|
|
| 901 |
ratio_map = {
|
| 902 |
"1:1": (1024, 1024),
|
| 903 |
"16:9": (1344, 756),
|
|
|
|
| 907 |
}
|
| 908 |
|
| 909 |
width, height = ratio_map.get(aspect_ratio, (1024, 1024))
|
| 910 |
+
actual_model = PollinationsFluxFallback.MODEL_MAP.get(model, "flux")
|
| 911 |
|
|
|
|
|
|
|
| 912 |
encoded_prompt = urllib.parse.quote(prompt)
|
| 913 |
url = f"{PollinationsFluxFallback.BASE_URL}/{encoded_prompt}"
|
| 914 |
+
|
| 915 |
params = {
|
| 916 |
"width": width,
|
| 917 |
"height": height,
|
| 918 |
+
"model": actual_model,
|
| 919 |
+
"nologo": "true",
|
| 920 |
+
"seed": random.randint(1, 999999)
|
| 921 |
}
|
| 922 |
|
| 923 |
+
max_retries = 2
|
| 924 |
+
for attempt in range(max_retries):
|
| 925 |
+
image_url = f"{url}?{'&'.join(f'{k}={v}' for k, v in params.items())}"
|
| 926 |
+
response = requests.get(image_url, timeout=60)
|
| 927 |
+
|
| 928 |
+
if response.status_code == 200 and len(response.content) > 1000:
|
| 929 |
+
logger.success(f"✅ [Flux Fallback] Imagem gerada via {actual_model}")
|
| 930 |
+
return {
|
| 931 |
+
"success": True,
|
| 932 |
+
"image_data": base64.b64encode(response.content).decode('utf-8'),
|
| 933 |
+
"mime_type": "image/png",
|
| 934 |
+
"model": f"pollinations-{actual_model}",
|
| 935 |
+
"prompt": prompt
|
| 936 |
+
}
|
| 937 |
+
|
| 938 |
+
if response.status_code == 429 and attempt < max_retries - 1:
|
| 939 |
+
logger.warning(f"⚠️ [Flux Fallback] 429, retry {attempt + 1}/{max_retries}...")
|
| 940 |
+
time.sleep(1.5)
|
| 941 |
+
params["seed"] = random.randint(1, 999999)
|
| 942 |
+
else:
|
| 943 |
+
return {"success": False, "error": f"Flux retornou status {response.status_code}"}
|
| 944 |
|
| 945 |
+
return {"success": False, "error": "Flux falhou após retentativas"}
|
| 946 |
|
| 947 |
except Exception as e:
|
| 948 |
logger.error(f"❌ [Flux Fallback] Erro: {e}")
|
|
|
|
| 960 |
1. CellCog (se disponível e funcional)
|
| 961 |
2. HuggingFace Inference (rotação de tokens)
|
| 962 |
3. Google Imagen 3 (Gemini API, free tier)
|
| 963 |
+
4. Cloudflare Workers AI (10k req/dia grátis, FLUX.1-schnell)
|
| 964 |
+
5. Pollinations Flux (grátis, flux-realism para prompts realistas)
|
| 965 |
+
6. Stability AI SD3.5 (créditos limitados, fallback)
|
| 966 |
"""
|
| 967 |
+
|
| 968 |
+
@staticmethod
|
| 969 |
+
def _extract_and_render_text(image_data: str, prompt: str) -> str:
|
| 970 |
+
"""
|
| 971 |
+
Extrai texto entre aspas do prompt e sobrepõe na imagem via PIL.
|
| 972 |
+
Retorna image_data (base64) com ou sem overlay.
|
| 973 |
+
"""
|
| 974 |
+
import re
|
| 975 |
+
matches = re.findall(r'[""]([^""]{2,})[""]', prompt)
|
| 976 |
+
if not matches:
|
| 977 |
+
return image_data
|
| 978 |
+
text = matches[-1]
|
| 979 |
+
if len(text) < 3 or len(text) > 200:
|
| 980 |
+
return image_data
|
| 981 |
+
try:
|
| 982 |
+
import base64 as b64
|
| 983 |
+
img = Image.open(io.BytesIO(b64.b64decode(image_data))).convert("RGBA")
|
| 984 |
+
w, h = img.size
|
| 985 |
+
overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
|
| 986 |
+
draw = ImageDraw.Draw(overlay)
|
| 987 |
+
font_size = max(w // 18, 20)
|
| 988 |
+
try:
|
| 989 |
+
font = ImageFont.truetype("arialbd.ttf", font_size)
|
| 990 |
+
except (IOError, OSError):
|
| 991 |
+
try:
|
| 992 |
+
font = ImageFont.truetype("arial.ttf", font_size)
|
| 993 |
+
except (IOError, OSError):
|
| 994 |
+
font = ImageFont.load_default()
|
| 995 |
+
bb = draw.textbbox((0, 0), text, font=font)
|
| 996 |
+
tw, th = bb[2] - bb[0], bb[3] - bb[1]
|
| 997 |
+
padding = int(h * 0.03)
|
| 998 |
+
bar_h = th + padding * 2
|
| 999 |
+
bar_y = h - bar_h - int(h * 0.04)
|
| 1000 |
+
draw.rectangle(
|
| 1001 |
+
[0, bar_y, w, bar_y + bar_h],
|
| 1002 |
+
fill=(0, 0, 0, 160)
|
| 1003 |
+
)
|
| 1004 |
+
tx = (w - tw) // 2
|
| 1005 |
+
ty = bar_y + padding + 1
|
| 1006 |
+
line_color = (255, 200, 50, 220)
|
| 1007 |
+
draw.text((tx + 2, ty + 2), text, font=font, fill=(0, 0, 0, 200))
|
| 1008 |
+
draw.text((tx, ty), text, font=font, fill=line_color)
|
| 1009 |
+
img = Image.alpha_composite(img, overlay)
|
| 1010 |
+
buf = io.BytesIO()
|
| 1011 |
+
img.convert("RGB").save(buf, format="JPEG", quality=92)
|
| 1012 |
+
logger.success(f"✅ [TEXT OVERLAY] Texto renderizado: '{text[:60]}'")
|
| 1013 |
+
return b64.b64encode(buf.getvalue()).decode('utf-8')
|
| 1014 |
+
except Exception as e:
|
| 1015 |
+
logger.warning(f"⚠️ [TEXT OVERLAY] Falha ao renderizar texto: {e}")
|
| 1016 |
+
return image_data
|
| 1017 |
|
| 1018 |
def __init__(self):
|
| 1019 |
self.cellcog = CellCogClient()
|
|
|
|
| 1071 |
logger.warning(f"⚠️ [MEDIA FACTORY] Google Imagen não disponível: {e}")
|
| 1072 |
|
| 1073 |
# TIER 4: Cloudflare Workers AI (10k req/dia grátis, FLUX melhor qualidade)
|
| 1074 |
+
providers_tried.append("cloudflare")
|
| 1075 |
try:
|
| 1076 |
from .cloudflare_image_gen import get_cloudflare_image_gen
|
| 1077 |
cf_result = self._try_provider("Cloudflare", prompt, aspect_ratio, model, get_cloudflare_image_gen())
|
|
|
|
| 1080 |
except Exception as e:
|
| 1081 |
logger.warning(f"⚠️ [MEDIA FACTORY] Cloudflare não disponível: {e}")
|
| 1082 |
|
| 1083 |
+
# TIER 5: Pollinations Flux (completamente grátis, sem key, melhor qualidade)
|
| 1084 |
+
providers_tried.append("pollinations")
|
| 1085 |
+
pollinations_model = model
|
| 1086 |
+
keywords_realistas = ["realistic", "photo", "cinematic", "8k", "photorealistic", "ultra realistic",
|
| 1087 |
+
"realista", "foto", "cinematográfico", "shape", "gym", "angulo", "feições"]
|
| 1088 |
+
if any(kw in prompt.lower() for kw in keywords_realistas):
|
| 1089 |
+
pollinations_model = "flux-realism"
|
| 1090 |
+
flux_result = self._try_provider("Pollinations Flux", prompt, aspect_ratio, pollinations_model, self.flux)
|
| 1091 |
+
if flux_result and flux_result.get("success"):
|
| 1092 |
+
flux_result["image_data"] = self._extract_and_render_text(
|
| 1093 |
+
flux_result["image_data"], prompt
|
| 1094 |
+
)
|
| 1095 |
+
return flux_result
|
| 1096 |
+
|
| 1097 |
+
# TIER 6: Stability AI SD3.5 (25 créditos grátis, fallback)
|
| 1098 |
+
providers_tried.append("stability")
|
| 1099 |
try:
|
| 1100 |
from .stability_image_gen import get_stability_image_gen
|
| 1101 |
stability_result = self._try_provider("Stability AI", prompt, aspect_ratio, model, get_stability_image_gen())
|
|
|
|
| 1104 |
except Exception as e:
|
| 1105 |
logger.warning(f"⚠️ [MEDIA FACTORY] Stability AI não disponível: {e}")
|
| 1106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1107 |
logger.error(f"❌ [MEDIA FACTORY] TODOS os providers falharam: {', '.join(providers_tried)}")
|
| 1108 |
return {"success": False, "error": f"Todos os providers de imagem falharam: {', '.join(providers_tried)}"}
|
| 1109 |
|
modules/cloudflare_rotation.py
CHANGED
|
@@ -37,16 +37,32 @@ class CloudflareRotation:
|
|
| 37 |
|
| 38 |
self._log_status()
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
def _discover_accounts(self):
|
| 41 |
"""Descobre contas: primária + sufixos _2, _3, etc."""
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
suffix = 2
|
| 45 |
while suffix <= 9:
|
| 46 |
acc_id_env = f'CLOUDFLARE_ACCOUNT_ID_{suffix}'
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
else:
|
| 51 |
break
|
| 52 |
suffix += 1
|
|
|
|
| 37 |
|
| 38 |
self._log_status()
|
| 39 |
|
| 40 |
+
@staticmethod
|
| 41 |
+
def _resolve_token_env() -> str:
|
| 42 |
+
"""Retorna o nome da env var do token, tentando variantes."""
|
| 43 |
+
candidates = [
|
| 44 |
+
"CLOUDFLARE_API_TOKEN",
|
| 45 |
+
"CLOUDFLARE_API_KEY",
|
| 46 |
+
"CLOUDFALRE_API_KEY",
|
| 47 |
+
]
|
| 48 |
+
for c in candidates:
|
| 49 |
+
if os.getenv(c):
|
| 50 |
+
return c
|
| 51 |
+
return "CLOUDFLARE_API_TOKEN"
|
| 52 |
+
|
| 53 |
def _discover_accounts(self):
|
| 54 |
"""Descobre contas: primária + sufixos _2, _3, etc."""
|
| 55 |
+
token_env = self._resolve_token_env()
|
| 56 |
+
self.accounts['main'] = ('CLOUDFLARE_ACCOUNT_ID', token_env)
|
| 57 |
|
| 58 |
suffix = 2
|
| 59 |
while suffix <= 9:
|
| 60 |
acc_id_env = f'CLOUDFLARE_ACCOUNT_ID_{suffix}'
|
| 61 |
+
for base in ("CLOUDFLARE_API_TOKEN", "CLOUDFLARE_API_KEY", "CLOUDFALRE_API_KEY"):
|
| 62 |
+
variant = f"{base}_{suffix}"
|
| 63 |
+
if os.getenv(acc_id_env) and os.getenv(variant):
|
| 64 |
+
self.accounts[f'main_{suffix}'] = (acc_id_env, variant)
|
| 65 |
+
break
|
| 66 |
else:
|
| 67 |
break
|
| 68 |
suffix += 1
|
modules/stability_image_gen.py
CHANGED
|
@@ -15,13 +15,19 @@ from typing import Dict, Any, Optional, List
|
|
| 15 |
|
| 16 |
class StabilityImageGen:
|
| 17 |
STABILITY_MODELS = {
|
|
|
|
| 18 |
"flux": "sd3.5-large",
|
| 19 |
"flux-dev": "sd3.5-large",
|
|
|
|
|
|
|
| 20 |
"stable-diffusion": "sd3.5-large",
|
| 21 |
"sd3-turbo": "sd3.5-large-turbo",
|
| 22 |
"playground": "sd3.5-large",
|
| 23 |
}
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
def __init__(self):
|
| 27 |
self._rotation = None
|
|
@@ -58,76 +64,81 @@ class StabilityImageGen:
|
|
| 58 |
"4:3": "4:3", "3:4": "3:4",
|
| 59 |
}
|
| 60 |
ar = ratio_map.get(aspect_ratio, "1:1")
|
| 61 |
-
sd_model = self.STABILITY_MODELS.get(model, "sd3.5-large")
|
| 62 |
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
for token_idx, api_key in enumerate(fallback_tokens):
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
"Authorization": f"Bearer {api_key}",
|
| 73 |
-
"Accept": "image/*"
|
| 74 |
-
},
|
| 75 |
-
files={"none": ""},
|
| 76 |
-
data={
|
| 77 |
"prompt": prompt,
|
| 78 |
-
"model": sd_model,
|
| 79 |
"aspect_ratio": ar,
|
| 80 |
"output_format": "png",
|
| 81 |
"mode": "text-to-image",
|
| 82 |
-
"negative_prompt": "deformed, blurry, bad anatomy, ugly, distorted, watermark, text artifacts, extra limbs, fused fingers, bad proportions, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, mutated hands, fused fingers, long neck, bad face, bad eyes, signature, username",
|
| 83 |
-
"cfg_scale": 7,
|
| 84 |
-
},
|
| 85 |
-
timeout=60
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
if response.status_code == 200 and len(response.content) > 1000:
|
| 89 |
-
img_b64 = base64.b64encode(response.content).decode("utf-8")
|
| 90 |
-
logger.success(f"✅ [STABILITY] Imagem gerada via {sd_model}")
|
| 91 |
-
return {
|
| 92 |
-
"success": True,
|
| 93 |
-
"image_data": img_b64,
|
| 94 |
-
"mime_type": "image/png",
|
| 95 |
-
"model": f"stability-{sd_model}",
|
| 96 |
-
"prompt": prompt
|
| 97 |
}
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
continue
|
| 112 |
-
|
| 113 |
-
logger.
|
| 114 |
-
if self._rotation:
|
| 115 |
-
self._rotation.handle_rate_limit_error(error_msg)
|
| 116 |
continue
|
| 117 |
-
|
| 118 |
-
logger.
|
| 119 |
continue
|
| 120 |
|
| 121 |
-
except requests.exceptions.Timeout:
|
| 122 |
-
logger.warning(f"⚠️ [STABILITY] Token {token_idx + 1} timeout")
|
| 123 |
-
continue
|
| 124 |
-
except requests.exceptions.ConnectionError as e:
|
| 125 |
-
logger.warning(f"⚠️ [STABILITY] Token {token_idx + 1} conexão: {e}")
|
| 126 |
-
continue
|
| 127 |
-
except Exception as e:
|
| 128 |
-
logger.error(f"❌ [STABILITY] Token {token_idx + 1} erro: {e}")
|
| 129 |
-
continue
|
| 130 |
-
|
| 131 |
logger.error("❌ [STABILITY] Todos os tokens falharam")
|
| 132 |
return {"success": False, "error": "Todos os tokens Stability falharam"}
|
| 133 |
|
|
|
|
| 15 |
|
| 16 |
class StabilityImageGen:
|
| 17 |
STABILITY_MODELS = {
|
| 18 |
+
"ultra": "stable-image-ultra",
|
| 19 |
"flux": "sd3.5-large",
|
| 20 |
"flux-dev": "sd3.5-large",
|
| 21 |
+
"flux-realism": "stable-image-ultra",
|
| 22 |
+
"realistic": "stable-image-ultra",
|
| 23 |
"stable-diffusion": "sd3.5-large",
|
| 24 |
"sd3-turbo": "sd3.5-large-turbo",
|
| 25 |
"playground": "sd3.5-large",
|
| 26 |
}
|
| 27 |
+
MODEL_ENDPOINTS = {
|
| 28 |
+
"stable-image-ultra": "https://api.stability.ai/v2beta/stable-image/generate/ultra",
|
| 29 |
+
}
|
| 30 |
+
DEFAULT_API_URL = "https://api.stability.ai/v2beta/stable-image/generate/sd3"
|
| 31 |
|
| 32 |
def __init__(self):
|
| 33 |
self._rotation = None
|
|
|
|
| 64 |
"4:3": "4:3", "3:4": "3:4",
|
| 65 |
}
|
| 66 |
ar = ratio_map.get(aspect_ratio, "1:1")
|
|
|
|
| 67 |
|
| 68 |
+
requested_model = self.STABILITY_MODELS.get(model, "sd3.5-large")
|
| 69 |
+
|
| 70 |
+
models_to_try = ["stable-image-ultra", "sd3.5-large"]
|
| 71 |
+
if requested_model in models_to_try:
|
| 72 |
+
models_to_try.remove(requested_model)
|
| 73 |
+
models_to_try.insert(0, requested_model)
|
| 74 |
|
| 75 |
for token_idx, api_key in enumerate(fallback_tokens):
|
| 76 |
+
for sd_model in models_to_try:
|
| 77 |
+
try:
|
| 78 |
+
api_url = self.MODEL_ENDPOINTS.get(sd_model, self.DEFAULT_API_URL)
|
| 79 |
+
logger.info(f"🎨 [STABILITY] Token {token_idx + 1}/{len(fallback_tokens)} modelo={sd_model}: '{prompt[:50]}...' [{ar}]")
|
| 80 |
+
|
| 81 |
+
data = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
"prompt": prompt,
|
|
|
|
| 83 |
"aspect_ratio": ar,
|
| 84 |
"output_format": "png",
|
| 85 |
"mode": "text-to-image",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
}
|
| 87 |
+
if "ultra" not in api_url:
|
| 88 |
+
data["model"] = sd_model
|
| 89 |
+
data["negative_prompt"] = "deformed, blurry, bad anatomy, ugly, distorted, watermark, text artifacts, extra limbs, fused fingers, bad proportions, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, mutated hands, fused fingers, long neck, bad face, bad eyes, signature, username"
|
| 90 |
+
data["cfg_scale"] = 7
|
| 91 |
+
|
| 92 |
+
response = requests.post(
|
| 93 |
+
api_url,
|
| 94 |
+
headers={
|
| 95 |
+
"Authorization": f"Bearer {api_key}",
|
| 96 |
+
"Accept": "image/*"
|
| 97 |
+
},
|
| 98 |
+
files={"none": ""},
|
| 99 |
+
data=data,
|
| 100 |
+
timeout=60
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if response.status_code == 200 and len(response.content) > 1000:
|
| 104 |
+
img_b64 = base64.b64encode(response.content).decode("utf-8")
|
| 105 |
+
logger.success(f"✅ [STABILITY] Imagem gerada via {sd_model}")
|
| 106 |
+
return {
|
| 107 |
+
"success": True,
|
| 108 |
+
"image_data": img_b64,
|
| 109 |
+
"mime_type": "image/png",
|
| 110 |
+
"model": f"stability-{sd_model}",
|
| 111 |
+
"prompt": prompt
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
error_msg = response.text[:200] if response.text else f"Status {response.status_code}"
|
| 115 |
+
error_lower = error_msg.lower()
|
| 116 |
+
|
| 117 |
+
if response.status_code == 402 or "insufficient" in error_lower or "credits" in error_lower:
|
| 118 |
+
logger.error(f"❌ [STABILITY] Token {token_idx + 1} {sd_model} sem créditos (402)")
|
| 119 |
+
break
|
| 120 |
+
elif response.status_code == 429 or "rate limit" in error_lower:
|
| 121 |
+
logger.warning(f"⚠️ [STABILITY] Token {token_idx + 1} {sd_model} rate limited (429)")
|
| 122 |
+
break
|
| 123 |
+
elif response.status_code == 401:
|
| 124 |
+
logger.error(f"❌ [STABILITY] Token {token_idx + 1} {sd_model} inválido (401)")
|
| 125 |
+
if self._rotation:
|
| 126 |
+
self._rotation.handle_rate_limit_error(error_msg)
|
| 127 |
+
break
|
| 128 |
+
else:
|
| 129 |
+
logger.warning(f"⚠️ [STABILITY] Token {token_idx + 1} {sd_model} falhou: {error_msg}")
|
| 130 |
+
continue
|
| 131 |
+
|
| 132 |
+
except requests.exceptions.Timeout:
|
| 133 |
+
logger.warning(f"⚠️ [STABILITY] Token {token_idx + 1} {sd_model} timeout")
|
| 134 |
continue
|
| 135 |
+
except requests.exceptions.ConnectionError as e:
|
| 136 |
+
logger.warning(f"⚠️ [STABILITY] Token {token_idx + 1} {sd_model} conexão: {e}")
|
|
|
|
|
|
|
| 137 |
continue
|
| 138 |
+
except Exception as e:
|
| 139 |
+
logger.error(f"❌ [STABILITY] Token {token_idx + 1} {sd_model} erro: {e}")
|
| 140 |
continue
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
logger.error("❌ [STABILITY] Todos os tokens falharam")
|
| 143 |
return {"success": False, "error": "Todos os tokens Stability falharam"}
|
| 144 |
|