Spaces:
Running
Running
Update modules/chatbot/sidebar_chat.py
Browse files- modules/chatbot/sidebar_chat.py +116 -70
modules/chatbot/sidebar_chat.py
CHANGED
|
@@ -11,18 +11,21 @@ def display_sidebar_chat(lang_code: str, chatbot_t: dict):
|
|
| 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 |
-
|
| 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;
|
| 28 |
background: white;
|
|
@@ -32,35 +35,41 @@ def display_sidebar_chat(lang_code: str, chatbot_t: dict):
|
|
| 32 |
</style>
|
| 33 |
""", unsafe_allow_html=True)
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
st.session_state
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
if
|
| 43 |
-
st.session_state.
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
-
try:
|
| 51 |
# Inicializar mensajes del chat
|
| 52 |
if 'sidebar_messages' not in st.session_state:
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
"¡Hola!
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
| 59 |
st.session_state.sidebar_messages = [
|
| 60 |
{"role": "assistant", "content": initial_message}
|
| 61 |
]
|
|
|
|
| 62 |
|
| 63 |
-
#
|
| 64 |
chat_container = st.container()
|
| 65 |
with chat_container:
|
| 66 |
for message in st.session_state.sidebar_messages:
|
|
@@ -68,53 +77,90 @@ def display_sidebar_chat(lang_code: str, chatbot_t: dict):
|
|
| 68 |
st.markdown(message["content"])
|
| 69 |
|
| 70 |
# Input del usuario
|
| 71 |
-
user_input = st.chat_input(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
if user_input:
|
| 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 |
# Botón para limpiar el chat
|
| 112 |
-
if st.button(
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
st.rerun()
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
Muestra el chatbot en el sidebar con soporte para contexto semántico
|
| 12 |
"""
|
| 13 |
with st.sidebar:
|
| 14 |
+
# Configurar logging
|
| 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-right: 10px;
|
| 27 |
}
|
| 28 |
+
.chat-input {
|
|
|
|
|
|
|
| 29 |
position: sticky;
|
| 30 |
bottom: 0;
|
| 31 |
background: white;
|
|
|
|
| 35 |
</style>
|
| 36 |
""", unsafe_allow_html=True)
|
| 37 |
|
| 38 |
+
try:
|
| 39 |
+
# Inicializar el procesador de chat si no existe
|
| 40 |
+
if 'chat_processor' not in st.session_state:
|
| 41 |
+
st.session_state.chat_processor = ChatProcessor()
|
| 42 |
+
logger.info("ChatProcessor initialized")
|
| 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 |
+
st.session_state.chat_processor.set_semantic_context(
|
| 49 |
+
text=semantic_data['text'],
|
| 50 |
+
metrics=semantic_data['metrics'],
|
| 51 |
+
graph_data=semantic_data['graph_data'],
|
| 52 |
+
lang_code=lang_code # Pasar el idioma actual
|
| 53 |
+
)
|
| 54 |
+
logger.info(f"Semantic context set for language: {lang_code}")
|
| 55 |
|
| 56 |
+
with st.expander("💬 Asistente Virtual", expanded=True):
|
|
|
|
| 57 |
# Inicializar mensajes del chat
|
| 58 |
if 'sidebar_messages' not in st.session_state:
|
| 59 |
+
initial_messages = {
|
| 60 |
+
'en': "Hello! How can I help you today?",
|
| 61 |
+
'es': "¡Hola! ¿Cómo puedo ayudarte hoy?",
|
| 62 |
+
'pt': "Olá! Como posso ajudar você hoje?",
|
| 63 |
+
'fr': "Bonjour ! Comment puis-je vous aider aujourd'hui ?"
|
| 64 |
+
}
|
| 65 |
+
initial_message = initial_messages.get(lang_code, initial_messages['en'])
|
| 66 |
+
|
| 67 |
st.session_state.sidebar_messages = [
|
| 68 |
{"role": "assistant", "content": initial_message}
|
| 69 |
]
|
| 70 |
+
logger.info("Chat messages initialized")
|
| 71 |
|
| 72 |
+
# Contenedor del chat
|
| 73 |
chat_container = st.container()
|
| 74 |
with chat_container:
|
| 75 |
for message in st.session_state.sidebar_messages:
|
|
|
|
| 77 |
st.markdown(message["content"])
|
| 78 |
|
| 79 |
# Input del usuario
|
| 80 |
+
user_input = st.chat_input(
|
| 81 |
+
{
|
| 82 |
+
'en': "Type your message...",
|
| 83 |
+
'es': "Escribe tu mensaje...",
|
| 84 |
+
'pt': "Digite sua mensagem...",
|
| 85 |
+
'fr': "Tapez votre message..."
|
| 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 |
+
with st.chat_message("user"):
|
| 100 |
+
st.markdown(user_input)
|
| 101 |
+
|
| 102 |
+
# Mostrar respuesta del asistente
|
| 103 |
+
with st.chat_message("assistant"):
|
| 104 |
+
response_placeholder = st.empty()
|
| 105 |
+
full_response = ""
|
| 106 |
+
|
| 107 |
+
# Obtener respuesta del procesador
|
| 108 |
+
for chunk in st.session_state.chat_processor.process_chat_input(
|
| 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": full_response}
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# Guardar en base de datos
|
| 124 |
+
store_chat_history(
|
| 125 |
+
username=st.session_state.username,
|
| 126 |
+
messages=st.session_state.sidebar_messages,
|
| 127 |
+
chat_type='semantic' if st.session_state.get('semantic_agent_active') else 'general'
|
| 128 |
+
)
|
| 129 |
+
logger.info("Conversation saved to database")
|
| 130 |
+
|
| 131 |
+
except Exception as e:
|
| 132 |
+
logger.error(f"Error processing user input: {str(e)}", exc_info=True)
|
| 133 |
+
st.error({
|
| 134 |
+
'en': "Error processing message. Please try again.",
|
| 135 |
+
'es': "Error al procesar el mensaje. Por favor, inténtalo de nuevo.",
|
| 136 |
+
'pt': "Erro ao processar a mensagem. Por favor, tente novamente.",
|
| 137 |
+
'fr': "Erreur lors du traitement du message. Veuillez réessayer."
|
| 138 |
+
}.get(lang_code, "Error processing message."))
|
| 139 |
|
| 140 |
# Botón para limpiar el chat
|
| 141 |
+
if st.button({
|
| 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 in sidebar chat: {str(e)}", exc_info=True)
|
| 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."))
|