File size: 5,129 Bytes
fd4e7a7
 
 
 
44b566a
 
 
 
fd4e7a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44b566a
fd4e7a7
 
 
44b566a
fd4e7a7
 
 
 
 
 
 
 
 
44b566a
fd4e7a7
 
 
 
 
 
 
 
 
 
 
 
 
44b566a
fd4e7a7
 
 
 
 
 
44b566a
fd4e7a7
 
44b566a
fd4e7a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# modules/chatbot/sidebar_chat.py
import streamlit as st
from .chat_process import ChatProcessor
from ..database.chat_mongo_db import store_chat_history, get_chat_history
import logging

logger = logging.getLogger(__name__)

def display_sidebar_chat(lang_code: str, chatbot_t: dict):
    """
    Muestra el chatbot en el sidebar con soporte para contexto semántico
    """
    with st.sidebar:
        # Estilos CSS para el chat
        st.markdown("""
        <style>
            /* Contenedor del chat con scroll */
            div[data-testid="stExpanderContent"] > div {
                max-height: 60vh;
                overflow-y: auto;
                padding-right: 10px;
            }
            
            /* Input fijo en la parte inferior */
            div[data-testid="stHorizontalBlock"]:has(> div[data-testid="column"]) {
                position: sticky;
                bottom: 0;
                background: white;
                padding-top: 10px;
                z-index: 100;
            }
        </style>
        """, unsafe_allow_html=True)

        # Inicializar el procesador de chat si no existe
        if 'chat_processor' not in st.session_state:
            st.session_state.chat_processor = ChatProcessor()

        # Configurar contexto semántico si está activo
        if st.session_state.get('semantic_agent_active', False):
            semantic_data = st.session_state.get('semantic_agent_data')
            if semantic_data:
                st.session_state.chat_processor.set_semantic_context(
                    text=semantic_data['text'],
                    metrics=semantic_data['metrics'],
                    graph_data=semantic_data['graph_data']
                )

        with st.expander("💬 Asistente Virtual", expanded=True):
            try:
                # Inicializar mensajes del chat
                if 'sidebar_messages' not in st.session_state:
                    # Mensaje inicial según el modo (normal o semántico)
                    initial_message = (
                        "¡Hola! Soy tu asistente de análisis semántico. ¿En qué puedo ayudarte?"
                        if st.session_state.get('semantic_agent_active', False)
                        else "¡Hola! ¿Cómo puedo ayudarte hoy?"
                    )
                    st.session_state.sidebar_messages = [
                        {"role": "assistant", "content": initial_message}
                    ]

                # Mostrar historial del chat
                chat_container = st.container()
                with chat_container:
                    for message in st.session_state.sidebar_messages:
                        with st.chat_message(message["role"]):
                            st.markdown(message["content"])

                # Input del usuario
                user_input = st.chat_input("Escribe tu mensaje...")

                if user_input:
                    # Agregar mensaje del usuario
                    st.session_state.sidebar_messages.append(
                        {"role": "user", "content": user_input}
                    )

                    # Mostrar mensaje del usuario
                    with chat_container:
                        with st.chat_message("user"):
                            st.markdown(user_input)

                        # Mostrar respuesta del asistente
                        with st.chat_message("assistant"):
                            response_placeholder = st.empty()
                            full_response = ""

                            # Obtener respuesta del procesador
                            for chunk in st.session_state.chat_processor.process_chat_input(
                                user_input, 
                                lang_code
                            ):
                                full_response += chunk
                                response_placeholder.markdown(full_response + "▌")

                            response_placeholder.markdown(full_response)
                            
                            # Guardar respuesta
                            st.session_state.sidebar_messages.append(
                                {"role": "assistant", "content": full_response}
                            )

                    # Guardar en base de datos
                    store_chat_history(
                        username=st.session_state.username,
                        messages=st.session_state.sidebar_messages,
                        chat_type='semantic' if st.session_state.get('semantic_agent_active') else 'general'
                    )

                # Botón para limpiar el chat
                if st.button("🔄 Limpiar conversación"):
                    st.session_state.sidebar_messages = [
                        {"role": "assistant", "content": "¡Hola! ¿En qué puedo ayudarte?"}
                    ]
                    st.rerun()

            except Exception as e:
                logger.error(f"Error en el chat: {str(e)}")
                st.error("Ocurrió un error en el chat. Por favor, inténtalo de nuevo.")