File size: 5,795 Bytes
d4c16ef
 
9e1b438
304d9f9
d4c16ef
 
 
 
c623cf2
304d9f9
d4c16ef
304d9f9
9a3bdf2
 
ce069d1
9a3bdf2
 
304d9f9
9a3bdf2
304d9f9
9a3bdf2
 
 
ce069d1
304d9f9
ce069d1
 
304d9f9
ce069d1
 
 
 
304d9f9
 
 
 
 
 
 
 
 
 
 
 
 
4d1c5f5
304d9f9
 
 
c623cf2
304d9f9
 
 
 
 
ce069d1
4d1c5f5
304d9f9
4d1c5f5
d4c16ef
304d9f9
c623cf2
 
304d9f9
 
d4c16ef
304d9f9
ce069d1
 
304d9f9
 
 
 
ce069d1
d4c16ef
c623cf2
ce069d1
 
 
304d9f9
 
 
 
ce069d1
304d9f9
ce069d1
304d9f9
 
 
 
 
ce069d1
304d9f9
ce069d1
 
 
304d9f9
 
 
 
 
 
 
 
 
 
 
ce069d1
304d9f9
ce069d1
304d9f9
 
 
 
 
 
 
 
c623cf2
d4c16ef
ce069d1
304d9f9
 
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
122
123
# modules/chatbot/sidebar_chat.py
import streamlit as st
from .chat_process import ChatProcessor
from ..database.chat_mongo_db import store_chat_history
import logging

logger = logging.getLogger(__name__)

def display_sidebar_chat(lang_code: str, chatbot_t: dict):
    """Chatbot mejorado con manejo completo del contexto semántico"""
    with st.sidebar:
        # Configuración de estilos
        st.markdown("""
        <style>
            .chat-container {
                max-height: 60vh;
                overflow-y: auto;
                padding: 10px;
            }
            .chat-message { margin-bottom: 15px; }
        </style>
        """, unsafe_allow_html=True)

        try:
            # Inicialización del procesador
            if 'chat_processor' not in st.session_state:
                st.session_state.chat_processor = ChatProcessor()
                logger.info("Nuevo ChatProcessor inicializado")

            # 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 and all(k in semantic_data for k in ['text', 'metrics']):
                    try:
                        st.session_state.chat_processor.set_semantic_context(
                            text=semantic_data['text'],
                            metrics=semantic_data['metrics'],
                            graph_data=semantic_data.get('graph_data'),
                            lang_code=lang_code
                        )
                        logger.info("Contexto semántico configurado en el chat")
                    except Exception as e:
                        logger.error(f"Error configurando contexto: {str(e)}")
                        st.error("Error al configurar el análisis. Recargue el documento.")
                        return

            # Interfaz del chat
            with st.expander("💬 Asistente de Análisis", expanded=True):
                # Inicializar historial si no existe
                if 'sidebar_messages' not in st.session_state:
                    initial_msg = {
                        'en': "Hello! Ask me about the semantic analysis.",
                        'es': "¡Hola! Pregúntame sobre el análisis semántico.",
                        'pt': "Olá! Pergunte-me sobre a análise semântica."
                    }.get(lang_code, "Hello!")
                    
                    st.session_state.sidebar_messages = [
                        {"role": "assistant", "content": initial_msg}
                    ]

                # Mostrar historial
                chat_container = st.container()
                with chat_container:
                    for msg in st.session_state.sidebar_messages:
                        st.chat_message(msg["role"]).write(msg["content"])

                # Manejo de mensajes nuevos
                user_input = st.chat_input(
                    {
                        'en': "Ask about the analysis...",
                        'es': "Pregunta sobre el análisis...",
                        'pt': "Pergunte sobre a análise..."
                    }.get(lang_code, "Message...")
                )

                if user_input:
                    try:
                        # Mostrar mensaje del usuario
                        with chat_container:
                            st.chat_message("user").write(user_input)
                            st.session_state.sidebar_messages.append(
                                {"role": "user", "content": user_input}
                            )

                            # Obtener y mostrar respuesta
                            with st.chat_message("assistant"):
                                response = st.write_stream(
                                    st.session_state.chat_processor.process_chat_input(
                                        user_input, lang_code
                                    )
                                )
                                st.session_state.sidebar_messages.append(
                                    {"role": "assistant", "content": response.replace("▌", "")}
                                )

                        # Guardar en base de datos
                        if 'username' in st.session_state:
                            store_chat_history(
                                username=st.session_state.username,
                                messages=st.session_state.sidebar_messages,
                                chat_type='semantic_analysis',
                                metadata={
                                    'text_sample': st.session_state.semantic_agent_data['text'][:500],
                                    'concepts': st.session_state.semantic_agent_data['metrics']['key_concepts'][:5]
                                }
                            )
                            
                    except Exception as e:
                        logger.error(f"Error en conversación: {str(e)}", exc_info=True)
                        st.error({
                            'en': "Error processing request. Try again.",
                            'es': "Error al procesar. Intente nuevamente.",
                            'pt': "Erro ao processar. Tente novamente."
                        }.get(lang_code, "Error"))

                # Botón para reiniciar
                if st.button("🔄 Reiniciar Chat"):
                    st.session_state.sidebar_messages = []
                    st.rerun()

        except Exception as e:
            logger.error(f"Error fatal en sidebar_chat: {str(e)}", exc_info=True)
            st.error("System error. Please refresh the page.")