Spaces:
Sleeping
Sleeping
Update generation.py
Browse files- generation.py +47 -14
generation.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import random
|
| 4 |
-
import
|
| 5 |
from datetime import datetime
|
| 6 |
from typing import Optional
|
| 7 |
|
|
@@ -11,37 +11,70 @@ os.makedirs(OUTPUT_DIR, exist_ok=True)
|
|
| 11 |
def generate_image_from_prompt(
|
| 12 |
prompt: str,
|
| 13 |
negative_prompt: str = "",
|
| 14 |
-
model_name: str = "
|
| 15 |
seed: Optional[int] = None,
|
| 16 |
) -> tuple[Optional[str], str]:
|
| 17 |
try:
|
| 18 |
-
|
|
|
|
| 19 |
if not api_key:
|
| 20 |
return None, "❌ Falta OPENROUTER_API_KEY en los Secrets."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
# Petición a OpenRouter
|
| 23 |
response = requests.post(
|
| 24 |
url="https://openrouter.ai/api/v1/chat/completions",
|
| 25 |
headers={
|
| 26 |
"Authorization": f"Bearer {api_key}",
|
| 27 |
"Content-Type": "application/json",
|
|
|
|
|
|
|
| 28 |
},
|
| 29 |
json={
|
| 30 |
-
"model":
|
| 31 |
-
"messages": [
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
)
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
data = response.json()
|
| 36 |
|
| 37 |
-
# OpenRouter suele devolver la
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
else:
|
| 44 |
-
return None, f"
|
| 45 |
|
| 46 |
except Exception as e:
|
| 47 |
-
return None, f"❌ Error técnico: {str(e)}"
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import random
|
| 4 |
+
import re
|
| 5 |
from datetime import datetime
|
| 6 |
from typing import Optional
|
| 7 |
|
|
|
|
| 11 |
def generate_image_from_prompt(
|
| 12 |
prompt: str,
|
| 13 |
negative_prompt: str = "",
|
| 14 |
+
model_name: str = "ignored", # Ignoramos lo que venga de fuera, usaremos el bueno aquí
|
| 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 |
+
# 2. Configuración del modelo real de OpenRouter
|
| 25 |
+
# Flux Schnell es muy barato y rápido
|
| 26 |
+
real_model = "black-forest-labs/flux-schnell"
|
| 27 |
+
|
| 28 |
+
print(f"Enviando prompt a OpenRouter: {prompt}")
|
| 29 |
|
|
|
|
| 30 |
response = requests.post(
|
| 31 |
url="https://openrouter.ai/api/v1/chat/completions",
|
| 32 |
headers={
|
| 33 |
"Authorization": f"Bearer {api_key}",
|
| 34 |
"Content-Type": "application/json",
|
| 35 |
+
"HTTP-Referer": "https://huggingface.co", # Requerido por OpenRouter
|
| 36 |
+
"X-Title": "Sofia AI Studio",
|
| 37 |
},
|
| 38 |
json={
|
| 39 |
+
"model": real_model,
|
| 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 |
data = response.json()
|
| 51 |
|
| 52 |
+
# OpenRouter con Flux suele devolver la URL dentro del contenido del mensaje
|
| 53 |
+
# A veces viene como markdown: 
|
| 54 |
+
content = data['choices'][0]['message']['content']
|
| 55 |
+
|
| 56 |
+
# Buscar la URL de la imagen usando una expresión regular
|
| 57 |
+
url_match = re.search(r'\((https://.*?)\)', content) # Busca (https://...)
|
| 58 |
+
if not url_match:
|
| 59 |
+
# Si no está entre paréntesis, buscamos directamente http
|
| 60 |
+
url_match = re.search(r'(https://[^\s]+)', content)
|
| 61 |
+
|
| 62 |
+
if url_match:
|
| 63 |
+
image_url = url_match.group(1)
|
| 64 |
+
# Descargar la imagen al disco
|
| 65 |
+
img_data = requests.get(image_url).content
|
| 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 |
+
with open(file_path, 'wb') as f:
|
| 73 |
+
f.write(img_data)
|
| 74 |
+
|
| 75 |
+
return file_path, f"✅ ¡ÉXITO! Imagen generada con {real_model}"
|
| 76 |
else:
|
| 77 |
+
return None, f"⚠️ OpenRouter respondió texto pero no encontré imagen: {content}"
|
| 78 |
|
| 79 |
except Exception as e:
|
| 80 |
+
return None, f"❌ Error técnico crítico: {str(e)}"
|