Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -5,22 +5,33 @@ import requests
|
|
5 |
import dropbox
|
6 |
from datetime import datetime
|
7 |
|
8 |
-
# ---
|
9 |
-
# Asegúrate de que estas variables estén configuradas en tu entorno de Hugging Face Spaces
|
10 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
11 |
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
12 |
-
SYSTEM_MESSAGE = os.environ.get("System_Prompt"
|
13 |
-
MODEL_NAME = "
|
14 |
MAX_TOKENS = 4096
|
15 |
TEMPERATURE = 0.7
|
16 |
TOP_P = 0.95
|
17 |
REMOTE_STORAGE_TOKEN = os.environ.get("REMOTE_STORAGE_TOKEN")
|
18 |
REMOTE_DESTINATION_PATH = "/Conversations/"
|
19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
def persist_data(session_data):
|
21 |
-
"""Guarda el historial de la conversación en Dropbox."""
|
22 |
if not REMOTE_STORAGE_TOKEN:
|
23 |
-
print("
|
24 |
return
|
25 |
|
26 |
try:
|
@@ -28,9 +39,9 @@ def persist_data(session_data):
|
|
28 |
|
29 |
formatted_log = ""
|
30 |
for user_msg, assistant_msg in session_data:
|
31 |
-
formatted_log += f"
|
32 |
if assistant_msg:
|
33 |
-
formatted_log += f"
|
34 |
formatted_log += "-----\n"
|
35 |
|
36 |
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
@@ -43,13 +54,12 @@ def persist_data(session_data):
|
|
43 |
with open(temp_log_path, "rb") as f:
|
44 |
storage_client.files_upload(f.read(), f"{REMOTE_DESTINATION_PATH}{log_name}", mode=dropbox.files.WriteMode('overwrite'))
|
45 |
|
46 |
-
print(f"
|
47 |
|
48 |
except Exception as e:
|
49 |
-
print(f"Error
|
50 |
|
51 |
-
def respond(message, history):
|
52 |
-
"""Genera una respuesta del chatbot usando la API de Groq."""
|
53 |
messages = [{"role": "system", "content": SYSTEM_MESSAGE}]
|
54 |
|
55 |
for user_msg, assistant_msg in history:
|
@@ -74,238 +84,51 @@ def respond(message, history):
|
|
74 |
"stream": True
|
75 |
}
|
76 |
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
if
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
yield "Lo siento, no recibí una respuesta. Inténtalo de nuevo."
|
111 |
-
else:
|
112 |
-
current_session = history + [(message, accumulated_response)]
|
113 |
-
persist_data(current_session)
|
114 |
-
|
115 |
-
except requests.exceptions.RequestException as e:
|
116 |
-
print(f"Error en la solicitud a la API: {e}")
|
117 |
-
yield f"Error de conexión con la API: {e}"
|
118 |
-
except Exception as e:
|
119 |
-
print(f"Un error inesperado ocurrió: {e}")
|
120 |
-
yield "Lo siento, ocurrió un error inesperado al procesar tu solicitud."
|
121 |
-
|
122 |
-
|
123 |
-
# --- Definición del Tema Personalizado de Gradio ---
|
124 |
-
# Se corrigió el error eliminando argumentos no válidos
|
125 |
-
blue_theme = gr.themes.Soft(
|
126 |
-
primary_hue=gr.themes.colors.blue,
|
127 |
-
secondary_hue=gr.themes.colors.blue,
|
128 |
-
neutral_hue=gr.themes.colors.slate,
|
129 |
-
).set(
|
130 |
-
# Botones principales
|
131 |
-
button_primary_background_fill="#0d5495",
|
132 |
-
button_primary_background_fill_hover="#1e68b8",
|
133 |
-
button_primary_background_fill_dark="#0a4373",
|
134 |
-
button_primary_text_color="white",
|
135 |
-
button_primary_text_color_dark="white",
|
136 |
-
|
137 |
-
# Botones secundarios
|
138 |
-
button_secondary_background_fill="*neutral_50",
|
139 |
-
button_secondary_background_fill_hover="*neutral_100",
|
140 |
-
button_secondary_text_color="#0d5495",
|
141 |
-
button_secondary_border_color="#0d5495",
|
142 |
-
|
143 |
-
# Inputs y formularios
|
144 |
-
input_background_fill="*neutral_50",
|
145 |
-
input_background_fill_focus="white",
|
146 |
-
input_border_color="*neutral_300",
|
147 |
-
input_border_color_focus="#0d5495",
|
148 |
-
input_border_width="2px",
|
149 |
-
|
150 |
-
# Fondos generales
|
151 |
-
background_fill_primary="white",
|
152 |
-
background_fill_secondary="*neutral_50",
|
153 |
-
|
154 |
-
# Texto y enlaces
|
155 |
-
body_text_color="*neutral_700",
|
156 |
-
body_text_color_subdued="*neutral_500",
|
157 |
-
link_text_color="#0d5495",
|
158 |
-
link_text_color_hover="#1e68b8",
|
159 |
-
link_text_color_visited="#0d5495",
|
160 |
-
|
161 |
-
# Bloques y paneles
|
162 |
-
block_background_fill="white",
|
163 |
-
block_border_color="*neutral_200",
|
164 |
-
block_border_width="1px",
|
165 |
-
block_shadow="*shadow_drop",
|
166 |
-
block_title_text_color="#0d5495",
|
167 |
-
block_title_text_weight="600",
|
168 |
-
|
169 |
-
# Sombras
|
170 |
-
shadow_drop="0 2px 4px rgba(13, 84, 149, 0.1)",
|
171 |
-
shadow_drop_lg="0 4px 8px rgba(13, 84, 149, 0.15)",
|
172 |
-
|
173 |
-
# La siguiente línea fue eliminada porque causaba el error:
|
174 |
-
# chatbot_code_background_color="*neutral_100",
|
175 |
-
|
176 |
-
# Loader/spinner
|
177 |
-
loader_color="#0d5495",
|
178 |
-
|
179 |
-
# Sliders y otros controles
|
180 |
-
slider_color="#0d5495",
|
181 |
-
slider_color_dark="#1e68b8",
|
182 |
-
)
|
183 |
|
184 |
-
# --- Creación de la Interfaz
|
185 |
demo = gr.ChatInterface(
|
186 |
respond,
|
187 |
-
theme=
|
188 |
-
title="Chatbot Azul",
|
189 |
-
description="Un chatbot conversacional con un tema azul personalizado.",
|
190 |
examples=[["¡Bienvenido a Prueba BM!"],
|
191 |
["¿En qué consiste el programa y para quién es?"],
|
192 |
["¿Qué beneficios obtengo y con qué empresas me conecto?"],
|
193 |
["¿Cómo puedo participar o registrarme?"]
|
194 |
-
]
|
195 |
-
css="""
|
196 |
-
/* Estilos CSS adicionales para pulir la interfaz */
|
197 |
-
|
198 |
-
.gradio-container {
|
199 |
-
background: linear-gradient(135deg, #f8fafc 0%, #e8f4f8 100%);
|
200 |
-
min-height: 100vh;
|
201 |
-
}
|
202 |
-
|
203 |
-
.chatbot {
|
204 |
-
border-radius: 12px !important;
|
205 |
-
box-shadow: 0 4px 12px rgba(13, 84, 149, 0.1) !important;
|
206 |
-
background: white !important;
|
207 |
-
}
|
208 |
-
|
209 |
-
.message.user > .message-body {
|
210 |
-
background: linear-gradient(135deg, #0d5495 0%, #1e68b8 100%) !important;
|
211 |
-
color: white !important;
|
212 |
-
border-radius: 18px 18px 4px 18px !important;
|
213 |
-
padding: 12px 16px !important;
|
214 |
-
margin: 8px 0 !important;
|
215 |
-
box-shadow: 0 2px 8px rgba(13, 84, 149, 0.2) !important;
|
216 |
-
}
|
217 |
-
|
218 |
-
.message.bot > .message-body {
|
219 |
-
background: #f8fafc !important;
|
220 |
-
color: #374151 !important;
|
221 |
-
border-radius: 18px 18px 18px 4px !important;
|
222 |
-
border-left: 4px solid #0d5495 !important;
|
223 |
-
padding: 12px 16px !important;
|
224 |
-
margin: 8px 0 !important;
|
225 |
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05) !important;
|
226 |
-
}
|
227 |
-
|
228 |
-
/* --- NUEVA REGLA CSS AÑADIDA --- */
|
229 |
-
/* Estilo para los bloques de código dentro de los mensajes del bot */
|
230 |
-
.message.bot > .message-body pre, .message.bot > .message-body code {
|
231 |
-
background-color: #e2e8f0 !important; /* Un gris claro (slate-200) */
|
232 |
-
border-radius: 6px !important;
|
233 |
-
padding: 10px 12px !important;
|
234 |
-
border: 1px solid #cbd5e1 !important;
|
235 |
-
display: block;
|
236 |
-
overflow-x: auto;
|
237 |
-
color: #334155; /* Color de texto oscuro para el código */
|
238 |
-
}
|
239 |
-
|
240 |
-
textarea {
|
241 |
-
border: 2px solid #0d5495 !important;
|
242 |
-
border-radius: 12px !important;
|
243 |
-
padding: 12px 16px !important;
|
244 |
-
font-size: 14px !important;
|
245 |
-
transition: all 0.3s ease !important;
|
246 |
-
background: white !important;
|
247 |
-
}
|
248 |
-
|
249 |
-
textarea:focus {
|
250 |
-
border-color: #1e68b8 !important;
|
251 |
-
box-shadow: 0 0 0 3px rgba(13, 84, 149, 0.1) !important;
|
252 |
-
outline: none !important;
|
253 |
-
}
|
254 |
-
|
255 |
-
.send-button {
|
256 |
-
background: linear-gradient(135deg, #0d5495 0%, #1e68b8 100%) !important;
|
257 |
-
border: none !important;
|
258 |
-
border-radius: 8px !important;
|
259 |
-
color: white !important;
|
260 |
-
padding: 8px 16px !important;
|
261 |
-
transition: all 0.3s ease !important;
|
262 |
-
font-weight: 500 !important;
|
263 |
-
}
|
264 |
-
|
265 |
-
.send-button:hover {
|
266 |
-
transform: translateY(-2px) !important;
|
267 |
-
box-shadow: 0 4px 12px rgba(13, 84, 149, 0.3) !important;
|
268 |
-
}
|
269 |
-
|
270 |
-
.example-button {
|
271 |
-
background: linear-gradient(135deg, #f8fafc 0%, #e8f4f8 100%) !important;
|
272 |
-
border: 2px solid #0d5495 !important;
|
273 |
-
color: #0d5495 !important;
|
274 |
-
border-radius: 8px !important;
|
275 |
-
padding: 8px 16px !important;
|
276 |
-
margin: 4px !important;
|
277 |
-
transition: all 0.3s ease !important;
|
278 |
-
font-weight: 500 !important;
|
279 |
-
}
|
280 |
-
|
281 |
-
.example-button:hover {
|
282 |
-
background: linear-gradient(135deg, #0d5495 0%, #1e68b8 100%) !important;
|
283 |
-
color: white !important;
|
284 |
-
transform: translateY(-2px) !important;
|
285 |
-
box-shadow: 0 4px 8px rgba(13, 84, 149, 0.2) !important;
|
286 |
-
}
|
287 |
-
|
288 |
-
.gr-form label {
|
289 |
-
color: #0d5495 !important;
|
290 |
-
font-weight: 600 !important;
|
291 |
-
margin-bottom: 8px !important;
|
292 |
-
}
|
293 |
-
|
294 |
-
.chatbot::-webkit-scrollbar { width: 8px; }
|
295 |
-
.chatbot::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 4px; }
|
296 |
-
.chatbot::-webkit-scrollbar-thumb { background: #0d5495; border-radius: 4px; opacity: 0.6; }
|
297 |
-
.chatbot::-webkit-scrollbar-thumb:hover { background: #1e68b8; opacity: 1; }
|
298 |
-
|
299 |
-
@media (max-width: 768px) {
|
300 |
-
.message.user > .message-body,
|
301 |
-
.message.bot > .message-body {
|
302 |
-
padding: 10px 12px !important;
|
303 |
-
font-size: 14px !important;
|
304 |
-
}
|
305 |
-
}
|
306 |
-
"""
|
307 |
)
|
308 |
|
309 |
-
# ---
|
310 |
if __name__ == "__main__":
|
311 |
-
demo.launch()
|
|
|
5 |
import dropbox
|
6 |
from datetime import datetime
|
7 |
|
8 |
+
# --- Claves de API y configuración (sin cambios) ---
|
|
|
9 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
10 |
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
11 |
+
SYSTEM_MESSAGE = os.environ.get("System_Prompt")
|
12 |
+
MODEL_NAME = "meta-llama/llama-4-maverick-17b-128e-instruct"
|
13 |
MAX_TOKENS = 4096
|
14 |
TEMPERATURE = 0.7
|
15 |
TOP_P = 0.95
|
16 |
REMOTE_STORAGE_TOKEN = os.environ.get("REMOTE_STORAGE_TOKEN")
|
17 |
REMOTE_DESTINATION_PATH = "/Conversations/"
|
18 |
|
19 |
+
# --- Definición del Tema Personalizado (NUEVO) ---
|
20 |
+
# Se utiliza un tema base (Soft) y se personaliza el color primario.
|
21 |
+
custom_theme = gr.themes.Soft(
|
22 |
+
primary_hue=gr.themes.colors.blue,
|
23 |
+
secondary_hue=gr.themes.colors.blue,
|
24 |
+
).set(
|
25 |
+
# Aplicamos tu color azul específico al fondo de los botones principales.
|
26 |
+
button_primary_background_fill="#0d5495",
|
27 |
+
button_primary_background_fill_hover="#0b4a85", # Un tono un poco más oscuro para el hover
|
28 |
+
)
|
29 |
+
|
30 |
+
|
31 |
+
# --- Funciones de lógica del backend (sin cambios) ---
|
32 |
def persist_data(session_data):
|
|
|
33 |
if not REMOTE_STORAGE_TOKEN:
|
34 |
+
print("Warning: Persistence token not configured.")
|
35 |
return
|
36 |
|
37 |
try:
|
|
|
39 |
|
40 |
formatted_log = ""
|
41 |
for user_msg, assistant_msg in session_data:
|
42 |
+
formatted_log += f"User: {user_msg}\n"
|
43 |
if assistant_msg:
|
44 |
+
formatted_log += f"Assistant: {assistant_msg}\n"
|
45 |
formatted_log += "-----\n"
|
46 |
|
47 |
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
|
54 |
with open(temp_log_path, "rb") as f:
|
55 |
storage_client.files_upload(f.read(), f"{REMOTE_DESTINATION_PATH}{log_name}", mode=dropbox.files.WriteMode('overwrite'))
|
56 |
|
57 |
+
print(f"Log entry created: {log_name}")
|
58 |
|
59 |
except Exception as e:
|
60 |
+
print(f"Error during data persistence: {e}")
|
61 |
|
62 |
+
def respond(message, history: list[tuple[str, str]]):
|
|
|
63 |
messages = [{"role": "system", "content": SYSTEM_MESSAGE}]
|
64 |
|
65 |
for user_msg, assistant_msg in history:
|
|
|
84 |
"stream": True
|
85 |
}
|
86 |
|
87 |
+
response = requests.post(
|
88 |
+
GROQ_API_URL,
|
89 |
+
headers=headers,
|
90 |
+
json=payload,
|
91 |
+
stream=True
|
92 |
+
)
|
93 |
+
|
94 |
+
accumulated_response = ""
|
95 |
+
for line in response.iter_lines():
|
96 |
+
if line:
|
97 |
+
line_text = line.decode('utf-8')
|
98 |
+
if line_text.startswith("data: "):
|
99 |
+
data_str = line_text[6:]
|
100 |
+
|
101 |
+
if data_str == "[DONE]":
|
102 |
+
break
|
103 |
+
|
104 |
+
try:
|
105 |
+
data = json.loads(data_str)
|
106 |
+
if 'choices' in data and len(data['choices']) > 0:
|
107 |
+
delta = data['choices'][0].get('delta', {})
|
108 |
+
if 'content' in delta and delta['content']:
|
109 |
+
token = delta['content']
|
110 |
+
accumulated_response += token
|
111 |
+
yield accumulated_response
|
112 |
+
except json.JSONDecodeError:
|
113 |
+
continue
|
114 |
+
|
115 |
+
if not accumulated_response:
|
116 |
+
yield "Lo siento, ocurrió un error al procesar tu solicitud."
|
117 |
+
else:
|
118 |
+
current_session = history + [(message, accumulated_response)]
|
119 |
+
persist_data(current_session)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
+
# --- Creación de la Interfaz con el Tema (MODIFICADO) ---
|
122 |
demo = gr.ChatInterface(
|
123 |
respond,
|
124 |
+
theme=custom_theme, # Se añade el tema personalizado aquí
|
|
|
|
|
125 |
examples=[["¡Bienvenido a Prueba BM!"],
|
126 |
["¿En qué consiste el programa y para quién es?"],
|
127 |
["¿Qué beneficios obtengo y con qué empresas me conecto?"],
|
128 |
["¿Cómo puedo participar o registrarme?"]
|
129 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
)
|
131 |
|
132 |
+
# --- Lanzamiento de la aplicación (sin cambios) ---
|
133 |
if __name__ == "__main__":
|
134 |
+
demo.launch()```
|