""" Streamlit Interface for M1 - Hugging Face Spaces Deployment Replicates the functionality of ui_es.html in a Streamlit interface Supports English and Spanish languages """ import streamlit as st import asyncio import json from decision_agent import DecisionAgent from tools.n8n_builder import N8NWorkflowBuilder from tools.comfyui_builder import ComfyUIWorkflowBuilder from tools.github_search import GitHubSearchTool from tools.web_search import WebSearchTool from chat_handler import SessionManager # ======================================== # LANGUAGE TRANSLATIONS # ======================================== TRANSLATIONS = { "en": { "title": "AI Workflow Agent", "subtitle": "AI Decision Making System - Milestone 1", "sidebar_config": "⚙️ Configuration", "sidebar_llm": "🧠 Intelligent AI Mode (Gemini)", "sidebar_llm_help": "Enable to use Gemini AI analysis. Disable for fast keyword mode.", "sidebar_language": "🌐 Language / Idioma", "sidebar_stats": "📊 M1 Statistics", "sidebar_endpoints": "21 API endpoints", "sidebar_templates": "16 workflow templates", "sidebar_modes": "2 modes: Fast and AI", "sidebar_status": "🚀 Status", "sidebar_current_mode": "Current Mode:", "sidebar_latency": "Latency:", "sidebar_info": "📝 Information", "sidebar_description": "Workflow analysis and generation system.", "sidebar_milestone": "Milestone 1 - Completed ✅", "mode_intelligent": "🧠 Intelligent AI", "mode_fast": "⚡ Fast", # Tabs "tab_home": "🏠 Home", "tab_analyze": "🧠 AI Analysis", "tab_build": "⚙️ Build Workflow", "tab_github": "🔍 GitHub Search", "tab_web": "🌐 Web Search", "tab_chat": "💬 Chat", # Home tab "home_welcome": "Welcome to M1 Dashboard", "home_features": "✨ Main Features:", "home_feature_1": "🧠 **AI Analysis**: Analyzes your needs and recommends the best tool", "home_feature_2": "⚙️ **Workflow Generation**: Creates n8n and ComfyUI workflows", "home_feature_3": "🔍 **Smart Search**: Search GitHub and web", "home_feature_4": "💬 **AI Chat**: Conversational assistant for automation", "home_getting_started": "🚀 Getting Started:", "home_step_1": "1. Enable **AI Mode** in the sidebar for intelligent analysis", "home_step_2": "2. Navigate through tabs to explore features", "home_step_3": "3. Try example queries in each tab", "home_modes": "💡 Modes:", "home_mode_fast": "**⚡ Fast**: <100ms, predefined templates", "home_mode_intelligent": "**🧠 Intelligent**: 2-3s, deep analysis with Gemini", "home_tip": "📌 **Tip**: Start with fast mode to test, then enable AI mode for deep analysis.", # AI Analysis tab "analyze_title": "Let AI analyze your automation needs", "analyze_query": "Your Query", "analyze_placeholder": "Describe what you want to automate...", "analyze_examples": "💡 View Example Queries", "analyze_example_1": "Example 1: Automated Emails", "analyze_example_2": "Example 2: AI Art Generation", "analyze_example_3": "Example 3: CRM Sync", "analyze_btn": "Analyze with AI ✨", "analyze_result": "🧠 AI Analysis Result", "analyze_project_type": "Project Type", "analyze_confidence": "Confidence", "analyze_method": "Method", "analyze_explanation": "📝 Explanation:", "analyze_tools": "🔧 Suggested Tools:", "analyze_steps": "📋 Next Steps:", "error_empty_query": "❌ Please enter a query", "analyzing": "Analyzing...", # Build Workflow tab "build_title": "Generate complete workflows from descriptions", "build_description": "Workflow Description", "build_placeholder": "Describe the workflow you want to create...", "build_tool": "Tool", "build_tool_help": "n8n for automation, ComfyUI for AI image generation", "build_examples": "💡 View Example Workflows", "build_example_1": "Example 1: Webhook + Email", "build_example_2": "Example 2: Twitter Monitor", "build_example_3": "Example 3: AI Photos", "build_btn": "Generate Workflow 🚀", "build_result": "✅ Workflow Generated!", "build_type": "Type", "build_nodes": "Nodes", "build_method": "Method", "build_ai_analysis": "📊 AI Analysis:", "build_explanation": "Explanation:", "build_confidence": "Confidence:", "build_json": "📄 Workflow JSON:", "generating": "Generating workflow...", "generated_ai": "🧠 Generated with AI", "generated_template": "⚡ Generated with templates", # GitHub Search tab "github_title": "Find relevant open source projects", "github_keywords": "Search Keywords", "github_placeholder": "e.g., workflow automation", "github_max": "Maximum Results", "github_examples": "💡 View Search Examples", "github_btn": "Search GitHub 🔍", "github_results": "🔍 GitHub Results ({} found)", "github_description": "Description:", "github_language": "Language:", "github_docker": "🐳 **Docker:** Yes", "github_url": "URL:", "github_no_results": "📭 No repositories found", "searching_github": "Searching GitHub...", # Web Search tab "web_title": "Search the web using DuckDuckGo", "web_query": "Search Query", "web_placeholder": "e.g., n8n automation examples", "web_max": "Maximum Results", "web_btn": "Search Web 🔍", "web_results": "🌐 Search Results ({} found)", "web_no_title": "No title", "web_no_description": "No description", "web_no_results": "📭 No results found", "searching_web": "Searching the web...", # Chat tab "chat_title": "Chat with AI about your automation needs", "chat_placeholder": "Ask the AI assistant anything...", "chat_examples": "💡 View Conversation Starters", "chat_example_1": "I want to create a bot that answers questions", "chat_example_2": "Help me automate my social media posts", "chat_example_3": "I need to process CSV files", "chat_thinking": "Thinking...", "chat_tools": "Suggested tools:", # Footer "footer_notes": "📝 Notes:", "footer_fast": "**Fast mode (keywords)**: <100ms, uses predefined templates", "footer_intelligent": "**Intelligent mode (Gemini)**: 2-3s, deep AI analysis", "footer_requirements": "**Requirements**: Gemini API key for intelligent mode (free at [Google AI Studio](https://aistudio.google.com/app/apikeys))", "footer_milestone": "🚀 **Milestone 1** - Basic AI decision-making system completed", # Example texts "ex_email": "I need to send automated emails to 1000 clients every morning", "ex_ai_art": "I want to generate AI art from text descriptions and post to Instagram", "ex_crm": "Process customer data from Shopify and sync with CRM", "ex_chatbot": "Create a chatbot that answers questions from my documentation", "ex_webhook": "Create a flow that receives customer data from webhook and sends confirmation email", "ex_twitter": "Build a flow that monitors Twitter for mentions and sends Slack notifications", "ex_photos": "Generate professional photos from uploaded photos", "ex_automation": "workflow automation", "ex_ml": "machine learning deployment", "ex_image_gen": "AI image generation", "ex_bot": "I want to create a bot that answers customer questions from my website", "ex_social": "Help me automate my social media posts", "ex_csv": "I need to process CSV files and generate reports" }, "es": { "title": "Agente de Flujo de Trabajo IA", "subtitle": "Sistema de Toma de Decisiones IA - Milestone 1", "sidebar_config": "⚙️ Configuración", "sidebar_llm": "🧠 Modo IA Inteligente (Gemini)", "sidebar_llm_help": "Activar para usar análisis con Gemini AI. Desactivar para modo rápido con palabras clave.", "sidebar_language": "🌐 Language / Idioma", "sidebar_stats": "📊 Estadísticas M1", "sidebar_endpoints": "21 endpoints API activos", "sidebar_templates": "16 plantillas de flujos", "sidebar_modes": "2 modos: Rápido y IA", "sidebar_status": "🚀 Estado", "sidebar_current_mode": "Modo Actual:", "sidebar_latency": "Latencia:", "sidebar_info": "📝 Información", "sidebar_description": "Sistema de análisis y generación de flujos de trabajo.", "sidebar_milestone": "Milestone 1 - Completado ✅", "mode_intelligent": "🧠 IA Inteligente", "mode_fast": "⚡ Rápido", # Tabs "tab_home": "🏠 Inicio", "tab_analyze": "🧠 Análisis IA", "tab_build": "⚙️ Construir Flujo", "tab_github": "🔍 Búsqueda GitHub", "tab_web": "🌐 Búsqueda Web", "tab_chat": "💬 Chat", # Home tab "home_welcome": "Bienvenido al Panel M1", "home_features": "✨ Características Principales:", "home_feature_1": "🧠 **Análisis IA**: Analiza tus necesidades y recomienda la mejor herramienta", "home_feature_2": "⚙️ **Generación de Flujos**: Crea flujos de trabajo de n8n y ComfyUI", "home_feature_3": "🔍 **Búsqueda Inteligente**: Busca en GitHub y la web", "home_feature_4": "💬 **Chat IA**: Asistente conversacional para automatización", "home_getting_started": "🚀 Comenzar:", "home_step_1": "1. Activa el **Modo IA** en la barra lateral para análisis inteligente", "home_step_2": "2. Navega por las pestañas para explorar características", "home_step_3": "3. Prueba las consultas de ejemplo en cada pestaña", "home_modes": "💡 Modos:", "home_mode_fast": "**⚡ Rápido**: <100ms, plantillas predefinidas", "home_mode_intelligent": "**🧠 Inteligente**: 2-3s, análisis profundo con Gemini", "home_tip": "📌 **Tip**: Comienza con el modo rápido para probar, luego activa el modo IA para análisis profundo.", # AI Analysis tab "analyze_title": "Permite que la IA analice tus necesidades de automatización", "analyze_query": "Tu Consulta", "analyze_placeholder": "Describe lo que deseas automatizar...", "analyze_examples": "💡 Ver Consultas de Ejemplo", "analyze_example_1": "Ejemplo 1: Correos Automatizados", "analyze_example_2": "Ejemplo 2: Generación de Arte IA", "analyze_example_3": "Ejemplo 3: Sincronización CRM", "analyze_btn": "Analizar con IA ✨", "analyze_result": "🧠 Resultado del Análisis IA", "analyze_project_type": "Tipo de Proyecto", "analyze_confidence": "Confianza", "analyze_method": "Método", "analyze_explanation": "📝 Explicación:", "analyze_tools": "🔧 Herramientas Sugeridas:", "analyze_steps": "📋 Próximos Pasos:", "error_empty_query": "❌ Por favor ingrese una consulta", "analyzing": "Analizando...", # Build Workflow tab "build_title": "Genera flujos de trabajo completos a partir de descripciones", "build_description": "Descripción del Flujo de Trabajo", "build_placeholder": "Describe el flujo de trabajo que deseas crear...", "build_tool": "Herramienta", "build_tool_help": "n8n para automatización, ComfyUI para generación de imágenes IA", "build_examples": "💡 Ver Flujos de Ejemplo", "build_example_1": "Ejemplo 1: Webhook + Email", "build_example_2": "Ejemplo 2: Monitor Twitter", "build_example_3": "Ejemplo 3: Fotos IA", "build_btn": "Generar Flujo de Trabajo 🚀", "build_result": "✅ ¡Flujo de Trabajo Generado!", "build_type": "Tipo", "build_nodes": "Nodos", "build_method": "Método", "build_ai_analysis": "📊 Análisis IA:", "build_explanation": "Explicación:", "build_confidence": "Confianza:", "build_json": "📄 JSON del Flujo de Trabajo:", "generating": "Generando flujo de trabajo...", "generated_ai": "🧠 Generado con IA", "generated_template": "⚡ Generado con plantillas", # GitHub Search tab "github_title": "Encuentra proyectos de código abierto relevantes", "github_keywords": "Palabras Clave de Búsqueda", "github_placeholder": "ej., automatización de flujos de trabajo", "github_max": "Resultados Máximos", "github_examples": "💡 Ver Ejemplos de Búsqueda", "github_btn": "Buscar en GitHub 🔍", "github_results": "🔍 Resultados de GitHub ({} encontrados)", "github_description": "Descripción:", "github_language": "Lenguaje:", "github_docker": "🐳 **Docker:** Sí", "github_url": "URL:", "github_no_results": "📭 No se encontraron repositorios", "searching_github": "Buscando en GitHub...", # Web Search tab "web_title": "Busca en la web usando DuckDuckGo", "web_query": "Consulta de Búsqueda", "web_placeholder": "ej., ejemplos de automatización n8n", "web_max": "Resultados Máximos", "web_btn": "Buscar en Web 🔍", "web_results": "🌐 Resultados de Búsqueda ({} encontrados)", "web_no_title": "Sin título", "web_no_description": "Sin descripción", "web_no_results": "📭 No se encontraron resultados", "searching_web": "Buscando en la web...", # Chat tab "chat_title": "Conversa con la IA sobre tus necesidades de automatización", "chat_placeholder": "Pregunta al asistente IA cualquier cosa...", "chat_examples": "💡 Ver Iniciadores de Conversación", "chat_example_1": "Quiero crear un bot que responda preguntas", "chat_example_2": "Ayúdame a automatizar mis publicaciones", "chat_example_3": "Necesito procesar archivos CSV", "chat_thinking": "Pensando...", "chat_tools": "Herramientas sugeridas:", # Footer "footer_notes": "📝 Notas:", "footer_fast": "**Modo Rápido (palabras clave)**: <100ms, usa plantillas predefinidas", "footer_intelligent": "**Modo Inteligente (Gemini)**: 2-3s, análisis profundo con IA", "footer_requirements": "**Requisitos**: Clave API de Gemini para modo inteligente (gratis en [Google AI Studio](https://aistudio.google.com/app/apikeys))", "footer_milestone": "🚀 **Milestone 1** - Sistema de toma de decisiones IA básico completado", # Example texts "ex_email": "Necesito enviar correos electrónicos automatizados a 1000 clientes cada mañana", "ex_ai_art": "Quiero generar arte IA a partir de descripciones de texto y publicar en Instagram", "ex_crm": "Procesar datos de clientes de Shopify y sincronizar con CRM", "ex_chatbot": "Crear un chatbot que responda preguntas de mi documentación", "ex_webhook": "Crear un flujo que reciba datos de clientes desde webhook y envíe correo de confirmación", "ex_twitter": "Construir un flujo que monitoree Twitter para menciones y envíe notificaciones de Slack", "ex_photos": "Generar fotos profesionales a partir de fotos subidas", "ex_automation": "automatización de flujos de trabajo", "ex_ml": "implementación de aprendizaje automático", "ex_image_gen": "generación de imágenes IA", "ex_bot": "Quiero crear un bot que responda preguntas de clientes desde mi sitio web", "ex_social": "Ayúdame a automatizar mis publicaciones en redes sociales", "ex_csv": "Necesito procesar archivos CSV y generar reportes" } } def t(key: str, lang: str = "es") -> str: """Get translation for key in specified language""" return TRANSLATIONS.get(lang, {}).get(key, TRANSLATIONS["en"].get(key, key)) # Page config st.set_page_config( page_title="M1 - Agente de Flujo de Trabajo IA", page_icon="🤖", layout="wide", initial_sidebar_state="expanded" ) # Custom CSS st.markdown(""" """, unsafe_allow_html=True) # Initialize components @st.cache_resource def init_components(): """Initialize all M1 components (cached)""" return { 'decision_agent': DecisionAgent(), 'n8n_builder': N8NWorkflowBuilder(), 'comfyui_builder': ComfyUIWorkflowBuilder(), 'github_tool': GitHubSearchTool(), 'web_tool': WebSearchTool(), 'session_manager': SessionManager() } components = init_components() # Helper to run async functions def run_async(coro): """Run async function in sync context""" try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete(coro) # ======================================== # SIDEBAR - Global Settings # ======================================== with st.sidebar: # Language selector lang = st.selectbox( "🌐 Language / Idioma", options=["es", "en"], format_func=lambda x: "🇪🇸 Español" if x == "es" else "🇬🇧 English", index=0 ) st.markdown("---") st.markdown(f"## {t('sidebar_config', lang)}") # Initialize use_llm in session state if not present if 'use_llm' not in st.session_state: st.session_state.use_llm = True use_llm = st.checkbox( t('sidebar_llm', lang), value=st.session_state.use_llm, key='use_llm_checkbox' ) st.markdown(f""" ### {t('sidebar_stats', lang)} - **{t('sidebar_endpoints', lang)}** - **{t('sidebar_templates', lang)}** - **{t('sidebar_modes', lang)}** ### {t('sidebar_status', lang)} - **{t('sidebar_current_mode', lang)}** {t('mode_intelligent', lang) if use_llm else t('mode_fast', lang)} - **{t('sidebar_latency', lang)}** {"2-3s" if use_llm else "<100ms"} """) st.markdown("---") st.markdown(f""" ### {t('sidebar_info', lang)} {t('sidebar_description', lang)} **{t('sidebar_milestone', lang)}** """) # ======================================== # MAIN CONTENT # ======================================== # Header st.markdown(f'