AIdeaText commited on
Commit
ce069d1
·
verified ·
1 Parent(s): d1b4d8d

Update modules/chatbot/sidebar_chat.py

Browse files
Files changed (1) hide show
  1. 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
- /* 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;
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
- # 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:
@@ -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("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.")
 
 
 
 
 
 
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."))