Spaces:
Running
Running
File size: 7,793 Bytes
d4c16ef 9e1b438 cedddd0 d4c16ef c623cf2 d4c16ef 4d1c5f5 d4c16ef ce069d1 4d1c5f5 9a3bdf2 ce069d1 9a3bdf2 ce069d1 9a3bdf2 ce069d1 4d1c5f5 ce069d1 4d1c5f5 c623cf2 ce069d1 4d1c5f5 ce069d1 d4c16ef ce069d1 c623cf2 d4c16ef c623cf2 ce069d1 d4c16ef c623cf2 ce069d1 4d1c5f5 ce069d1 c623cf2 4d1c5f5 ce069d1 c623cf2 ce069d1 d4c16ef ce069d1 |
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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
# 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 con soporte para contexto semántico
"""
with st.sidebar:
# Configurar logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Estilos CSS para el chat
st.markdown("""
<style>
.chat-container {
max-height: 60vh;
overflow-y: auto;
padding-right: 10px;
}
.chat-input {
position: sticky;
bottom: 0;
background: white;
padding-top: 10px;
z-index: 100;
}
</style>
""", unsafe_allow_html=True)
try:
# Inicializar el procesador de chat si no existe
if 'chat_processor' not in st.session_state:
st.session_state.chat_processor = ChatProcessor()
logger.info("ChatProcessor initialized")
# 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:
st.session_state.chat_processor.set_semantic_context(
text=semantic_data['text'],
metrics=semantic_data['metrics'],
graph_data=semantic_data['graph_data'],
lang_code=lang_code # Pasar el idioma actual
)
logger.info(f"Semantic context set for language: {lang_code}")
with st.expander("💬 Asistente Virtual", expanded=True):
# Inicializar mensajes del chat
if 'sidebar_messages' not in st.session_state:
initial_messages = {
'en': "Hello! How can I help you today?",
'es': "¡Hola! ¿Cómo puedo ayudarte hoy?",
'pt': "Olá! Como posso ajudar você hoje?",
'fr': "Bonjour ! Comment puis-je vous aider aujourd'hui ?"
}
initial_message = initial_messages.get(lang_code, initial_messages['en'])
st.session_state.sidebar_messages = [
{"role": "assistant", "content": initial_message}
]
logger.info("Chat messages initialized")
# Contenedor del chat
chat_container = st.container()
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.chat_input(
{
'en': "Type your message...",
'es': "Escribe tu mensaje...",
'pt': "Digite sua mensagem...",
'fr': "Tapez votre message..."
}.get(lang_code, "Type your message...")
)
if user_input:
try:
# Agregar mensaje del usuario
st.session_state.sidebar_messages.append(
{"role": "user", "content": user_input}
)
logger.info(f"User message received: {user_input[:50]}...")
# Mostrar mensaje del usuario
with chat_container:
with st.chat_message("user"):
st.markdown(user_input)
# Mostrar respuesta del asistente
with st.chat_message("assistant"):
response_placeholder = st.empty()
full_response = ""
# Obtener respuesta del procesador
for chunk in st.session_state.chat_processor.process_chat_input(
user_input,
lang_code
):
full_response += chunk
response_placeholder.markdown(full_response + "▌")
response_placeholder.markdown(full_response)
logger.info(f"Assistant response generated: {full_response[:50]}...")
# Guardar respuesta
st.session_state.sidebar_messages.append(
{"role": "assistant", "content": full_response}
)
# Guardar en base de datos
store_chat_history(
username=st.session_state.username,
messages=st.session_state.sidebar_messages,
chat_type='semantic' if st.session_state.get('semantic_agent_active') else 'general'
)
logger.info("Conversation saved to database")
except Exception as e:
logger.error(f"Error processing user input: {str(e)}", exc_info=True)
st.error({
'en': "Error processing message. Please try again.",
'es': "Error al procesar el mensaje. Por favor, inténtalo de nuevo.",
'pt': "Erro ao processar a mensagem. Por favor, tente novamente.",
'fr': "Erreur lors du traitement du message. Veuillez réessayer."
}.get(lang_code, "Error processing message."))
# Botón para limpiar el chat
if st.button({
'en': "🔄 Clear conversation",
'es': "🔄 Limpiar conversación",
'pt': "🔄 Limpar conversa",
'fr': "🔄 Effacer la conversation"
}.get(lang_code, "🔄 Clear")):
st.session_state.sidebar_messages = [{
"role": "assistant",
"content": {
'en': "Hello! How can I help you today?",
'es': "¡Hola! ¿Cómo puedo ayudarte hoy?",
'pt': "Olá! Como posso ajudar você hoje?",
'fr': "Bonjour ! Comment puis-je vous aider aujourd'hui ?"
}.get(lang_code, "Hello! How can I help you?")
}]
st.rerun()
logger.info("Conversation cleared")
except Exception as e:
logger.error(f"Error in sidebar chat: {str(e)}", exc_info=True)
st.error({
'en': "An error occurred in the chat. Please try again.",
'es': "Ocurrió un error en el chat. Por favor, inténtalo de nuevo.",
'pt': "Ocorreu um erro no chat. Por favor, tente novamente.",
'fr': "Une erreur s'est produite dans le chat. Veuillez réessayer."
}.get(lang_code, "Chat error occurred.")) |