Spaces:
Sleeping
Sleeping
Update generation.py
Browse files- generation.py +76 -51
generation.py
CHANGED
|
@@ -5,76 +5,101 @@ import re
|
|
| 5 |
from datetime import datetime
|
| 6 |
from typing import Optional
|
| 7 |
|
|
|
|
| 8 |
OUTPUT_DIR = "generated_images"
|
| 9 |
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 10 |
|
| 11 |
def generate_image_from_prompt(
|
| 12 |
prompt: str,
|
| 13 |
negative_prompt: str = "",
|
| 14 |
-
model_name: str = "ignored", #
|
| 15 |
seed: Optional[int] = None,
|
| 16 |
) -> tuple[Optional[str], str]:
|
| 17 |
-
try:
|
| 18 |
-
# 1. Limpieza de Clave (Seguridad contra espacios invisibles)
|
| 19 |
-
api_key = os.getenv("OPENROUTER_API_KEY")
|
| 20 |
-
if not api_key:
|
| 21 |
-
return None, "❌ Falta OPENROUTER_API_KEY en los Secrets."
|
| 22 |
-
api_key = api_key.strip()
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
"Authorization": f"Bearer {api_key}",
|
| 34 |
"Content-Type": "application/json",
|
| 35 |
-
"HTTP-Referer": "https://huggingface.co",
|
| 36 |
"X-Title": "Sofia AI Studio",
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
|
|
|
|
| 40 |
"messages": [
|
| 41 |
{"role": "user", "content": prompt}
|
| 42 |
]
|
| 43 |
}
|
| 44 |
-
)
|
| 45 |
-
|
| 46 |
-
# 3. Procesar respuesta
|
| 47 |
-
if response.status_code != 200:
|
| 48 |
-
return None, f"❌ Error OpenRouter ({response.status_code}): {response.text}"
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 68 |
-
if seed is None: seed = random.randint(0, 9999)
|
| 69 |
-
filename = f"sofia_{timestamp}_{seed}.png"
|
| 70 |
-
file_path = os.path.join(OUTPUT_DIR, filename)
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
| 5 |
from datetime import datetime
|
| 6 |
from typing import Optional
|
| 7 |
|
| 8 |
+
# Configuración de carpetas
|
| 9 |
OUTPUT_DIR = "generated_images"
|
| 10 |
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 11 |
|
| 12 |
def generate_image_from_prompt(
|
| 13 |
prompt: str,
|
| 14 |
negative_prompt: str = "",
|
| 15 |
+
model_name: str = "ignored", # Este argumento lo ignoramos para usar los hardcodeados seguros
|
| 16 |
seed: Optional[int] = None,
|
| 17 |
) -> tuple[Optional[str], str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
# 1. VALIDACIÓN DE CREDENCIALES
|
| 20 |
+
api_key = os.getenv("OPENROUTER_API_KEY")
|
| 21 |
+
if not api_key:
|
| 22 |
+
return None, "❌ Error Crítico: No existe OPENROUTER_API_KEY en Secrets."
|
| 23 |
+
|
| 24 |
+
api_key = api_key.strip() # Limpieza de seguridad
|
| 25 |
|
| 26 |
+
# 2. DEFINICIÓN DE MODELOS (Principal y Respaldo)
|
| 27 |
+
# El ID correcto verificado es con '-1-'
|
| 28 |
+
primary_model = "black-forest-labs/flux-1-schnell"
|
| 29 |
+
backup_model = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 30 |
|
| 31 |
+
models_to_try = [primary_model, backup_model]
|
| 32 |
+
|
| 33 |
+
last_error = ""
|
| 34 |
+
|
| 35 |
+
# 3. BUCLE DE INTENTOS
|
| 36 |
+
for model in models_to_try:
|
| 37 |
+
try:
|
| 38 |
+
print(f"🔄 Intentando generar con modelo: {model}...")
|
| 39 |
+
|
| 40 |
+
headers = {
|
| 41 |
"Authorization": f"Bearer {api_key}",
|
| 42 |
"Content-Type": "application/json",
|
| 43 |
+
"HTTP-Referer": "https://huggingface.co",
|
| 44 |
"X-Title": "Sofia AI Studio",
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
payload = {
|
| 48 |
+
"model": model,
|
| 49 |
"messages": [
|
| 50 |
{"role": "user", "content": prompt}
|
| 51 |
]
|
| 52 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
response = requests.post(
|
| 55 |
+
url="https://openrouter.ai/api/v1/chat/completions",
|
| 56 |
+
headers=headers,
|
| 57 |
+
json=payload,
|
| 58 |
+
timeout=45 # Timeout para evitar bloqueos eternos
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Si hay error 400/500, pasamos al siguiente modelo
|
| 62 |
+
if response.status_code != 200:
|
| 63 |
+
error_detail = response.text
|
| 64 |
+
print(f"⚠️ Fallo con {model}: {error_detail}")
|
| 65 |
+
last_error = f"Error {response.status_code} en {model}: {error_detail}"
|
| 66 |
+
continue # Salta al siguiente modelo del bucle
|
| 67 |
+
|
| 68 |
+
# Si es 200 OK, procesamos la imagen
|
| 69 |
+
data = response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
# OpenRouter devuelve la imagen dentro del contenido del mensaje (Markdown o URL directa)
|
| 72 |
+
if "choices" in data and len(data["choices"]) > 0:
|
| 73 |
+
content = data['choices'][0]['message']['content']
|
| 74 |
|
| 75 |
+
# Buscamos la URL con regex (formatos markdown  o url directa)
|
| 76 |
+
url_match = re.search(r'\((https://.*?)\)', content)
|
| 77 |
+
if not url_match:
|
| 78 |
+
url_match = re.search(r'(https://[^\s]+\.(png|jpg|jpeg|webp))', content)
|
| 79 |
+
|
| 80 |
+
if url_match:
|
| 81 |
+
image_url = url_match.group(1)
|
| 82 |
+
|
| 83 |
+
# Descargamos la imagen
|
| 84 |
+
img_data = requests.get(image_url).content
|
| 85 |
+
|
| 86 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 87 |
+
if seed is None: seed = random.randint(0, 9999)
|
| 88 |
+
filename = f"sofia_{timestamp}_{seed}.png"
|
| 89 |
+
file_path = os.path.join(OUTPUT_DIR, filename)
|
| 90 |
+
|
| 91 |
+
with open(file_path, 'wb') as f:
|
| 92 |
+
f.write(img_data)
|
| 93 |
+
|
| 94 |
+
return file_path, f"✅ ÉXITO: Imagen creada con {model}"
|
| 95 |
+
else:
|
| 96 |
+
last_error = f"La API respondió texto pero no vi imagen: {content[:50]}..."
|
| 97 |
+
else:
|
| 98 |
+
last_error = f"Respuesta vacía o formato desconocido: {data}"
|
| 99 |
+
|
| 100 |
+
except Exception as e:
|
| 101 |
+
last_error = f"Excepción técnica con {model}: {str(e)}"
|
| 102 |
+
continue
|
| 103 |
|
| 104 |
+
# Si llega aquí, fallaron todos los modelos
|
| 105 |
+
return None, f"❌ ERROR FATAL: Fallaron todos los intentos.\nÚltimo error: {last_error}"
|