Spaces:
Runtime error
Runtime error
Actualizar app.py
Browse files
app.py
CHANGED
|
@@ -1,255 +1,113 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
from datetime import datetime
|
| 5 |
import logging
|
| 6 |
import threading
|
| 7 |
|
| 8 |
-
# Configuraci贸n de logging
|
| 9 |
logging.basicConfig(level=logging.INFO)
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
-
|
| 13 |
-
from model_manager import ModelManager
|
| 14 |
-
from api_agent import APIAgent
|
| 15 |
-
from prompt_generator import PromptGenerator
|
| 16 |
-
|
| 17 |
-
# Inicializar componentes
|
| 18 |
-
model_manager = ModelManager()
|
| 19 |
-
api_agent = APIAgent()
|
| 20 |
-
prompt_generator = PromptGenerator()
|
| 21 |
-
|
| 22 |
-
class BATUTOChatbot:
|
| 23 |
def __init__(self):
|
| 24 |
self.conversation_history = []
|
| 25 |
-
self.
|
| 26 |
-
|
| 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):
|
| 33 |
-
"""Actualiza la configuraci贸n desde la UI"""
|
| 34 |
-
updated = False
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 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 |
-
|
| 78 |
-
yield 'Procesando...'
|
| 79 |
|
| 80 |
try:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
enhanced_prompt = prompt_generator.enhance_prompt(message, intent)
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
|
| 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 |
-
#
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
metadata += f' | Tipo: C贸digo'
|
| 105 |
-
else:
|
| 106 |
-
metadata += f' | Tipo: Conversaci贸n'
|
| 107 |
|
| 108 |
-
full_response =
|
| 109 |
|
| 110 |
-
# Guardar en historial
|
| 111 |
self.conversation_history.append({
|
| 112 |
-
|
| 113 |
-
|
| 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
|
| 123 |
-
logger.error(f'Error en chat_response: {e}')
|
| 124 |
yield error_msg
|
| 125 |
-
|
| 126 |
-
def clear_conversation(self):
|
| 127 |
-
"""Limpia la conversaci贸n"""
|
| 128 |
-
self.conversation_history.clear()
|
| 129 |
-
return None, []
|
| 130 |
|
| 131 |
-
# Crear instancia
|
| 132 |
-
chatbot =
|
| 133 |
|
| 134 |
-
# Cargar modelos
|
| 135 |
def load_models_async():
|
| 136 |
-
|
| 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 |
-
#
|
| 145 |
-
with gr.Blocks(
|
| 146 |
-
|
| 147 |
-
theme=gr.themes.Soft(),
|
| 148 |
-
css='''
|
| 149 |
-
.gradio-container {
|
| 150 |
-
max-width: 1000px !important;
|
| 151 |
-
margin: auto;
|
| 152 |
-
}
|
| 153 |
-
.chat-container {
|
| 154 |
-
height: 500px;
|
| 155 |
-
}
|
| 156 |
-
.status-panel {
|
| 157 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 158 |
-
padding: 20px;
|
| 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 |
-
|
| 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=
|
| 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 |
-
|
| 194 |
-
gr.Markdown(
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 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
|
| 250 |
-
return
|
| 251 |
|
| 252 |
-
# Conectar el bot贸n de enviar
|
| 253 |
submit_btn.click(
|
| 254 |
handle_submit,
|
| 255 |
inputs=[msg, chatbot_interface],
|
|
@@ -260,7 +118,6 @@ with gr.Blocks(
|
|
| 260 |
outputs=[chatbot_interface]
|
| 261 |
)
|
| 262 |
|
| 263 |
-
# Enter tambi茅n env铆a
|
| 264 |
msg.submit(
|
| 265 |
handle_submit,
|
| 266 |
inputs=[msg, chatbot_interface],
|
|
@@ -271,34 +128,10 @@ with gr.Blocks(
|
|
| 271 |
outputs=[chatbot_interface]
|
| 272 |
)
|
| 273 |
|
| 274 |
-
# Limpiar chat
|
| 275 |
clear_btn.click(
|
| 276 |
-
|
| 277 |
outputs=[msg, chatbot_interface]
|
| 278 |
)
|
| 279 |
-
|
| 280 |
-
# Configuraci贸n
|
| 281 |
-
save_config_btn.click(
|
| 282 |
-
chatbot.update_config,
|
| 283 |
-
inputs=[deepseek_key, openai_key, max_tokens, temperature],
|
| 284 |
-
outputs=[config_output]
|
| 285 |
-
).then(
|
| 286 |
-
chatbot.get_system_status,
|
| 287 |
-
outputs=[status_display]
|
| 288 |
-
)
|
| 289 |
-
|
| 290 |
-
# Actualizar estado al cargar
|
| 291 |
-
demo.load(
|
| 292 |
-
chatbot.get_system_status,
|
| 293 |
-
outputs=[status_display]
|
| 294 |
-
)
|
| 295 |
|
| 296 |
-
|
| 297 |
-
|
| 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 |
-
)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
from transformers import pipeline
|
|
|
|
| 4 |
import logging
|
| 5 |
import threading
|
| 6 |
|
|
|
|
| 7 |
logging.basicConfig(level=logging.INFO)
|
| 8 |
logger = logging.getLogger(__name__)
|
| 9 |
|
| 10 |
+
class SimpleChatbot:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
def __init__(self):
|
| 12 |
self.conversation_history = []
|
| 13 |
+
self.models_loaded = False
|
| 14 |
+
self.chat_model = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
def load_models(self):
|
| 17 |
+
try:
|
| 18 |
+
logger.info('Loading DialoGPT model...')
|
| 19 |
+
self.chat_model = pipeline(
|
| 20 |
+
"text-generation",
|
| 21 |
+
model="microsoft/DialoGPT-small",
|
| 22 |
+
device="cpu"
|
| 23 |
+
)
|
| 24 |
+
self.models_loaded = True
|
| 25 |
+
logger.info('Model loaded successfully')
|
| 26 |
+
return True
|
| 27 |
+
except Exception as e:
|
| 28 |
+
logger.error(f'Error loading model: {e}')
|
| 29 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def chat_response(self, message, history):
|
|
|
|
| 32 |
if not message.strip():
|
| 33 |
+
return ""
|
| 34 |
|
| 35 |
+
yield "Procesando..."
|
|
|
|
| 36 |
|
| 37 |
try:
|
| 38 |
+
if not self.models_loaded:
|
| 39 |
+
self.load_models()
|
|
|
|
| 40 |
|
| 41 |
+
# Generar respuesta con el modelo local
|
| 42 |
+
result = self.chat_model(
|
| 43 |
+
message,
|
| 44 |
+
max_length=150,
|
| 45 |
+
num_return_sequences=1,
|
| 46 |
+
temperature=0.7,
|
| 47 |
+
do_sample=True
|
| 48 |
+
)
|
| 49 |
|
| 50 |
+
response = result[0]['generated_text']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
# Limpiar respuesta
|
| 53 |
+
if response.startswith(message):
|
| 54 |
+
response = response[len(message):].strip()
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
full_response = response + "\n\n---\nFuente: Modelo Local"
|
| 57 |
|
|
|
|
| 58 |
self.conversation_history.append({
|
| 59 |
+
"user": message,
|
| 60 |
+
"bot": response
|
|
|
|
|
|
|
|
|
|
| 61 |
})
|
| 62 |
|
| 63 |
yield full_response
|
| 64 |
|
| 65 |
except Exception as e:
|
| 66 |
+
error_msg = f"Error: {str(e)}"
|
|
|
|
| 67 |
yield error_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
# Crear instancia
|
| 70 |
+
chatbot = SimpleChatbot()
|
| 71 |
|
| 72 |
+
# Cargar modelos en segundo plano
|
| 73 |
def load_models_async():
|
| 74 |
+
chatbot.load_models()
|
|
|
|
|
|
|
| 75 |
|
|
|
|
| 76 |
model_loader = threading.Thread(target=load_models_async, daemon=True)
|
| 77 |
model_loader.start()
|
| 78 |
|
| 79 |
+
# Interfaz simple
|
| 80 |
+
with gr.Blocks(title="BATUTO Chatbot") as demo:
|
| 81 |
+
gr.Markdown("# BATUTO Chatbot - Asistente Educativo")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
with gr.Row():
|
| 84 |
with gr.Column(scale=2):
|
| 85 |
+
chatbot_interface = gr.Chatbot(label="Conversaci贸n", height=400)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
msg = gr.Textbox(
|
| 87 |
+
label="Escribe tu mensaje",
|
| 88 |
+
placeholder="Pregunta sobre programaci贸n...",
|
| 89 |
+
lines=2
|
|
|
|
| 90 |
)
|
| 91 |
|
| 92 |
with gr.Row():
|
| 93 |
+
submit_btn = gr.Button("Enviar", variant="primary")
|
| 94 |
+
clear_btn = gr.Button("Limpiar", variant="secondary")
|
| 95 |
|
| 96 |
with gr.Column(scale=1):
|
| 97 |
+
gr.Markdown("### Informaci贸n")
|
| 98 |
+
gr.Markdown("""
|
| 99 |
+
**Ejemplos:**
|
| 100 |
+
- Explica qu茅 es Python
|
| 101 |
+
- Muestra funci贸n para ordenar listas
|
| 102 |
+
- Corrige c贸digo Python
|
| 103 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
# Event handlers
|
| 106 |
def handle_submit(message, history):
|
| 107 |
if not message.strip():
|
| 108 |
+
return "", history
|
| 109 |
+
return "", history + [[message, None]]
|
| 110 |
|
|
|
|
| 111 |
submit_btn.click(
|
| 112 |
handle_submit,
|
| 113 |
inputs=[msg, chatbot_interface],
|
|
|
|
| 118 |
outputs=[chatbot_interface]
|
| 119 |
)
|
| 120 |
|
|
|
|
| 121 |
msg.submit(
|
| 122 |
handle_submit,
|
| 123 |
inputs=[msg, chatbot_interface],
|
|
|
|
| 128 |
outputs=[chatbot_interface]
|
| 129 |
)
|
| 130 |
|
|
|
|
| 131 |
clear_btn.click(
|
| 132 |
+
lambda: (None, []),
|
| 133 |
outputs=[msg, chatbot_interface]
|
| 134 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|