Spaces:
Running
Running
Update modules/chatbot/sidebar_chat.py
Browse files- modules/chatbot/sidebar_chat.py +53 -94
modules/chatbot/sidebar_chat.py
CHANGED
@@ -8,35 +8,20 @@ logger = logging.getLogger(__name__)
|
|
8 |
|
9 |
def display_sidebar_chat(lang_code: str, chatbot_t: dict):
|
10 |
"""
|
11 |
-
Muestra el chatbot en el sidebar
|
12 |
-
Args:
|
13 |
-
lang_code: Código del idioma
|
14 |
-
chatbot_t: Diccionario de traducciones del chatbot
|
15 |
"""
|
16 |
-
|
17 |
-
# Asegurar que tenemos las traducciones necesarias
|
18 |
-
default_translations = {
|
19 |
-
'error_message': 'An error occurred',
|
20 |
-
'expand_chat': 'Open Assistant',
|
21 |
-
'initial_message': 'Hi! How can I help?',
|
22 |
-
'input_placeholder': 'Type your message...',
|
23 |
-
'clear_chat': 'Clear chat'
|
24 |
-
}
|
25 |
-
|
26 |
-
# Combinar traducciones por defecto con las proporcionadas
|
27 |
-
translations = {**default_translations, **chatbot_t}
|
28 |
-
|
29 |
with st.sidebar:
|
|
|
30 |
st.markdown("""
|
31 |
<style>
|
32 |
-
/* Contenedor
|
33 |
div[data-testid="stExpanderContent"] > div {
|
34 |
max-height: 60vh;
|
35 |
overflow-y: auto;
|
36 |
padding-right: 10px;
|
37 |
}
|
38 |
|
39 |
-
/*
|
40 |
div[data-testid="stHorizontalBlock"]:has(> div[data-testid="column"]) {
|
41 |
position: sticky;
|
42 |
bottom: 0;
|
@@ -44,118 +29,92 @@ def display_sidebar_chat(lang_code: str, chatbot_t: dict):
|
|
44 |
padding-top: 10px;
|
45 |
z-index: 100;
|
46 |
}
|
47 |
-
|
48 |
-
/* Asegura que el expander no afecte el layout */
|
49 |
-
section[data-testid="stSidebar"] > div {
|
50 |
-
overflow: visible !important;
|
51 |
-
}
|
52 |
</style>
|
53 |
""", unsafe_allow_html=True)
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
semantic_context = st.session_state.get('semantic_agent_data')
|
59 |
-
|
60 |
-
# Inicializar el chat con contexto especializado si existe
|
61 |
-
if semantic_context and 'chat_processor' in st.session_state:
|
62 |
-
st.session_state.chat_processor.set_semantic_context(
|
63 |
-
text=semantic_context['text'],
|
64 |
-
metrics=semantic_context['metrics'],
|
65 |
-
graph_data=semantic_context['graph_data']
|
66 |
-
)
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
{"role": "assistant", "content": initial_message}
|
82 |
-
]
|
83 |
-
|
84 |
-
except Exception as e:
|
85 |
-
logger.error(f"Error inicializando ChatProcessor con contexto semántico: {str(e)}")
|
86 |
-
st.error("Error: No se pudo inicializar el chat especializado.")
|
87 |
-
return
|
88 |
-
|
89 |
-
# Inicializar mensajes si no existen
|
90 |
if 'sidebar_messages' not in st.session_state:
|
91 |
-
#
|
92 |
-
|
93 |
-
|
94 |
-
if
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
except Exception as e:
|
101 |
-
logger.error(f"Error recuperando historial: {str(e)}")
|
102 |
-
st.session_state.sidebar_messages = [
|
103 |
-
{"role": "assistant", "content": translations['initial_message']}
|
104 |
-
]
|
105 |
|
106 |
-
#
|
107 |
chat_container = st.container()
|
108 |
-
|
109 |
-
# Mostrar mensajes existentes
|
110 |
with chat_container:
|
111 |
for message in st.session_state.sidebar_messages:
|
112 |
with st.chat_message(message["role"]):
|
113 |
st.markdown(message["content"])
|
114 |
|
115 |
# Input del usuario
|
116 |
-
user_input = st.
|
117 |
-
translations['input_placeholder'],
|
118 |
-
key='sidebar_chat_input'
|
119 |
-
)
|
120 |
|
121 |
if user_input:
|
122 |
# Agregar mensaje del usuario
|
123 |
st.session_state.sidebar_messages.append(
|
124 |
{"role": "user", "content": user_input}
|
125 |
)
|
126 |
-
|
127 |
-
#
|
128 |
with chat_container:
|
|
|
|
|
|
|
|
|
129 |
with st.chat_message("assistant"):
|
130 |
-
|
131 |
full_response = ""
|
132 |
-
|
|
|
133 |
for chunk in st.session_state.chat_processor.process_chat_input(
|
134 |
-
user_input,
|
135 |
lang_code
|
136 |
):
|
137 |
full_response += chunk
|
138 |
-
|
|
|
|
|
139 |
|
140 |
# Guardar respuesta
|
141 |
st.session_state.sidebar_messages.append(
|
142 |
-
{"role": "assistant", "content": full_response
|
143 |
)
|
144 |
-
|
145 |
-
#
|
146 |
store_chat_history(
|
147 |
username=st.session_state.username,
|
148 |
messages=st.session_state.sidebar_messages,
|
149 |
-
|
150 |
)
|
151 |
|
152 |
-
# Botón para limpiar chat
|
153 |
-
if st.button(
|
154 |
st.session_state.sidebar_messages = [
|
155 |
-
{"role": "assistant", "content":
|
156 |
]
|
157 |
st.rerun()
|
158 |
|
159 |
except Exception as e:
|
160 |
-
logger.error(f"Error en
|
161 |
-
st.error(
|
|
|
8 |
|
9 |
def display_sidebar_chat(lang_code: str, chatbot_t: dict):
|
10 |
"""
|
11 |
+
Muestra el chatbot en el sidebar con soporte para contexto semántico
|
|
|
|
|
|
|
12 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
with st.sidebar:
|
14 |
+
# Estilos CSS para el chat
|
15 |
st.markdown("""
|
16 |
<style>
|
17 |
+
/* Contenedor del chat con scroll */
|
18 |
div[data-testid="stExpanderContent"] > div {
|
19 |
max-height: 60vh;
|
20 |
overflow-y: auto;
|
21 |
padding-right: 10px;
|
22 |
}
|
23 |
|
24 |
+
/* Input fijo en la parte inferior */
|
25 |
div[data-testid="stHorizontalBlock"]:has(> div[data-testid="column"]) {
|
26 |
position: sticky;
|
27 |
bottom: 0;
|
|
|
29 |
padding-top: 10px;
|
30 |
z-index: 100;
|
31 |
}
|
|
|
|
|
|
|
|
|
|
|
32 |
</style>
|
33 |
""", unsafe_allow_html=True)
|
34 |
|
35 |
+
# Inicializar el procesador de chat si no existe
|
36 |
+
if 'chat_processor' not in st.session_state:
|
37 |
+
st.session_state.chat_processor = ChatProcessor()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
+
# Configurar contexto semántico si está activo
|
40 |
+
if st.session_state.get('semantic_agent_active', False):
|
41 |
+
semantic_data = st.session_state.get('semantic_agent_data')
|
42 |
+
if semantic_data:
|
43 |
+
st.session_state.chat_processor.set_semantic_context(
|
44 |
+
text=semantic_data['text'],
|
45 |
+
metrics=semantic_data['metrics'],
|
46 |
+
graph_data=semantic_data['graph_data']
|
47 |
+
)
|
48 |
+
|
49 |
+
with st.expander("💬 Asistente Virtual", expanded=True):
|
50 |
+
try:
|
51 |
+
# Inicializar mensajes del chat
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
if 'sidebar_messages' not in st.session_state:
|
53 |
+
# Mensaje inicial según el modo (normal o semántico)
|
54 |
+
initial_message = (
|
55 |
+
"¡Hola! Soy tu asistente de análisis semántico. ¿En qué puedo ayudarte?"
|
56 |
+
if st.session_state.get('semantic_agent_active', False)
|
57 |
+
else "¡Hola! ¿Cómo puedo ayudarte hoy?"
|
58 |
+
)
|
59 |
+
st.session_state.sidebar_messages = [
|
60 |
+
{"role": "assistant", "content": initial_message}
|
61 |
+
]
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
+
# Mostrar historial del chat
|
64 |
chat_container = st.container()
|
|
|
|
|
65 |
with chat_container:
|
66 |
for message in st.session_state.sidebar_messages:
|
67 |
with st.chat_message(message["role"]):
|
68 |
st.markdown(message["content"])
|
69 |
|
70 |
# Input del usuario
|
71 |
+
user_input = st.chat_input("Escribe tu mensaje...")
|
|
|
|
|
|
|
72 |
|
73 |
if user_input:
|
74 |
# Agregar mensaje del usuario
|
75 |
st.session_state.sidebar_messages.append(
|
76 |
{"role": "user", "content": user_input}
|
77 |
)
|
78 |
+
|
79 |
+
# Mostrar mensaje del usuario
|
80 |
with chat_container:
|
81 |
+
with st.chat_message("user"):
|
82 |
+
st.markdown(user_input)
|
83 |
+
|
84 |
+
# Mostrar respuesta del asistente
|
85 |
with st.chat_message("assistant"):
|
86 |
+
response_placeholder = st.empty()
|
87 |
full_response = ""
|
88 |
+
|
89 |
+
# Obtener respuesta del procesador
|
90 |
for chunk in st.session_state.chat_processor.process_chat_input(
|
91 |
+
user_input,
|
92 |
lang_code
|
93 |
):
|
94 |
full_response += chunk
|
95 |
+
response_placeholder.markdown(full_response + "▌")
|
96 |
+
|
97 |
+
response_placeholder.markdown(full_response)
|
98 |
|
99 |
# Guardar respuesta
|
100 |
st.session_state.sidebar_messages.append(
|
101 |
+
{"role": "assistant", "content": full_response}
|
102 |
)
|
103 |
+
|
104 |
+
# Guardar en base de datos
|
105 |
store_chat_history(
|
106 |
username=st.session_state.username,
|
107 |
messages=st.session_state.sidebar_messages,
|
108 |
+
chat_type='semantic' if st.session_state.get('semantic_agent_active') else 'general'
|
109 |
)
|
110 |
|
111 |
+
# Botón para limpiar el chat
|
112 |
+
if st.button("🔄 Limpiar conversación"):
|
113 |
st.session_state.sidebar_messages = [
|
114 |
+
{"role": "assistant", "content": "¡Hola! ¿En qué puedo ayudarte?"}
|
115 |
]
|
116 |
st.rerun()
|
117 |
|
118 |
except Exception as e:
|
119 |
+
logger.error(f"Error en el chat: {str(e)}")
|
120 |
+
st.error("Ocurrió un error en el chat. Por favor, inténtalo de nuevo.")
|