File size: 6,024 Bytes
d4c16ef
 
9e1b438
cedddd0
d4c16ef
 
 
 
c623cf2
d4c16ef
 
c623cf2
 
9bcf433
d4c16ef
9bcf433
 
 
 
 
 
 
 
 
 
 
 
d4c16ef
9bcf433
c623cf2
2c23a8a
 
 
 
 
9bcf433
 
2c23a8a
 
 
 
 
 
 
 
 
 
 
 
 
 
9bcf433
2c23a8a
 
9bcf433
d4c16ef
c623cf2
 
 
9bcf433
 
 
 
 
 
 
 
 
 
c623cf2
9bcf433
c623cf2
d4c16ef
c623cf2
 
d4c16ef
c623cf2
 
 
 
 
d4c16ef
c623cf2
 
9bcf433
c623cf2
d4c16ef
 
c623cf2
 
 
 
 
edb914b
c623cf2
 
 
 
 
 
 
 
 
 
 
edb914b
c623cf2
 
 
edb914b
c623cf2
edb914b
1b7ac3d
c623cf2
1b7ac3d
 
 
c623cf2
 
 
9bcf433
c623cf2
9bcf433
c623cf2
 
d4c16ef
c623cf2
 
9bcf433
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
124
125
126
127
128
129
# 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
    Args:
        lang_code: Código del idioma
        chatbot_t: Diccionario de traducciones del chatbot
    """
    # Asegurar que tenemos las traducciones necesarias
    default_translations = {
        'error_message': 'An error occurred',
        'expand_chat': 'Open Assistant',
        'initial_message': 'Hi! How can I help?',
        'input_placeholder': 'Type your message...',
        'clear_chat': 'Clear chat'
    }
    
    # Combinar traducciones por defecto con las proporcionadas
    translations = {**default_translations, **chatbot_t}

    with st.sidebar:
        with st.expander(translations['expand_chat'], expanded=False):
            try:
                # Verificar si hay contexto semántico activo
                semantic_context = st.session_state.get('semantic_agent_data')
                
                # Inicializar el chat con contexto especializado si existe
                if semantic_context and 'chat_processor' not in st.session_state:
                    try:
                        st.session_state.chat_processor = ChatProcessor()
                        
                        # Mensaje inicial especializado para análisis semántico
                        initial_message = (
                            f"He analizado tu texto con {len(semantic_context['metrics'].get('key_concepts', []))} conceptos clave. "
                            "¿Qué aspecto te gustaría discutir? Por ejemplo:\n"
                            "- ¿Por qué estos conceptos son los más centrales?\n"
                            "- ¿Qué patrones ves en las relaciones conceptuales?\n"
                            "- ¿Cómo podrías mejorar la estructura del texto?"
                        )
                        
                        st.session_state.sidebar_messages = [
                            {"role": "assistant", "content": initial_message}
                        ]
                        
                    except Exception as e:
                        logger.error(f"Error inicializando ChatProcessor con contexto semántico: {str(e)}")
                        st.error("Error: No se pudo inicializar el chat especializado.")
                        return
                
                # Inicializar mensajes si no existen
                if 'sidebar_messages' not in st.session_state:
                    # Intentar recuperar historial previo
                    try:
                        history = get_chat_history(st.session_state.username, 'sidebar', 10)
                        if history:
                            st.session_state.sidebar_messages = history[0]['messages']
                        else:
                            st.session_state.sidebar_messages = [
                                {"role": "assistant", "content": translations['initial_message']}
                            ]
                    except Exception as e:
                        logger.error(f"Error recuperando historial: {str(e)}")
                        st.session_state.sidebar_messages = [
                            {"role": "assistant", "content": translations['initial_message']}
                        ]

                # Contenedor del chat
                chat_container = st.container()

                # Mostrar mensajes existentes
                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.text_input(
                    translations['input_placeholder'],
                    key='sidebar_chat_input'
                )

                if user_input:
                    # Agregar mensaje del usuario
                    st.session_state.sidebar_messages.append(
                        {"role": "user", "content": user_input}
                    )
                
                    # Generar y mostrar respuesta
                    with chat_container:
                        with st.chat_message("assistant"):
                            message_placeholder = st.empty()
                            full_response = ""
                            
                            for chunk in st.session_state.chat_processor.process_chat_input(
                                user_input,
                                lang_code
                            ):
                                full_response += chunk
                                message_placeholder.markdown(full_response)
                            
                            # Guardar respuesta
                            st.session_state.sidebar_messages.append(
                                {"role": "assistant", "content": full_response.strip()}
                            )
                                    
                    # En la función donde guardamos el chat
                    store_chat_history(
                        username=st.session_state.username,
                        messages=st.session_state.sidebar_messages,
                        analysis_type='sidebar'  # Especificar el tipo
                    )

                # Botón para limpiar chat
                if st.button(translations['clear_chat']):
                    st.session_state.sidebar_messages = [
                        {"role": "assistant", "content": translations['initial_message']}
                    ]
                    st.rerun()

            except Exception as e:
                logger.error(f"Error en sidebar chat: {str(e)}")
                st.error(translations['error_message'])