AIdeaText commited on
Commit
c743fe6
verified
1 Parent(s): 5ee3fd1

Create sidebar_chat-BackUp-19-5-2025.py

Browse files
modules/chatbot/sidebar_chat-BackUp-19-5-2025.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, get_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
12
+ Args:
13
+ lang_code: C贸digo del idioma
14
+ chatbot_t: Diccionario de traducciones del chatbot
15
+ """
16
+ # Asegurar que tenemos las traducciones necesarias
17
+ default_translations = {
18
+ 'error_message': 'An error occurred',
19
+ 'expand_chat': 'Open Assistant',
20
+ 'initial_message': 'Hi! How can I help?',
21
+ 'input_placeholder': 'Type your message...',
22
+ 'clear_chat': 'Clear chat'
23
+ }
24
+
25
+ # Combinar traducciones por defecto con las proporcionadas
26
+ translations = {**default_translations, **chatbot_t}
27
+
28
+ with st.sidebar:
29
+ # Chatbot expandible
30
+ with st.expander(translations['expand_chat'], expanded=False):
31
+ try:
32
+ # Inicializar procesador si no existe
33
+ if 'chat_processor' not in st.session_state:
34
+ try:
35
+ st.session_state.chat_processor = ChatProcessor()
36
+ except Exception as e:
37
+ logger.error(f"Error inicializando ChatProcessor: {str(e)}")
38
+ st.error("Error: No se pudo inicializar el chat. Verifica la configuraci贸n.")
39
+ return
40
+
41
+ # Inicializar mensajes si no existen
42
+ if 'sidebar_messages' not in st.session_state:
43
+ # Intentar recuperar historial previo
44
+ try:
45
+ history = get_chat_history(st.session_state.username, 'sidebar', 10)
46
+ if history:
47
+ st.session_state.sidebar_messages = history[0]['messages']
48
+ else:
49
+ st.session_state.sidebar_messages = [
50
+ {"role": "assistant", "content": translations['initial_message']}
51
+ ]
52
+ except Exception as e:
53
+ logger.error(f"Error recuperando historial: {str(e)}")
54
+ st.session_state.sidebar_messages = [
55
+ {"role": "assistant", "content": translations['initial_message']}
56
+ ]
57
+
58
+ # Contenedor del chat
59
+ chat_container = st.container()
60
+
61
+ # Mostrar mensajes existentes
62
+ with chat_container:
63
+ for message in st.session_state.sidebar_messages:
64
+ with st.chat_message(message["role"]):
65
+ st.markdown(message["content"])
66
+
67
+ # Input del usuario
68
+ user_input = st.text_input(
69
+ translations['input_placeholder'],
70
+ key='sidebar_chat_input'
71
+ )
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
+ # Generar y mostrar respuesta
80
+ with chat_container:
81
+ with st.chat_message("assistant"):
82
+ message_placeholder = st.empty()
83
+ full_response = ""
84
+
85
+ for chunk in st.session_state.chat_processor.process_chat_input(
86
+ user_input,
87
+ lang_code
88
+ ):
89
+ full_response += chunk
90
+ message_placeholder.markdown(full_response)
91
+
92
+ # Guardar respuesta
93
+ st.session_state.sidebar_messages.append(
94
+ {"role": "assistant", "content": full_response.strip()}
95
+ )
96
+
97
+ # En la funci贸n donde guardamos el chat
98
+ store_chat_history(
99
+ username=st.session_state.username,
100
+ messages=st.session_state.sidebar_messages,
101
+ analysis_type='sidebar' # Especificar el tipo
102
+ )
103
+
104
+ # Bot贸n para limpiar chat
105
+ if st.button(translations['clear_chat']):
106
+ st.session_state.sidebar_messages = [
107
+ {"role": "assistant", "content": translations['initial_message']}
108
+ ]
109
+ st.rerun()
110
+
111
+ except Exception as e:
112
+ logger.error(f"Error en sidebar chat: {str(e)}")
113
+ st.error(translations['error_message'])