Spaces:
Running
Running
Update modules/chatbot/sidebar_chat.py
Browse files- modules/chatbot/sidebar_chat.py +70 -113
modules/chatbot/sidebar_chat.py
CHANGED
@@ -1,166 +1,123 @@
|
|
1 |
# modules/chatbot/sidebar_chat.py
|
2 |
import streamlit as st
|
3 |
from .chat_process import ChatProcessor
|
4 |
-
from ..database.chat_mongo_db import store_chat_history
|
5 |
import logging
|
6 |
|
7 |
logger = logging.getLogger(__name__)
|
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 |
-
#
|
15 |
-
logging.basicConfig(
|
16 |
-
level=logging.INFO,
|
17 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
18 |
-
)
|
19 |
-
|
20 |
-
# Estilos CSS para el chat
|
21 |
st.markdown("""
|
22 |
<style>
|
23 |
.chat-container {
|
24 |
max-height: 60vh;
|
25 |
overflow-y: auto;
|
26 |
-
padding
|
27 |
-
}
|
28 |
-
.chat-input {
|
29 |
-
position: sticky;
|
30 |
-
bottom: 0;
|
31 |
-
background: white;
|
32 |
-
padding-top: 10px;
|
33 |
-
z-index: 100;
|
34 |
}
|
|
|
35 |
</style>
|
36 |
""", unsafe_allow_html=True)
|
37 |
|
38 |
try:
|
39 |
-
#
|
40 |
if 'chat_processor' not in st.session_state:
|
41 |
st.session_state.chat_processor = ChatProcessor()
|
42 |
-
logger.info("ChatProcessor
|
43 |
|
44 |
# Configurar contexto semántico si está activo
|
45 |
if st.session_state.get('semantic_agent_active', False):
|
46 |
semantic_data = st.session_state.get('semantic_agent_data')
|
47 |
-
if semantic_data:
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
-
|
57 |
-
|
|
|
58 |
if 'sidebar_messages' not in st.session_state:
|
59 |
-
|
60 |
-
'en': "Hello!
|
61 |
-
'es': "¡Hola!
|
62 |
-
'pt': "Olá!
|
63 |
-
|
64 |
-
}
|
65 |
-
initial_message = initial_messages.get(lang_code, initial_messages['en'])
|
66 |
|
67 |
st.session_state.sidebar_messages = [
|
68 |
-
{"role": "assistant", "content":
|
69 |
]
|
70 |
-
logger.info("Chat messages initialized")
|
71 |
|
72 |
-
#
|
73 |
chat_container = st.container()
|
74 |
with chat_container:
|
75 |
-
for
|
76 |
-
|
77 |
-
st.markdown(message["content"])
|
78 |
|
79 |
-
#
|
80 |
user_input = st.chat_input(
|
81 |
{
|
82 |
-
'en': "
|
83 |
-
'es': "
|
84 |
-
'pt': "
|
85 |
-
|
86 |
-
}.get(lang_code, "Type your message...")
|
87 |
)
|
88 |
|
89 |
if user_input:
|
90 |
try:
|
91 |
-
# Agregar mensaje del usuario
|
92 |
-
st.session_state.sidebar_messages.append(
|
93 |
-
{"role": "user", "content": user_input}
|
94 |
-
)
|
95 |
-
logger.info(f"User message received: {user_input[:50]}...")
|
96 |
-
|
97 |
# Mostrar mensaje del usuario
|
98 |
with chat_container:
|
99 |
-
|
100 |
-
|
|
|
|
|
101 |
|
102 |
-
#
|
103 |
with st.chat_message("assistant"):
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
user_input,
|
110 |
-
lang_code
|
111 |
-
):
|
112 |
-
full_response += chunk
|
113 |
-
response_placeholder.markdown(full_response + "▌")
|
114 |
-
|
115 |
-
response_placeholder.markdown(full_response)
|
116 |
-
logger.info(f"Assistant response generated: {full_response[:50]}...")
|
117 |
-
|
118 |
-
# Guardar respuesta
|
119 |
st.session_state.sidebar_messages.append(
|
120 |
-
{"role": "assistant", "content":
|
121 |
)
|
122 |
|
123 |
# Guardar en base de datos
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
131 |
except Exception as e:
|
132 |
-
logger.error(f"Error
|
133 |
st.error({
|
134 |
-
'en': "Error processing
|
135 |
-
'es': "Error al procesar
|
136 |
-
'pt': "Erro ao processar
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
'en': "🔄 Clear conversation",
|
143 |
-
'es': "🔄 Limpiar conversación",
|
144 |
-
'pt': "🔄 Limpar conversa",
|
145 |
-
'fr': "🔄 Effacer la conversation"
|
146 |
-
}.get(lang_code, "🔄 Clear")):
|
147 |
-
st.session_state.sidebar_messages = [{
|
148 |
-
"role": "assistant",
|
149 |
-
"content": {
|
150 |
-
'en': "Hello! How can I help you today?",
|
151 |
-
'es': "¡Hola! ¿Cómo puedo ayudarte hoy?",
|
152 |
-
'pt': "Olá! Como posso ajudar você hoje?",
|
153 |
-
'fr': "Bonjour ! Comment puis-je vous aider aujourd'hui ?"
|
154 |
-
}.get(lang_code, "Hello! How can I help you?")
|
155 |
-
}]
|
156 |
st.rerun()
|
157 |
-
logger.info("Conversation cleared")
|
158 |
|
159 |
except Exception as e:
|
160 |
-
logger.error(f"Error
|
161 |
-
st.error(
|
162 |
-
'en': "An error occurred in the chat. Please try again.",
|
163 |
-
'es': "Ocurrió un error en el chat. Por favor, inténtalo de nuevo.",
|
164 |
-
'pt': "Ocorreu um erro no chat. Por favor, tente novamente.",
|
165 |
-
'fr': "Une erreur s'est produite dans le chat. Veuillez réessayer."
|
166 |
-
}.get(lang_code, "Chat error occurred."))
|
|
|
1 |
# modules/chatbot/sidebar_chat.py
|
2 |
import streamlit as st
|
3 |
from .chat_process import ChatProcessor
|
4 |
+
from ..database.chat_mongo_db import store_chat_history
|
5 |
import logging
|
6 |
|
7 |
logger = logging.getLogger(__name__)
|
8 |
|
9 |
def display_sidebar_chat(lang_code: str, chatbot_t: dict):
|
10 |
+
"""Chatbot mejorado con manejo completo del contexto semántico"""
|
|
|
|
|
11 |
with st.sidebar:
|
12 |
+
# Configuración de estilos
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
st.markdown("""
|
14 |
<style>
|
15 |
.chat-container {
|
16 |
max-height: 60vh;
|
17 |
overflow-y: auto;
|
18 |
+
padding: 10px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
}
|
20 |
+
.chat-message { margin-bottom: 15px; }
|
21 |
</style>
|
22 |
""", unsafe_allow_html=True)
|
23 |
|
24 |
try:
|
25 |
+
# Inicialización del procesador
|
26 |
if 'chat_processor' not in st.session_state:
|
27 |
st.session_state.chat_processor = ChatProcessor()
|
28 |
+
logger.info("Nuevo ChatProcessor inicializado")
|
29 |
|
30 |
# Configurar contexto semántico si está activo
|
31 |
if st.session_state.get('semantic_agent_active', False):
|
32 |
semantic_data = st.session_state.get('semantic_agent_data')
|
33 |
+
if semantic_data and all(k in semantic_data for k in ['text', 'metrics']):
|
34 |
+
try:
|
35 |
+
st.session_state.chat_processor.set_semantic_context(
|
36 |
+
text=semantic_data['text'],
|
37 |
+
metrics=semantic_data['metrics'],
|
38 |
+
graph_data=semantic_data.get('graph_data'),
|
39 |
+
lang_code=lang_code
|
40 |
+
)
|
41 |
+
logger.info("Contexto semántico configurado en el chat")
|
42 |
+
except Exception as e:
|
43 |
+
logger.error(f"Error configurando contexto: {str(e)}")
|
44 |
+
st.error("Error al configurar el análisis. Recargue el documento.")
|
45 |
+
return
|
46 |
|
47 |
+
# Interfaz del chat
|
48 |
+
with st.expander("💬 Asistente de Análisis", expanded=True):
|
49 |
+
# Inicializar historial si no existe
|
50 |
if 'sidebar_messages' not in st.session_state:
|
51 |
+
initial_msg = {
|
52 |
+
'en': "Hello! Ask me about the semantic analysis.",
|
53 |
+
'es': "¡Hola! Pregúntame sobre el análisis semántico.",
|
54 |
+
'pt': "Olá! Pergunte-me sobre a análise semântica."
|
55 |
+
}.get(lang_code, "Hello!")
|
|
|
|
|
56 |
|
57 |
st.session_state.sidebar_messages = [
|
58 |
+
{"role": "assistant", "content": initial_msg}
|
59 |
]
|
|
|
60 |
|
61 |
+
# Mostrar historial
|
62 |
chat_container = st.container()
|
63 |
with chat_container:
|
64 |
+
for msg in st.session_state.sidebar_messages:
|
65 |
+
st.chat_message(msg["role"]).write(msg["content"])
|
|
|
66 |
|
67 |
+
# Manejo de mensajes nuevos
|
68 |
user_input = st.chat_input(
|
69 |
{
|
70 |
+
'en': "Ask about the analysis...",
|
71 |
+
'es': "Pregunta sobre el análisis...",
|
72 |
+
'pt': "Pergunte sobre a análise..."
|
73 |
+
}.get(lang_code, "Message...")
|
|
|
74 |
)
|
75 |
|
76 |
if user_input:
|
77 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
# Mostrar mensaje del usuario
|
79 |
with chat_container:
|
80 |
+
st.chat_message("user").write(user_input)
|
81 |
+
st.session_state.sidebar_messages.append(
|
82 |
+
{"role": "user", "content": user_input}
|
83 |
+
)
|
84 |
|
85 |
+
# Obtener y mostrar respuesta
|
86 |
with st.chat_message("assistant"):
|
87 |
+
response = st.write_stream(
|
88 |
+
st.session_state.chat_processor.process_chat_input(
|
89 |
+
user_input, lang_code
|
90 |
+
)
|
91 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
st.session_state.sidebar_messages.append(
|
93 |
+
{"role": "assistant", "content": response.replace("▌", "")}
|
94 |
)
|
95 |
|
96 |
# Guardar en base de datos
|
97 |
+
if 'username' in st.session_state:
|
98 |
+
store_chat_history(
|
99 |
+
username=st.session_state.username,
|
100 |
+
messages=st.session_state.sidebar_messages,
|
101 |
+
chat_type='semantic_analysis',
|
102 |
+
metadata={
|
103 |
+
'text_sample': st.session_state.semantic_agent_data['text'][:500],
|
104 |
+
'concepts': st.session_state.semantic_agent_data['metrics']['key_concepts'][:5]
|
105 |
+
}
|
106 |
+
)
|
107 |
+
|
108 |
except Exception as e:
|
109 |
+
logger.error(f"Error en conversación: {str(e)}", exc_info=True)
|
110 |
st.error({
|
111 |
+
'en': "Error processing request. Try again.",
|
112 |
+
'es': "Error al procesar. Intente nuevamente.",
|
113 |
+
'pt': "Erro ao processar. Tente novamente."
|
114 |
+
}.get(lang_code, "Error"))
|
115 |
+
|
116 |
+
# Botón para reiniciar
|
117 |
+
if st.button("🔄 Reiniciar Chat"):
|
118 |
+
st.session_state.sidebar_messages = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
st.rerun()
|
|
|
120 |
|
121 |
except Exception as e:
|
122 |
+
logger.error(f"Error fatal en sidebar_chat: {str(e)}", exc_info=True)
|
123 |
+
st.error("System error. Please refresh the page.")
|
|
|
|
|
|
|
|
|
|