Download app.py from FLAFUENTE/HUGCHAT: direct link, hf CLI and curl.
- Browser
- Download file 7.78 kB
-
https://huggingface.co/spaces/FLAFUENTE/HUGCHAT/resolve/main/app.py
- Command line
-
hf download hf://spaces/FLAFUENTE/HUGCHAT/app.py
-
curl -L -o app.py https://huggingface.co/spaces/FLAFUENTE/HUGCHAT/resolve/main/app.py
7.78 kB
| #!/usr/bin/env python3 | |
| """ | |
| HuggingChat Client - Interfaz web para Hugging Face Spaces | |
| Esta aplicación proporciona una interfaz web usando Gradio para interactuar | |
| con el cliente de HuggingChat desarrollado en este proyecto. | |
| Autor: HuggingChat Client Team | |
| Fecha: Noviembre 2024 | |
| Licencia: MIT | |
| """ | |
| import os | |
| import sys | |
| from pathlib import Path | |
| import gradio as gr | |
| # Agregamos el directorio src al path para importar nuestro módulo | |
| project_root = Path(__file__).parent | |
| src_path = project_root / "src" | |
| sys.path.insert(0, str(src_path)) | |
| try: | |
| from huggingchat_client import HuggingChatClient | |
| except ImportError as e: | |
| print(f"❌ Error importando el cliente de HuggingChat: {e}") | |
| sys.exit(1) | |
| # Variable global para mantener el cliente | |
| client = None | |
| def initialize_client(): | |
| """Inicializa el cliente de HuggingChat""" | |
| global client | |
| try: | |
| client = HuggingChatClient() | |
| return "✅ Cliente inicializado correctamente" | |
| except Exception as e: | |
| # En Spaces, a veces la validación inicial falla pero el cliente funciona | |
| # Creamos el cliente de forma más básica para Spaces | |
| client = None # Lo inicializaremos en el primer mensaje | |
| return "⚠️ Cliente listo (se inicializará en el primer mensaje)" | |
| def chat_with_huggingchat(message, history): | |
| """ | |
| Función principal para el chat con HuggingChat | |
| Args: | |
| message (str): Mensaje del usuario | |
| history (list): Historial de la conversación | |
| Returns: | |
| tuple: (mensaje_vacío, historial_actualizado) | |
| """ | |
| global client | |
| if not message.strip(): | |
| return "", history | |
| try: | |
| # Inicializar cliente si no existe (inicialización diferida) | |
| if client is None: | |
| try: | |
| client = HuggingChatClient() | |
| except Exception as init_error: | |
| error_response = f"❌ Error de conexión: {str(init_error)[:100]}... Verifica tu token HF_TOKEN" | |
| history.append([message, error_response]) | |
| return "", history | |
| # Obtener respuesta del modelo | |
| response = client.send_message(message.strip()) | |
| # Actualizar historial | |
| history.append([message, response]) | |
| return "", history | |
| except Exception as e: | |
| error_response = f"❌ Error: {str(e)}" | |
| history.append([message, error_response]) | |
| return "", history | |
| def clear_conversation(): | |
| """Limpia el historial de conversación""" | |
| global client | |
| if client: | |
| client.clear_history() | |
| return [] | |
| def get_model_info(): | |
| """Obtiene información del modelo actual""" | |
| global client | |
| if client: | |
| return f"Modelo actual: {client.model}" | |
| return "❌ Cliente no inicializado" | |
| # Configuración de la interfaz Gradio | |
| def create_interface(): | |
| """Crea la interfaz web de Gradio""" | |
| with gr.Blocks(title="HuggingChat Client") as demo: | |
| gr.HTML(""" | |
| <div style="text-align: center; margin-bottom: 20px;"> | |
| <h1>T7 - Ejercicio 2 OBS asignatura NLP</h1> | |
| <h2>Ejercicio:</h2> | |
| <p>Explora las posibilidades conversacionales de HuggingChat,</p> | |
| <p>Busca diferentes formas de comunicarte, investiga sobre ingeniería de prompting y experimenta con este chatbot.</p> | |
| <p>Investiga acerca de hugchat (hugging chat API) y desarrolla un código de prueba.</p> | |
| <hr style="margin: 20px 0;"> | |
| <p><em>Cliente oficial para la API de HuggingChat de Hugging Face</em></p> | |
| </div> | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=4): | |
| # Interfaz de chat principal | |
| chatbot = gr.Chatbot(label="Conversación con HuggingChat") | |
| with gr.Row(): | |
| msg_input = gr.Textbox( | |
| label="Tu mensaje", | |
| placeholder="Escribe tu mensaje aquí...", | |
| lines=2 | |
| ) | |
| send_btn = gr.Button("Enviar", variant="primary") | |
| with gr.Row(): | |
| clear_btn = gr.Button("Limpiar Chat") | |
| info_btn = gr.Button("ℹ️ Info del Modelo") | |
| with gr.Column(scale=1): | |
| # Panel de información | |
| gr.HTML(""" | |
| <div style="background-color: #f0f0f0; padding: 15px; border-radius: 10px; margin-bottom: 10px;"> | |
| <h3>📋 Información</h3> | |
| <p><strong>Modelo:</strong> Llama-3.2-3B-Instruct</p> | |
| <p><strong>API:</strong> Hugging Face oficial</p> | |
| <p><strong>Tipo:</strong> Chat conversacional</p> | |
| </div> | |
| """) | |
| model_info_display = gr.Textbox( | |
| label="Estado del Sistema", | |
| value="🔄 Inicializando...", | |
| interactive=False, | |
| lines=3 | |
| ) | |
| gr.HTML(""" | |
| <div style="background-color: #e6f3ff; padding: 10px; border-radius: 8px; margin-top: 10px;"> | |
| <h4>Características</h4> | |
| <ul style="margin: 5px 0; padding-left: 20px;"> | |
| <li>✅ API oficial REST</li> | |
| <li>✅ Historial de conversación</li> | |
| <li>✅ Respuestas en tiempo real</li> | |
| <li>✅ Sin límites de sesión</li> | |
| </ul> | |
| </div> | |
| """) | |
| # Event handlers | |
| msg_input.submit( | |
| chat_with_huggingchat, | |
| inputs=[msg_input, chatbot], | |
| outputs=[msg_input, chatbot] | |
| ) | |
| send_btn.click( | |
| chat_with_huggingchat, | |
| inputs=[msg_input, chatbot], | |
| outputs=[msg_input, chatbot] | |
| ) | |
| clear_btn.click( | |
| clear_conversation, | |
| outputs=[chatbot] | |
| ) | |
| info_btn.click( | |
| get_model_info, | |
| outputs=[model_info_display] | |
| ) | |
| # Inicialización automática | |
| demo.load( | |
| initialize_client, | |
| outputs=[model_info_display] | |
| ) | |
| # Footer | |
| gr.HTML(""" | |
| <div style="text-align: center; margin-top: 20px; padding: 10px; border-top: 1px solid #ddd;"> | |
| <p style="color: #666; font-size: 0.9em;"> | |
| HuggingChat Client v1.0.0 | | |
| <a href="https://huggingface.co/docs/api-inference/" target="_blank">Documentación API</a> | | |
| <a href="https://huggingface.co/settings/tokens" target="_blank">Configurar Token</a> | |
| </p> | |
| </div> | |
| """) | |
| return demo | |
| # Punto de entrada principal | |
| if __name__ == "__main__": | |
| # Verificar que el token está configurado | |
| if not os.getenv('HF_TOKEN'): | |
| print("⚠️ WARNING: HF_TOKEN no está configurado en las variables de entorno") | |
| print("La aplicación necesita un token válido de Hugging Face para funcionar") | |
| # Crear y lanzar la interfaz | |
| demo = create_interface() | |
| # Configuración para Hugging Face Spaces | |
| demo.launch( | |
| server_name="0.0.0.0", # Permite conexiones externas | |
| server_port=7860, # Puerto estándar de Hugging Face Spaces | |
| share=False, # No crear link público temporal | |
| show_error=True, # Mostrar errores en la interfaz | |
| show_api=False, # No mostrar documentación API automática | |
| quiet=False # Mostrar logs de arranque | |
| ) |