AIdeaText commited on
Commit
c623cf2
1 Parent(s): bef9637

Update modules/chatbot/sidebar_chat.py

Browse files
Files changed (1) hide show
  1. modules/chatbot/sidebar_chat.py +75 -87
modules/chatbot/sidebar_chat.py CHANGED
@@ -1,105 +1,93 @@
1
  # modules/chatbot/sidebar_chat.py
 
2
  import streamlit as st
3
- from .chatbot import ClaudeAPIChat, initialize_chatbot, get_chatbot_response
4
- from ..database.chat_mongo_db import store_chat_history, get_chat_history
5
  import logging
6
 
7
  logger = logging.getLogger(__name__)
8
 
9
- def display_sidebar_chat(lang_code):
10
  """
11
  Muestra el chatbot en el sidebar
 
 
 
12
  """
13
- translations = {
14
- 'es': {
15
- 'chat_title': "Asistente AIdeaText",
16
- 'input_placeholder': "¿Tienes alguna pregunta?",
17
- 'initial_message': "¡Hola! Soy tu asistente. ¿En qué puedo ayudarte?",
18
- 'expand_chat': "Abrir asistente",
19
- 'clear_chat': "Limpiar chat"
20
- },
21
- 'en': {
22
- 'chat_title': "AIdeaText Assistant",
23
- 'input_placeholder': "Any questions?",
24
- 'initial_message': "Hi! I'm your assistant. How can I help?",
25
- 'expand_chat': "Open assistant",
26
- 'clear_chat': "Clear chat"
27
- }
28
- }
29
-
30
- t = translations.get(lang_code, translations['en'])
31
-
32
  with st.sidebar:
33
  # Chatbot expandible
34
- with st.expander(t['expand_chat'], expanded=False):
35
- # Inicializar chatbot si no existe
36
- if 'sidebar_chatbot' not in st.session_state:
37
- st.session_state.sidebar_chatbot = initialize_chatbot()
 
38
 
39
- # Inicializar mensajes si no existen
40
- if 'sidebar_messages' not in st.session_state:
41
- # Intentar recuperar historial previo
42
- history = get_chat_history(st.session_state.username, 'sidebar', 10)
43
- if history:
44
- st.session_state.sidebar_messages = history[0]['messages']
45
- else:
46
- st.session_state.sidebar_messages = [
47
- {"role": "assistant", "content": t['initial_message']}
48
- ]
49
 
50
- # Contenedor del chat
51
- chat_container = st.container()
52
 
53
- # Mostrar mensajes
54
- with chat_container:
55
- for message in st.session_state.sidebar_messages:
56
- with st.chat_message(message["role"]):
57
- st.markdown(message["content"])
58
-
59
- # Input del usuario
60
- user_input = st.text_input(
61
- t['input_placeholder'],
62
- key='sidebar_chat_input'
63
- )
64
 
65
- # Procesar input
66
- if user_input:
67
- # Agregar mensaje del usuario
68
- st.session_state.sidebar_messages.append(
69
- {"role": "user", "content": user_input}
70
  )
71
 
72
- # Generar y mostrar respuesta
73
- with chat_container:
74
- with st.chat_message("assistant"):
75
- message_placeholder = st.empty()
76
- full_response = ""
77
-
78
- for chunk in get_chatbot_response(
79
- st.session_state.sidebar_chatbot,
80
- user_input,
81
- lang_code
82
- ):
83
- full_response += chunk
84
- message_placeholder.markdown(full_response + "▌")
85
-
86
- message_placeholder.markdown(full_response)
87
-
88
- # Guardar respuesta
89
- st.session_state.sidebar_messages.append(
90
- {"role": "assistant", "content": full_response}
91
- )
92
-
93
- # Guardar conversación
94
- store_chat_history(
95
- st.session_state.username,
96
- 'sidebar',
97
- st.session_state.sidebar_messages
98
- )
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- # Botón para limpiar chat
101
- if st.button(t['clear_chat']):
102
- st.session_state.sidebar_messages = [
103
- {"role": "assistant", "content": t['initial_message']}
104
- ]
105
- st.rerun()
 
1
  # modules/chatbot/sidebar_chat.py
2
+ # modules/chatbot/chatbot/sidebar_chat.py
3
  import streamlit as st
4
+ from .chat_process import ChatProcessor
5
+ from ...database.chat_mongo_db import store_chat_history, get_chat_history
6
  import logging
7
 
8
  logger = logging.getLogger(__name__)
9
 
10
+ def display_sidebar_chat(lang_code: str, chatbot_t: dict):
11
  """
12
  Muestra el chatbot en el sidebar
13
+ Args:
14
+ lang_code: Código del idioma
15
+ chatbot_t: Traducciones del chatbot del archivo central
16
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  with st.sidebar:
18
  # Chatbot expandible
19
+ with st.expander(chatbot_t.get('expand_chat', 'Open assistant'), expanded=False):
20
+ try:
21
+ # Inicializar procesador si no existe
22
+ if 'chat_processor' not in st.session_state:
23
+ st.session_state.chat_processor = ChatProcessor()
24
 
25
+ # Inicializar mensajes si no existen
26
+ if 'sidebar_messages' not in st.session_state:
27
+ # Intentar recuperar historial previo
28
+ history = get_chat_history(st.session_state.username, 'sidebar', 10)
29
+ if history:
30
+ st.session_state.sidebar_messages = history[0]['messages']
31
+ else:
32
+ st.session_state.sidebar_messages = [
33
+ {"role": "assistant", "content": chatbot_t['initial_message']}
34
+ ]
35
 
36
+ # Contenedor del chat
37
+ chat_container = st.container()
38
 
39
+ # Mostrar mensajes existentes
40
+ with chat_container:
41
+ for message in st.session_state.sidebar_messages:
42
+ with st.chat_message(message["role"]):
43
+ st.markdown(message["content"])
 
 
 
 
 
 
44
 
45
+ # Input del usuario
46
+ user_input = st.text_input(
47
+ chatbot_t['input_placeholder'],
48
+ key='sidebar_chat_input'
 
49
  )
50
 
51
+ if user_input:
52
+ # Agregar mensaje del usuario
53
+ st.session_state.sidebar_messages.append(
54
+ {"role": "user", "content": user_input}
55
+ )
56
+
57
+ # Generar y mostrar respuesta
58
+ with chat_container:
59
+ with st.chat_message("assistant"):
60
+ message_placeholder = st.empty()
61
+ full_response = ""
62
+
63
+ for chunk in st.session_state.chat_processor.process_chat_input(
64
+ user_input,
65
+ lang_code
66
+ ):
67
+ full_response += chunk
68
+ message_placeholder.markdown(full_response + "▌")
69
+
70
+ message_placeholder.markdown(full_response)
71
+
72
+ # Guardar respuesta
73
+ st.session_state.sidebar_messages.append(
74
+ {"role": "assistant", "content": full_response}
75
+ )
76
+
77
+ # Guardar conversación
78
+ store_chat_history(
79
+ st.session_state.username,
80
+ 'sidebar',
81
+ st.session_state.sidebar_messages
82
+ )
83
+
84
+ # Botón para limpiar chat
85
+ if st.button(chatbot_t['clear_chat']):
86
+ st.session_state.sidebar_messages = [
87
+ {"role": "assistant", "content": chatbot_t['initial_message']}
88
+ ]
89
+ st.rerun()
90
 
91
+ except Exception as e:
92
+ logger.error(f"Error en sidebar chat: {str(e)}")
93
+ st.error(chatbot_t['error_message'])