Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
-
# app.py (Versión
|
| 2 |
|
| 3 |
import os
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
-
from typing import List, Dict, Union
|
| 7 |
import json
|
| 8 |
# Importamos las listas de data.py
|
| 9 |
from data import (
|
|
@@ -83,180 +83,4 @@ ELEMENTOS DISPONIBLES:
|
|
| 83 |
|
| 84 |
EJEMPLO DE OUTPUT EXCLUSIVO (Asegura el cierre del bloque ```prompt):
|
| 85 |
```prompt
|
| 86 |
-
Ultra-realistic voyeuristic photo of a Linguistics Professor, caught in the sensual everyday moment of 'pulling up thigh-high hosiery' (knee lifted delicately), wearing an oversized button-down shirt and a silk-trim micro lace thong subtly visible. Ambience: soft morning light through curtains, with thin gold necklace accessory. Shot on Fujifilm GFX 100S, 110mm f/2 lens, high texture, subtle grain, cinematic warm shadows. --ar 9:16 --style raw --q 2
|
| 87 |
-
""" # <-- ¡AQUÍ ESTABA EL TRIPLE CIERRE FALTANTE!
|
| 88 |
-
|
| 89 |
-
# ==========================
|
| 90 |
-
# CLIENTE SAMBANOVA (OPTIMIZADO)
|
| 91 |
-
# ==========================
|
| 92 |
-
|
| 93 |
-
class SambaNovaClient:
|
| 94 |
-
"""Cliente optimizado para la API de SambaNova."""
|
| 95 |
-
def __init__(self, api_key: str, base_url: str = "https://api.sambanova.ai/v1"):
|
| 96 |
-
self.base_url = base_url
|
| 97 |
-
self.session = requests.Session()
|
| 98 |
-
self.session.headers.update({
|
| 99 |
-
"Authorization": f"Bearer {api_key}",
|
| 100 |
-
"Content-Type": "application/json"
|
| 101 |
-
})
|
| 102 |
-
|
| 103 |
-
def chat_completion(
|
| 104 |
-
self,
|
| 105 |
-
messages: List[Dict],
|
| 106 |
-
model: str = VOYEUR_SPECIALIST_CONFIG["name"],
|
| 107 |
-
temperature: float = 0.8,
|
| 108 |
-
top_p: float = 0.9,
|
| 109 |
-
stream: bool = False,
|
| 110 |
-
max_tokens: int = 2000
|
| 111 |
-
) -> str:
|
| 112 |
-
"""Llama al endpoint de chat/completions."""
|
| 113 |
-
url = f"{self.base_url}/chat/completions"
|
| 114 |
-
payload = {
|
| 115 |
-
"model": model,
|
| 116 |
-
"messages": messages,
|
| 117 |
-
"temperature": temperature,
|
| 118 |
-
"top_p": top_p,
|
| 119 |
-
"stream": stream,
|
| 120 |
-
"max_tokens": max_tokens
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
try:
|
| 124 |
-
response = self.session.post(url, json=payload, timeout=60)
|
| 125 |
-
response.raise_for_status()
|
| 126 |
-
data = response.json()
|
| 127 |
-
|
| 128 |
-
if data and "choices" in data and data["choices"]:
|
| 129 |
-
return data["choices"][0]["message"]["content"]
|
| 130 |
-
else:
|
| 131 |
-
return "Error en la respuesta de la API: Estructura de 'choices' vacía o incorrecta."
|
| 132 |
-
|
| 133 |
-
except requests.exceptions.HTTPError as e:
|
| 134 |
-
error_details = f"HTTP Error {e.response.status_code}: {e.response.text}"
|
| 135 |
-
print(f"Error HTTP: {error_details}")
|
| 136 |
-
return f"❌ Error de Servidor de la API. Revisa tu clave y permisos. Detalles: {error_details[:100]}..."
|
| 137 |
-
except requests.exceptions.RequestException as e:
|
| 138 |
-
print(f"Error de Conexión: {e}")
|
| 139 |
-
return f"❌ Error de Conexión. ¿Está la API funcionando? Detalles: {str(e)[:100]}..."
|
| 140 |
-
|
| 141 |
-
# ==========================
|
| 142 |
-
# FUNCIÓN DE CHAT (EL CORE RÁPIDO)
|
| 143 |
-
# ==========================
|
| 144 |
-
|
| 145 |
-
def chat_voyeur(history: List[List[Union[str, None]]]):
|
| 146 |
-
"""Función principal que maneja la lógica de la conversación y la API."""
|
| 147 |
-
api_key = os.getenv("SAMBANOVA_API_KEY")
|
| 148 |
-
if not api_key:
|
| 149 |
-
error_msg = "❌ Error: La variable de entorno SAMBANOVA_API_KEY no está configurada. ¡Asegúrate de que el secreto esté bien puesto en el Space!"
|
| 150 |
-
if history and len(history[-1]) == 2 and history[-1][1] is None:
|
| 151 |
-
history[-1][1] = error_msg
|
| 152 |
-
elif history:
|
| 153 |
-
history.append([None, error_msg])
|
| 154 |
-
else:
|
| 155 |
-
history = [[None, error_msg]]
|
| 156 |
-
return history
|
| 157 |
-
|
| 158 |
-
client = SambaNovaClient(api_key)
|
| 159 |
-
|
| 160 |
-
# Construcción de la conversación, iniciando con el prompt del sistema
|
| 161 |
-
messages: List[Dict] = [{"role": "system", "content": SYSTEM_PROMPT_BASE}]
|
| 162 |
-
|
| 163 |
-
# Construir el historial de mensajes para la API
|
| 164 |
-
for user_msg, assistant_msg in history[:-1]:
|
| 165 |
-
messages.append({"role": "user", "content": user_msg})
|
| 166 |
-
if assistant_msg is not None:
|
| 167 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
| 168 |
-
|
| 169 |
-
# Agregar el mensaje actual del usuario
|
| 170 |
-
current_user_message = history[-1][0]
|
| 171 |
-
messages.append({"role": "user", "content": current_user_message})
|
| 172 |
-
|
| 173 |
-
# Llamada a la API
|
| 174 |
-
response = client.chat_completion(messages)
|
| 175 |
-
|
| 176 |
-
# Actualizar el historial con la respuesta
|
| 177 |
-
history[-1][1] = response
|
| 178 |
-
return history
|
| 179 |
-
|
| 180 |
-
# ==========================
|
| 181 |
-
# INTERFAZ GRADIO
|
| 182 |
-
# ==========================
|
| 183 |
-
|
| 184 |
-
with gr.Blocks(title="Chatbot Voyeur Prompt Specialist") as demo:
|
| 185 |
-
|
| 186 |
-
gr.Markdown("# 🫦 Chatbot Universal - Especialista en Prompts Sensuales Voyeur")
|
| 187 |
-
gr.Markdown("### 💬 Conversa en español, ¡todo en español! Pero cuando pidas prompts, te los aviento en inglés **sin broncas**, listos para copiar y usar.")
|
| 188 |
-
|
| 189 |
-
chatbot = gr.Chatbot(
|
| 190 |
-
label="💬 Chat con el Especialista (Puro Flow)",
|
| 191 |
-
height=500
|
| 192 |
-
)
|
| 193 |
-
msg = gr.Textbox(
|
| 194 |
-
label="Échame tu mensaje, mi BATUTO",
|
| 195 |
-
placeholder="Ej: Genera 2 prompts sensuales voyeur... o pregunta lo que quieras.",
|
| 196 |
-
lines=2,
|
| 197 |
-
)
|
| 198 |
-
with gr.Row():
|
| 199 |
-
send_btn = gr.Button("🚀 Enviar y Volar", variant="primary")
|
| 200 |
-
clear_btn = gr.Button("🧹 Limpiar Cuchitrán")
|
| 201 |
-
|
| 202 |
-
gr.Markdown("---")
|
| 203 |
-
|
| 204 |
-
# Bloque de Info del Especialista
|
| 205 |
-
with gr.Accordion("📚 Ficha Técnica del Especialista (Pura Cachimba)", open=False):
|
| 206 |
-
gr.Markdown("### 📋 Especialidades")
|
| 207 |
-
gr.Markdown(f"• **Modelo:** {VOYEUR_SPECIALIST_CONFIG['name']}")
|
| 208 |
-
for specialty in VOYEUR_SPECIALIST_CONFIG["specialties"]:
|
| 209 |
-
gr.Markdown(f"• {specialty}")
|
| 210 |
-
gr.Markdown("### 🎯 Experiencia Técnica")
|
| 211 |
-
for expertise in VOYEUR_SPECIALIST_CONFIG["technical_expertise"]:
|
| 212 |
-
gr.Markdown(f"• {expertise}")
|
| 213 |
-
|
| 214 |
-
gr.Markdown("### ✨ Ejemplos para que te rifes (¡Copia y Pega!)")
|
| 215 |
-
gr.Examples(
|
| 216 |
-
examples=[
|
| 217 |
-
"Genera un prompt sensual voyeur con una secretaria.",
|
| 218 |
-
"Crea 3 prompts ultra-sensuales con momentos cotidianos.",
|
| 219 |
-
"¿Cómo generar prompts mejores para Midjourney?",
|
| 220 |
-
"Háblame sobre iluminación cinemática en la fotografía íntima."
|
| 221 |
-
],
|
| 222 |
-
inputs=msg,
|
| 223 |
-
)
|
| 224 |
-
|
| 225 |
-
# 🚀 Definición de la función auxiliar para manejar la entrada de usuario
|
| 226 |
-
def user_message(user_msg, history):
|
| 227 |
-
# Limpia el cuadro de texto y añade el mensaje de usuario al historial
|
| 228 |
-
return "", history + [[user_msg, None]]
|
| 229 |
-
|
| 230 |
-
# 🛠️ Flujo optimizado: submit y click usan la misma secuencia
|
| 231 |
-
msg.submit(
|
| 232 |
-
user_message,
|
| 233 |
-
inputs=[msg, chatbot],
|
| 234 |
-
outputs=[msg, chatbot],
|
| 235 |
-
queue=False
|
| 236 |
-
).then(
|
| 237 |
-
# Llama a la API para obtener la respuesta
|
| 238 |
-
chat_voyeur,
|
| 239 |
-
inputs=[chatbot],
|
| 240 |
-
outputs=[chatbot],
|
| 241 |
-
)
|
| 242 |
-
|
| 243 |
-
send_btn.click(
|
| 244 |
-
user_message,
|
| 245 |
-
inputs=[msg, chatbot],
|
| 246 |
-
outputs=[msg, chatbot],
|
| 247 |
-
queue=False
|
| 248 |
-
).then(
|
| 249 |
-
chat_voyeur,
|
| 250 |
-
inputs=[chatbot],
|
| 251 |
-
outputs=[chatbot],
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
clear_btn.click(lambda: [], None, chatbot, queue=False)
|
| 255 |
-
|
| 256 |
-
# Para correr el demo
|
| 257 |
-
if __name__ == "__main__":
|
| 258 |
-
if not os.getenv("SAMBANOVA_API_KEY"):
|
| 259 |
-
print("\n⚠️ ADVERTENCIA: La variable SAMBANOVA_API_KEY no está configurada. Asegúrate de ponerla en los Secretos del Space.")
|
| 260 |
-
|
| 261 |
-
demo.launch()
|
| 262 |
-
|
|
|
|
| 1 |
+
# app.py (Versión CORREGIDA y Blindada)
|
| 2 |
|
| 3 |
import os
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
+
from typing import List, Dict, Union, Tuple
|
| 7 |
import json
|
| 8 |
# Importamos las listas de data.py
|
| 9 |
from data import (
|
|
|
|
| 83 |
|
| 84 |
EJEMPLO DE OUTPUT EXCLUSIVO (Asegura el cierre del bloque ```prompt):
|
| 85 |
```prompt
|
| 86 |
+
Ultra-realistic voyeuristic photo of a Linguistics Professor, caught in the sensual everyday moment of 'pulling up thigh-high hosiery' (knee lifted delicately), wearing an oversized button-down shirt and a silk-trim micro lace thong subtly visible. Ambience: soft morning light through curtains, with thin gold necklace accessory. Shot on Fujifilm GFX 100S, 110mm f/2 lens, high texture, subtle grain, cinematic warm shadows. --ar 9:16 --style raw --q 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|