Spaces:
Runtime error
Runtime error
Actualizar app.py
Browse files
app.py
CHANGED
|
@@ -3,6 +3,7 @@ import os
|
|
| 3 |
import json
|
| 4 |
from datetime import datetime
|
| 5 |
import logging
|
|
|
|
| 6 |
|
| 7 |
# Configuración de logging
|
| 8 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -22,10 +23,10 @@ class BATUTOChatbot:
|
|
| 22 |
def __init__(self):
|
| 23 |
self.conversation_history = []
|
| 24 |
self.config = {
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
}
|
| 30 |
|
| 31 |
def update_config(self, deepseek_key, openai_key, max_tokens, temperature):
|
|
@@ -33,48 +34,48 @@ class BATUTOChatbot:
|
|
| 33 |
updated = False
|
| 34 |
|
| 35 |
if deepseek_key:
|
| 36 |
-
self.config[
|
| 37 |
updated = True
|
| 38 |
if openai_key:
|
| 39 |
-
self.config[
|
| 40 |
updated = True
|
| 41 |
if max_tokens:
|
| 42 |
-
self.config[
|
| 43 |
updated = True
|
| 44 |
if temperature:
|
| 45 |
-
self.config[
|
| 46 |
updated = True
|
| 47 |
|
| 48 |
# Actualizar agentes
|
| 49 |
model_manager.set_config(self.config)
|
| 50 |
api_agent.set_config(self.config)
|
| 51 |
|
| 52 |
-
return
|
| 53 |
|
| 54 |
def get_system_status(self):
|
| 55 |
"""Obtiene el estado del sistema"""
|
| 56 |
-
has_deepseek = bool(self.config.get(
|
| 57 |
-
has_openai = bool(self.config.get(
|
| 58 |
models_loaded = model_manager.loaded
|
| 59 |
|
| 60 |
-
status_html = f
|
| 61 |
<div style='padding: 15px; border-radius: 10px; background: #f8f9fa; border: 2px solid #e9ecef;'>
|
| 62 |
-
<h4 style='margin-top: 0;'
|
| 63 |
-
<p><strong>Modelos locales:</strong> {'
|
| 64 |
-
<p><strong>DeepSeek API:</strong> {'
|
| 65 |
-
<p><strong>OpenAI API:</strong> {'
|
| 66 |
<p><strong>Mensajes en sesión:</strong> {len(self.conversation_history)}</p>
|
| 67 |
</div>
|
| 68 |
-
|
| 69 |
return status_html
|
| 70 |
|
| 71 |
def chat_response(self, message, history):
|
| 72 |
"""Genera respuesta del chatbot optimizado para HF"""
|
| 73 |
if not message.strip():
|
| 74 |
-
return
|
| 75 |
|
| 76 |
# Mostrar indicador de typing
|
| 77 |
-
yield
|
| 78 |
|
| 79 |
try:
|
| 80 |
# Detectar intención y mejorar prompt
|
|
@@ -82,44 +83,44 @@ class BATUTOChatbot:
|
|
| 82 |
enhanced_prompt = prompt_generator.enhance_prompt(message, intent)
|
| 83 |
|
| 84 |
# Intentar usar APIs primero
|
| 85 |
-
api_result = api_agent.generate_response(enhanced_prompt, intent[
|
| 86 |
|
| 87 |
-
if api_result[
|
| 88 |
# Usar respuesta de API
|
| 89 |
-
response_text = api_result[
|
| 90 |
-
source = api_result[
|
| 91 |
else:
|
| 92 |
# Usar modelo local como fallback
|
| 93 |
response_text = model_manager.generate_local_response(
|
| 94 |
enhanced_prompt,
|
| 95 |
-
intent[
|
| 96 |
-
max_length=200
|
| 97 |
)
|
| 98 |
-
source =
|
| 99 |
|
| 100 |
# Agregar metadata a la respuesta
|
| 101 |
-
metadata = f
|
| 102 |
-
if intent[
|
| 103 |
-
metadata += f
|
| 104 |
else:
|
| 105 |
-
metadata += f
|
| 106 |
|
| 107 |
full_response = response_text + metadata
|
| 108 |
|
| 109 |
# Guardar en historial
|
| 110 |
self.conversation_history.append({
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
})
|
| 117 |
|
| 118 |
yield full_response
|
| 119 |
|
| 120 |
except Exception as e:
|
| 121 |
-
error_msg = f
|
| 122 |
-
logger.error(f
|
| 123 |
yield error_msg
|
| 124 |
|
| 125 |
def clear_conversation(self):
|
|
@@ -132,20 +133,19 @@ chatbot = BATUTOChatbot()
|
|
| 132 |
|
| 133 |
# Cargar modelos al inicio (async)
|
| 134 |
def load_models_async():
|
| 135 |
-
logger.info(
|
| 136 |
model_manager.load_models()
|
| 137 |
-
logger.info(
|
| 138 |
|
| 139 |
# Iniciar carga de modelos
|
| 140 |
-
import threading
|
| 141 |
model_loader = threading.Thread(target=load_models_async, daemon=True)
|
| 142 |
model_loader.start()
|
| 143 |
|
| 144 |
# Configuración de la interfaz Gradio para HF
|
| 145 |
with gr.Blocks(
|
| 146 |
-
title=
|
| 147 |
theme=gr.themes.Soft(),
|
| 148 |
-
css=
|
| 149 |
.gradio-container {
|
| 150 |
max-width: 1000px !important;
|
| 151 |
margin: auto;
|
|
@@ -159,95 +159,95 @@ with gr.Blocks(
|
|
| 159 |
border-radius: 10px;
|
| 160 |
color: white;
|
| 161 |
}
|
| 162 |
-
|
| 163 |
) as demo:
|
| 164 |
|
| 165 |
-
gr.Markdown(
|
| 166 |
-
#
|
| 167 |
**Sistema inteligente con modelos locales y APIs externas**
|
| 168 |
*Desplegado en Hugging Face Spaces - Versión Optimizada*
|
| 169 |
-
|
| 170 |
|
| 171 |
with gr.Row():
|
| 172 |
with gr.Column(scale=2):
|
| 173 |
# Área de chat
|
| 174 |
-
gr.Markdown(
|
| 175 |
chatbot_interface = gr.Chatbot(
|
| 176 |
-
label=
|
| 177 |
height=400,
|
| 178 |
show_copy_button=True,
|
| 179 |
container=True
|
| 180 |
)
|
| 181 |
msg = gr.Textbox(
|
| 182 |
-
label=
|
| 183 |
-
placeholder=
|
| 184 |
lines=2,
|
| 185 |
max_lines=4
|
| 186 |
)
|
| 187 |
|
| 188 |
with gr.Row():
|
| 189 |
-
submit_btn = gr.Button(
|
| 190 |
-
clear_btn = gr.Button(
|
| 191 |
|
| 192 |
with gr.Column(scale=1):
|
| 193 |
# Panel de estado
|
| 194 |
-
gr.Markdown(
|
| 195 |
status_display = gr.HTML()
|
| 196 |
|
| 197 |
# Configuración rápida
|
| 198 |
-
with gr.Accordion(
|
| 199 |
with gr.Group():
|
| 200 |
deepseek_key = gr.Textbox(
|
| 201 |
-
label=
|
| 202 |
-
type=
|
| 203 |
-
placeholder=
|
| 204 |
-
info=
|
| 205 |
)
|
| 206 |
openai_key = gr.Textbox(
|
| 207 |
-
label=
|
| 208 |
-
type=
|
| 209 |
-
placeholder=
|
| 210 |
-
info=
|
| 211 |
)
|
| 212 |
|
| 213 |
with gr.Row():
|
| 214 |
max_tokens = gr.Slider(
|
| 215 |
-
label=
|
| 216 |
minimum=100,
|
| 217 |
maximum=800,
|
| 218 |
value=400,
|
| 219 |
step=50
|
| 220 |
)
|
| 221 |
temperature = gr.Slider(
|
| 222 |
-
label=
|
| 223 |
minimum=0.1,
|
| 224 |
maximum=1.0,
|
| 225 |
value=0.7,
|
| 226 |
step=0.1
|
| 227 |
)
|
| 228 |
|
| 229 |
-
save_config_btn = gr.Button(
|
| 230 |
-
config_output = gr.Textbox(label=
|
| 231 |
|
| 232 |
# Información
|
| 233 |
-
with gr.Accordion(
|
| 234 |
-
gr.Markdown(
|
| 235 |
**Ejemplos:**
|
| 236 |
-
-
|
| 237 |
-
-
|
| 238 |
-
-
|
| 239 |
|
| 240 |
**Fuentes:**
|
| 241 |
-
1.
|
| 242 |
-
2.
|
| 243 |
-
3.
|
| 244 |
-
|
| 245 |
|
| 246 |
# Event handlers
|
| 247 |
def handle_submit(message, history):
|
| 248 |
if not message.strip():
|
| 249 |
-
return
|
| 250 |
-
return
|
| 251 |
|
| 252 |
# Conectar el botón de enviar
|
| 253 |
submit_btn.click(
|
|
@@ -294,12 +294,11 @@ with gr.Blocks(
|
|
| 294 |
)
|
| 295 |
|
| 296 |
# Configuración específica para Hugging Face Spaces
|
| 297 |
-
if __name__ ==
|
| 298 |
demo.launch(
|
| 299 |
-
server_name=
|
| 300 |
server_port=7860,
|
| 301 |
share=True,
|
| 302 |
show_error=True,
|
| 303 |
-
debug=False
|
| 304 |
-
favicon_path=None
|
| 305 |
)
|
|
|
|
| 3 |
import json
|
| 4 |
from datetime import datetime
|
| 5 |
import logging
|
| 6 |
+
import threading
|
| 7 |
|
| 8 |
# Configuración de logging
|
| 9 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 23 |
def __init__(self):
|
| 24 |
self.conversation_history = []
|
| 25 |
self.config = {
|
| 26 |
+
'deepseek_api_key': '',
|
| 27 |
+
'openai_api_key': '',
|
| 28 |
+
'max_tokens': 400,
|
| 29 |
+
'temperature': 0.7
|
| 30 |
}
|
| 31 |
|
| 32 |
def update_config(self, deepseek_key, openai_key, max_tokens, temperature):
|
|
|
|
| 34 |
updated = False
|
| 35 |
|
| 36 |
if deepseek_key:
|
| 37 |
+
self.config['deepseek_api_key'] = deepseek_key
|
| 38 |
updated = True
|
| 39 |
if openai_key:
|
| 40 |
+
self.config['openai_api_key'] = openai_key
|
| 41 |
updated = True
|
| 42 |
if max_tokens:
|
| 43 |
+
self.config['max_tokens'] = int(max_tokens)
|
| 44 |
updated = True
|
| 45 |
if temperature:
|
| 46 |
+
self.config['temperature'] = float(temperature)
|
| 47 |
updated = True
|
| 48 |
|
| 49 |
# Actualizar agentes
|
| 50 |
model_manager.set_config(self.config)
|
| 51 |
api_agent.set_config(self.config)
|
| 52 |
|
| 53 |
+
return 'Configuración actualizada' if updated else 'Sin cambios'
|
| 54 |
|
| 55 |
def get_system_status(self):
|
| 56 |
"""Obtiene el estado del sistema"""
|
| 57 |
+
has_deepseek = bool(self.config.get('deepseek_api_key'))
|
| 58 |
+
has_openai = bool(self.config.get('openai_api_key'))
|
| 59 |
models_loaded = model_manager.loaded
|
| 60 |
|
| 61 |
+
status_html = f'''
|
| 62 |
<div style='padding: 15px; border-radius: 10px; background: #f8f9fa; border: 2px solid #e9ecef;'>
|
| 63 |
+
<h4 style='margin-top: 0;'>Estado del Sistema</h4>
|
| 64 |
+
<p><strong>Modelos locales:</strong> {'Cargados' if models_loaded else 'Cargando...'}</p>
|
| 65 |
+
<p><strong>DeepSeek API:</strong> {'Configurada' if has_deepseek else 'No configurada'}</p>
|
| 66 |
+
<p><strong>OpenAI API:</strong> {'Configurada' if has_openai else 'No configurada'}</p>
|
| 67 |
<p><strong>Mensajes en sesión:</strong> {len(self.conversation_history)}</p>
|
| 68 |
</div>
|
| 69 |
+
'''
|
| 70 |
return status_html
|
| 71 |
|
| 72 |
def chat_response(self, message, history):
|
| 73 |
"""Genera respuesta del chatbot optimizado para HF"""
|
| 74 |
if not message.strip():
|
| 75 |
+
return ''
|
| 76 |
|
| 77 |
# Mostrar indicador de typing
|
| 78 |
+
yield 'Procesando...'
|
| 79 |
|
| 80 |
try:
|
| 81 |
# Detectar intención y mejorar prompt
|
|
|
|
| 83 |
enhanced_prompt = prompt_generator.enhance_prompt(message, intent)
|
| 84 |
|
| 85 |
# Intentar usar APIs primero
|
| 86 |
+
api_result = api_agent.generate_response(enhanced_prompt, intent['is_code'])
|
| 87 |
|
| 88 |
+
if api_result['response']:
|
| 89 |
# Usar respuesta de API
|
| 90 |
+
response_text = api_result['response']
|
| 91 |
+
source = api_result['source']
|
| 92 |
else:
|
| 93 |
# Usar modelo local como fallback
|
| 94 |
response_text = model_manager.generate_local_response(
|
| 95 |
enhanced_prompt,
|
| 96 |
+
intent['is_code'],
|
| 97 |
+
max_length=200
|
| 98 |
)
|
| 99 |
+
source = 'local'
|
| 100 |
|
| 101 |
# Agregar metadata a la respuesta
|
| 102 |
+
metadata = f'\n\n---\nFuente: {source.upper()}'
|
| 103 |
+
if intent['is_code']:
|
| 104 |
+
metadata += f' | Tipo: C��digo'
|
| 105 |
else:
|
| 106 |
+
metadata += f' | Tipo: Conversación'
|
| 107 |
|
| 108 |
full_response = response_text + metadata
|
| 109 |
|
| 110 |
# Guardar en historial
|
| 111 |
self.conversation_history.append({
|
| 112 |
+
'timestamp': datetime.now().isoformat(),
|
| 113 |
+
'user': message,
|
| 114 |
+
'bot': response_text,
|
| 115 |
+
'source': source,
|
| 116 |
+
'intent': intent
|
| 117 |
})
|
| 118 |
|
| 119 |
yield full_response
|
| 120 |
|
| 121 |
except Exception as e:
|
| 122 |
+
error_msg = f'Error: {str(e)}'
|
| 123 |
+
logger.error(f'Error en chat_response: {e}')
|
| 124 |
yield error_msg
|
| 125 |
|
| 126 |
def clear_conversation(self):
|
|
|
|
| 133 |
|
| 134 |
# Cargar modelos al inicio (async)
|
| 135 |
def load_models_async():
|
| 136 |
+
logger.info('Cargando modelos en segundo plano...')
|
| 137 |
model_manager.load_models()
|
| 138 |
+
logger.info('Modelos cargados exitosamente')
|
| 139 |
|
| 140 |
# Iniciar carga de modelos
|
|
|
|
| 141 |
model_loader = threading.Thread(target=load_models_async, daemon=True)
|
| 142 |
model_loader.start()
|
| 143 |
|
| 144 |
# Configuración de la interfaz Gradio para HF
|
| 145 |
with gr.Blocks(
|
| 146 |
+
title='BATUTO Chatbot - Asistente Educativo',
|
| 147 |
theme=gr.themes.Soft(),
|
| 148 |
+
css='''
|
| 149 |
.gradio-container {
|
| 150 |
max-width: 1000px !important;
|
| 151 |
margin: auto;
|
|
|
|
| 159 |
border-radius: 10px;
|
| 160 |
color: white;
|
| 161 |
}
|
| 162 |
+
'''
|
| 163 |
) as demo:
|
| 164 |
|
| 165 |
+
gr.Markdown('''
|
| 166 |
+
# BATUTO Chatbot - Asistente Educativo
|
| 167 |
**Sistema inteligente con modelos locales y APIs externas**
|
| 168 |
*Desplegado en Hugging Face Spaces - Versión Optimizada*
|
| 169 |
+
''')
|
| 170 |
|
| 171 |
with gr.Row():
|
| 172 |
with gr.Column(scale=2):
|
| 173 |
# Área de chat
|
| 174 |
+
gr.Markdown('### Conversación')
|
| 175 |
chatbot_interface = gr.Chatbot(
|
| 176 |
+
label='Chat con BATUTO',
|
| 177 |
height=400,
|
| 178 |
show_copy_button=True,
|
| 179 |
container=True
|
| 180 |
)
|
| 181 |
msg = gr.Textbox(
|
| 182 |
+
label='Escribe tu mensaje',
|
| 183 |
+
placeholder='Pregunta sobre programación, explica conceptos, pide ejemplos...',
|
| 184 |
lines=2,
|
| 185 |
max_lines=4
|
| 186 |
)
|
| 187 |
|
| 188 |
with gr.Row():
|
| 189 |
+
submit_btn = gr.Button('Enviar', variant='primary')
|
| 190 |
+
clear_btn = gr.Button('Limpiar', variant='secondary')
|
| 191 |
|
| 192 |
with gr.Column(scale=1):
|
| 193 |
# Panel de estado
|
| 194 |
+
gr.Markdown('### Estado del Sistema')
|
| 195 |
status_display = gr.HTML()
|
| 196 |
|
| 197 |
# Configuración rápida
|
| 198 |
+
with gr.Accordion('Configuración Rápida', open=False):
|
| 199 |
with gr.Group():
|
| 200 |
deepseek_key = gr.Textbox(
|
| 201 |
+
label='DeepSeek API Key',
|
| 202 |
+
type='password',
|
| 203 |
+
placeholder='sk-...',
|
| 204 |
+
info='Opcional - para respuestas mejoradas'
|
| 205 |
)
|
| 206 |
openai_key = gr.Textbox(
|
| 207 |
+
label='OpenAI API Key',
|
| 208 |
+
type='password',
|
| 209 |
+
placeholder='sk-...',
|
| 210 |
+
info='Opcional - alternativa'
|
| 211 |
)
|
| 212 |
|
| 213 |
with gr.Row():
|
| 214 |
max_tokens = gr.Slider(
|
| 215 |
+
label='Tokens máx',
|
| 216 |
minimum=100,
|
| 217 |
maximum=800,
|
| 218 |
value=400,
|
| 219 |
step=50
|
| 220 |
)
|
| 221 |
temperature = gr.Slider(
|
| 222 |
+
label='Temperatura',
|
| 223 |
minimum=0.1,
|
| 224 |
maximum=1.0,
|
| 225 |
value=0.7,
|
| 226 |
step=0.1
|
| 227 |
)
|
| 228 |
|
| 229 |
+
save_config_btn = gr.Button('Guardar Config', size='sm')
|
| 230 |
+
config_output = gr.Textbox(label='Estado', interactive=False)
|
| 231 |
|
| 232 |
# Información
|
| 233 |
+
with gr.Accordion('Cómo usar', open=True):
|
| 234 |
+
gr.Markdown('''
|
| 235 |
**Ejemplos:**
|
| 236 |
+
- Muéstrame una función Python para ordenar listas
|
| 237 |
+
- Explica qué es machine learning
|
| 238 |
+
- Corrige este código: [tu código]
|
| 239 |
|
| 240 |
**Fuentes:**
|
| 241 |
+
1. DeepSeek API (si se configura)
|
| 242 |
+
2. OpenAI API (si se configura)
|
| 243 |
+
3. Modelos locales (fallback)
|
| 244 |
+
''')
|
| 245 |
|
| 246 |
# Event handlers
|
| 247 |
def handle_submit(message, history):
|
| 248 |
if not message.strip():
|
| 249 |
+
return '', history
|
| 250 |
+
return '', history + [[message, None]]
|
| 251 |
|
| 252 |
# Conectar el botón de enviar
|
| 253 |
submit_btn.click(
|
|
|
|
| 294 |
)
|
| 295 |
|
| 296 |
# Configuración específica para Hugging Face Spaces
|
| 297 |
+
if __name__ == '__main__':
|
| 298 |
demo.launch(
|
| 299 |
+
server_name='0.0.0.0',
|
| 300 |
server_port=7860,
|
| 301 |
share=True,
|
| 302 |
show_error=True,
|
| 303 |
+
debug=False
|
|
|
|
| 304 |
)
|