""" Chatbot Biblioteca usando Gradio + Wit.ai (API /converse) No dejes el token en el código: se lee desde la variable de entorno WIT_TOKEN. En Hugging Face Spaces → Settings → Repository secrets añade WIT_TOKEN. """ import os import requests import gradio as gr # Obtener el token desde secrets de Hugging Face WIT_TOKEN = os.getenv("WIT_TOKEN") if not WIT_TOKEN: raise ValueError( "No se encontró la variable de entorno 'WIT_TOKEN'.\n" "En Hugging Face: Settings → Repository secrets → añade 'WIT_TOKEN'." ) # Función para enviar mensajes a Wit.ai usando /converse def chatbot_respuesta(mensaje): url = "https://api.wit.ai/converse?v=20250101" headers = { "Authorization": f"Bearer {WIT_TOKEN}", "Content-Type": "application/json" } data = { "query": mensaje, "session_id": "usuario_123" # cualquier string que identifique la sesión } try: response = requests.post(url, headers=headers, json=data, timeout=10) response.raise_for_status() result = response.json() # Wit.ai devuelve 'type' que indica si es mensaje, acción o error if result.get("type") == "msg": return result.get("text", "Lo siento, no entendí tu mensaje 🤖.") else: return "Lo siento, no entendí tu mensaje 🤖." except requests.exceptions.RequestException as e: return f"Error de conexión a Wit.ai: {e}" except Exception as e: return f"Error procesando la respuesta: {e}" # Interfaz Gradio iface = gr.Interface( fn=chatbot_respuesta, inputs="text", outputs="text", title="Chatbot Biblioteca con Wit.ai", description="Escribe un mensaje y el bot responderá usando Wit.ai." ) # Lanzamiento en Hugging Face Spaces if __name__ == "__main__": iface.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))