Delete modules/ui.py
Browse files- modules/ui.py +0 -647
modules/ui.py
DELETED
@@ -1,647 +0,0 @@
|
|
1 |
-
#Importaciones generales
|
2 |
-
import streamlit as st
|
3 |
-
import re
|
4 |
-
import io
|
5 |
-
from io import BytesIO
|
6 |
-
import base64
|
7 |
-
import matplotlib.pyplot as plt
|
8 |
-
import pandas as pd
|
9 |
-
import time
|
10 |
-
from datetime import datetime
|
11 |
-
from streamlit_player import st_player # Necesitarás instalar esta librería: pip install streamlit-player
|
12 |
-
from modules.database import store_application_request
|
13 |
-
from modules.email import send_email_notification
|
14 |
-
from spacy import displacy
|
15 |
-
import logging
|
16 |
-
|
17 |
-
# Configuración del logger
|
18 |
-
logging.basicConfig(level=logging.INFO)
|
19 |
-
logger = logging.getLogger(__name__)
|
20 |
-
|
21 |
-
#Importaciones locales
|
22 |
-
#Importaciones locales de autenticación y base de datos
|
23 |
-
from .auth import authenticate_user, register_user
|
24 |
-
|
25 |
-
from .database import (
|
26 |
-
get_student_data,
|
27 |
-
store_application_request,
|
28 |
-
store_morphosyntax_result,
|
29 |
-
store_semantic_result,
|
30 |
-
store_discourse_analysis_result,
|
31 |
-
store_chat_history,
|
32 |
-
create_admin_user,
|
33 |
-
create_student_user
|
34 |
-
)
|
35 |
-
|
36 |
-
#Importaciones locales de uiadmin
|
37 |
-
from .admin_ui import admin_page
|
38 |
-
|
39 |
-
#Importaciones locales funciones de análisis
|
40 |
-
from .morpho_analysis import generate_arc_diagram, get_repeated_words_colors, highlight_repeated_words, POS_COLORS, POS_TRANSLATIONS
|
41 |
-
from .semantic_analysis import visualize_semantic_relations, perform_semantic_analysis
|
42 |
-
from .discourse_analysis import compare_semantic_analysis, perform_discourse_analysis
|
43 |
-
from .chatbot import initialize_chatbot, get_chatbot_response
|
44 |
-
|
45 |
-
##################################################################################################
|
46 |
-
def initialize_session_state():
|
47 |
-
if 'initialized' not in st.session_state:
|
48 |
-
st.session_state.clear()
|
49 |
-
st.session_state.initialized = True
|
50 |
-
st.session_state.logged_in = False
|
51 |
-
st.session_state.page = 'login'
|
52 |
-
st.session_state.username = None
|
53 |
-
st.session_state.role = None
|
54 |
-
|
55 |
-
##################################################################################################
|
56 |
-
def main():
|
57 |
-
initialize_session_state()
|
58 |
-
|
59 |
-
print(f"Página actual: {st.session_state.page}")
|
60 |
-
print(f"Rol del usuario: {st.session_state.role}")
|
61 |
-
|
62 |
-
if st.session_state.page == 'login':
|
63 |
-
login_register_page()
|
64 |
-
elif st.session_state.page == 'admin':
|
65 |
-
print("Intentando mostrar página de admin")
|
66 |
-
admin_page()
|
67 |
-
elif st.session_state.page == 'user':
|
68 |
-
user_page()
|
69 |
-
else:
|
70 |
-
print(f"Página no reconocida: {st.session_state.page}")
|
71 |
-
|
72 |
-
print(f"Estado final de la sesión: {st.session_state}")
|
73 |
-
|
74 |
-
##################################################################################################
|
75 |
-
def login_register_page():
|
76 |
-
st.title("AIdeaText")
|
77 |
-
|
78 |
-
left_column, right_column = st.columns([1, 3])
|
79 |
-
|
80 |
-
with left_column:
|
81 |
-
tab1, tab2 = st.tabs(["Iniciar Sesión", "Registrarse"])
|
82 |
-
|
83 |
-
with tab1:
|
84 |
-
login_form()
|
85 |
-
|
86 |
-
with tab2:
|
87 |
-
register_form()
|
88 |
-
|
89 |
-
with right_column:
|
90 |
-
display_videos_and_info()
|
91 |
-
|
92 |
-
##################################################################################################
|
93 |
-
|
94 |
-
def login_form():
|
95 |
-
username = st.text_input("Correo electrónico", key="login_username")
|
96 |
-
password = st.text_input("Contraseña", type="password", key="login_password")
|
97 |
-
|
98 |
-
if st.button("Iniciar Sesión", key="login_button"):
|
99 |
-
success, role = authenticate_user(username, password)
|
100 |
-
if success:
|
101 |
-
st.session_state.logged_in = True
|
102 |
-
st.session_state.username = username
|
103 |
-
st.session_state.role = role
|
104 |
-
st.session_state.page = 'admin' if role == 'Administrador' else 'user'
|
105 |
-
print(f"Inicio de sesión exitoso. Usuario: {username}, Rol: {role}")
|
106 |
-
print(f"Estado de sesión después de login: {st.session_state}")
|
107 |
-
st.rerun()
|
108 |
-
else:
|
109 |
-
st.error("Credenciales incorrectas")
|
110 |
-
|
111 |
-
##################################################################################################
|
112 |
-
def admin_page():
|
113 |
-
st.title("Panel de Administración")
|
114 |
-
st.write(f"Bienvenido, {st.session_state.username}")
|
115 |
-
|
116 |
-
st.header("Crear Nuevo Usuario Estudiante")
|
117 |
-
new_username = st.text_input("Correo electrónico del nuevo usuario", key="admin_new_username")
|
118 |
-
new_password = st.text_input("Contraseña", type="password", key="admin_new_password")
|
119 |
-
if st.button("Crear Usuario", key="admin_create_user"):
|
120 |
-
if create_student_user(new_username, new_password):
|
121 |
-
st.success(f"Usuario estudiante {new_username} creado exitosamente")
|
122 |
-
else:
|
123 |
-
st.error("Error al crear el usuario estudiante")
|
124 |
-
|
125 |
-
# Aquí puedes añadir más funcionalidades para el panel de administración
|
126 |
-
|
127 |
-
##################################################################################################
|
128 |
-
def user_page():
|
129 |
-
st.title("Bienvenido a AIdeaText")
|
130 |
-
st.write(f"Hola, {st.session_state.username}")
|
131 |
-
|
132 |
-
# Aquí puedes añadir las funcionalidades para el usuario estudiante
|
133 |
-
# Por ejemplo:
|
134 |
-
tabs = st.tabs(["Análisis Morfosintáctico", "Análisis Semántico", "Análisis del Discurso", "Chat", "Mi Progreso"])
|
135 |
-
|
136 |
-
with tabs[0]:
|
137 |
-
display_morphosyntax_analysis_interface(nlp_models, 'es') # Asumiendo que 'es' es el idioma por defecto
|
138 |
-
with tabs[1]:
|
139 |
-
display_semantic_analysis_interface(nlp_models, 'es')
|
140 |
-
with tabs[2]:
|
141 |
-
display_discourse_analysis_interface(nlp_models, 'es')
|
142 |
-
with tabs[3]:
|
143 |
-
display_chatbot_interface('es')
|
144 |
-
with tabs[4]:
|
145 |
-
display_student_progress(st.session_state.username, 'es')
|
146 |
-
|
147 |
-
##################################################################################################
|
148 |
-
def display_videos_and_info():
|
149 |
-
st.header("Videos: pitch, demos, entrevistas, otros")
|
150 |
-
|
151 |
-
videos = {
|
152 |
-
"Intro AideaText": "https://www.youtube.com/watch?v=UA-md1VxaRc",
|
153 |
-
"Pitch IFE Explora": "https://www.youtube.com/watch?v=Fqi4Di_Rj_s",
|
154 |
-
"Entrevista Dr. Guillermo Ruíz": "https://www.youtube.com/watch?v=_ch8cRja3oc",
|
155 |
-
"Demo versión desktop": "https://www.youtube.com/watch?v=nP6eXbog-ZY"
|
156 |
-
}
|
157 |
-
|
158 |
-
selected_title = st.selectbox("Selecciona un video tutorial:", list(videos.keys()))
|
159 |
-
|
160 |
-
if selected_title in videos:
|
161 |
-
try:
|
162 |
-
st_player(videos[selected_title])
|
163 |
-
except Exception as e:
|
164 |
-
st.error(f"Error al cargar el video: {str(e)}")
|
165 |
-
|
166 |
-
st.markdown("""
|
167 |
-
## Novedades de la versión actual
|
168 |
-
- Nueva función de análisis semántico
|
169 |
-
- Soporte para múltiples idiomas
|
170 |
-
- Interfaz mejorada para una mejor experiencia de usuario
|
171 |
-
""")
|
172 |
-
|
173 |
-
##################################################################################################
|
174 |
-
def register_form():
|
175 |
-
st.header("Solicitar prueba de la aplicación")
|
176 |
-
|
177 |
-
name = st.text_input("Nombre completo")
|
178 |
-
email = st.text_input("Correo electrónico institucional")
|
179 |
-
institution = st.text_input("Institución")
|
180 |
-
role = st.selectbox("Rol", ["Estudiante", "Profesor", "Investigador", "Otro"])
|
181 |
-
reason = st.text_area("¿Por qué estás interesado en probar AIdeaText?")
|
182 |
-
|
183 |
-
if st.button("Enviar solicitud"):
|
184 |
-
logger.info(f"Attempting to submit application for {email}")
|
185 |
-
logger.debug(f"Form data: name={name}, email={email}, institution={institution}, role={role}, reason={reason}")
|
186 |
-
|
187 |
-
if not name or not email or not institution or not reason:
|
188 |
-
logger.warning("Incomplete form submission")
|
189 |
-
st.error("Por favor, completa todos los campos.")
|
190 |
-
elif not is_institutional_email(email):
|
191 |
-
logger.warning(f"Non-institutional email used: {email}")
|
192 |
-
st.error("Por favor, utiliza un correo electrónico institucional.")
|
193 |
-
else:
|
194 |
-
logger.info(f"Attempting to store application for {email}")
|
195 |
-
success = store_application_request(name, email, institution, role, reason)
|
196 |
-
if success:
|
197 |
-
st.success("Tu solicitud ha sido enviada. Te contactaremos pronto.")
|
198 |
-
logger.info(f"Application request stored successfully for {email}")
|
199 |
-
else:
|
200 |
-
st.error("Hubo un problema al enviar tu solicitud. Por favor, intenta de nuevo más tarde.")
|
201 |
-
logger.error(f"Failed to store application request for {email}")
|
202 |
-
|
203 |
-
|
204 |
-
def is_institutional_email(email):
|
205 |
-
forbidden_domains = ['gmail.com', 'hotmail.com', 'yahoo.com', 'outlook.com']
|
206 |
-
return not any(domain in email.lower() for domain in forbidden_domains)
|
207 |
-
################################################################################
|
208 |
-
|
209 |
-
def display_student_progress(username, lang_code='es'):
|
210 |
-
student_data = get_student_data(username)
|
211 |
-
|
212 |
-
if student_data is None or len(student_data['entries']) == 0:
|
213 |
-
st.warning("No se encontraron datos para este estudiante.")
|
214 |
-
st.info("Intenta realizar algunos análisis de texto primero.")
|
215 |
-
return
|
216 |
-
|
217 |
-
st.title(f"Progreso de {username}")
|
218 |
-
|
219 |
-
with st.expander("Resumen de Actividades y Progreso", expanded=True):
|
220 |
-
# Resumen de actividades
|
221 |
-
total_entries = len(student_data['entries'])
|
222 |
-
st.write(f"Total de análisis realizados: {total_entries}")
|
223 |
-
|
224 |
-
# Gráfico de tipos de análisis
|
225 |
-
analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
|
226 |
-
analysis_counts = pd.Series(analysis_types).value_counts()
|
227 |
-
|
228 |
-
fig, ax = plt.subplots()
|
229 |
-
analysis_counts.plot(kind='bar', ax=ax)
|
230 |
-
ax.set_title("Tipos de análisis realizados")
|
231 |
-
ax.set_xlabel("Tipo de análisis")
|
232 |
-
ax.set_ylabel("Cantidad")
|
233 |
-
st.pyplot(fig)
|
234 |
-
|
235 |
-
# Progreso a lo largo del tiempo
|
236 |
-
dates = [datetime.fromisoformat(entry['timestamp']) for entry in student_data['entries']]
|
237 |
-
analysis_counts = pd.Series(dates).value_counts().sort_index()
|
238 |
-
|
239 |
-
fig, ax = plt.subplots()
|
240 |
-
analysis_counts.plot(kind='line', ax=ax)
|
241 |
-
ax.set_title("Análisis realizados a lo largo del tiempo")
|
242 |
-
ax.set_xlabel("Fecha")
|
243 |
-
ax.set_ylabel("Cantidad de análisis")
|
244 |
-
st.pyplot(fig)
|
245 |
-
|
246 |
-
with st.expander("Histórico de Análisis Morfosintácticos"):
|
247 |
-
morphosyntax_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'morphosyntax']
|
248 |
-
for entry in morphosyntax_entries:
|
249 |
-
st.subheader(f"Análisis del {entry['timestamp']}")
|
250 |
-
if entry['arc_diagrams']:
|
251 |
-
st.write(entry['arc_diagrams'][0], unsafe_allow_html=True)
|
252 |
-
|
253 |
-
with st.expander("Histórico de Análisis Semánticos"):
|
254 |
-
semantic_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'semantic']
|
255 |
-
for entry in semantic_entries:
|
256 |
-
st.subheader(f"Análisis del {entry['timestamp']}")
|
257 |
-
st.write(f"Archivo analizado: {entry.get('filename', 'Nombre no disponible')}")
|
258 |
-
if 'network_diagram' in entry:
|
259 |
-
try:
|
260 |
-
# Intentar decodificar la imagen si está en formato base64
|
261 |
-
image_bytes = base64.b64decode(entry['network_diagram'])
|
262 |
-
st.image(image_bytes)
|
263 |
-
except Exception as e:
|
264 |
-
st.error(f"No se pudo mostrar la imagen: {str(e)}")
|
265 |
-
st.write("Datos de la imagen (para depuración):")
|
266 |
-
st.write(entry['network_diagram'][:100] + "...") #
|
267 |
-
|
268 |
-
with st.expander("Histórico de Análisis Discursivos"):
|
269 |
-
discourse_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'discourse']
|
270 |
-
for entry in discourse_entries:
|
271 |
-
st.subheader(f"Análisis del {entry['timestamp']}")
|
272 |
-
st.write(f"Archivo patrón: {entry.get('filename1', 'Nombre no disponible')}")
|
273 |
-
st.write(f"Archivo comparado: {entry.get('filename2', 'Nombre no disponible')}")
|
274 |
-
|
275 |
-
try:
|
276 |
-
# Intentar obtener y combinar las dos imágenes
|
277 |
-
if 'graph1' in entry and 'graph2' in entry:
|
278 |
-
img1 = Image.open(BytesIO(base64.b64decode(entry['graph1'])))
|
279 |
-
img2 = Image.open(BytesIO(base64.b64decode(entry['graph2'])))
|
280 |
-
|
281 |
-
# Crear una nueva imagen combinada
|
282 |
-
total_width = img1.width + img2.width
|
283 |
-
max_height = max(img1.height, img2.height)
|
284 |
-
combined_img = Image.new('RGB', (total_width, max_height))
|
285 |
-
|
286 |
-
# Pegar las dos imágenes lado a lado
|
287 |
-
combined_img.paste(img1, (0, 0))
|
288 |
-
combined_img.paste(img2, (img1.width, 0))
|
289 |
-
|
290 |
-
# Convertir la imagen combinada a bytes
|
291 |
-
buffered = BytesIO()
|
292 |
-
combined_img.save(buffered, format="PNG")
|
293 |
-
img_str = base64.b64encode(buffered.getvalue()).decode()
|
294 |
-
|
295 |
-
# Mostrar la imagen combinada
|
296 |
-
st.image(f"data:image/png;base64,{img_str}")
|
297 |
-
elif 'combined_graph' in entry:
|
298 |
-
# Si ya existe una imagen combinada, mostrarla directamente
|
299 |
-
img_bytes = base64.b64decode(entry['combined_graph'])
|
300 |
-
st.image(img_bytes)
|
301 |
-
else:
|
302 |
-
st.write("No se encontraron gráficos para este análisis.")
|
303 |
-
except Exception as e:
|
304 |
-
st.error(f"No se pudieron mostrar los gráficos: {str(e)}")
|
305 |
-
st.write("Datos de los gráficos (para depuración):")
|
306 |
-
if 'graph1' in entry:
|
307 |
-
st.write("Graph 1:", entry['graph1'][:100] + "...")
|
308 |
-
if 'graph2' in entry:
|
309 |
-
st.write("Graph 2:", entry['graph2'][:100] + "...")
|
310 |
-
if 'combined_graph' in entry:
|
311 |
-
st.write("Combined Graph:", entry['combined_graph'][:100] + "...")
|
312 |
-
|
313 |
-
with st.expander("Histórico de Conversaciones con el ChatBot"):
|
314 |
-
if 'chat_history' in student_data:
|
315 |
-
for i, chat in enumerate(student_data['chat_history']):
|
316 |
-
st.subheader(f"Conversación {i+1} - {chat['timestamp']}")
|
317 |
-
for message in chat['messages']:
|
318 |
-
if message['role'] == 'user':
|
319 |
-
st.write("Usuario: " + message['content'])
|
320 |
-
else:
|
321 |
-
st.write("Asistente: " + message['content'])
|
322 |
-
st.write("---")
|
323 |
-
else:
|
324 |
-
st.write("No se encontraron conversaciones con el ChatBot.")
|
325 |
-
|
326 |
-
# Añadir logs para depuración
|
327 |
-
if st.checkbox("Mostrar datos de depuración"):
|
328 |
-
st.write("Datos del estudiante (para depuración):")
|
329 |
-
st.json(student_data)
|
330 |
-
|
331 |
-
##################################################################################################
|
332 |
-
def display_morphosyntax_analysis_interface(nlp_models, lang_code):
|
333 |
-
translations = {
|
334 |
-
'es': {
|
335 |
-
'title': "AIdeaText - Análisis morfológico y sintáctico",
|
336 |
-
'input_label': "Ingrese un texto para analizar (máx. 5,000 palabras):",
|
337 |
-
'input_placeholder': "El objetivo de esta aplicación es que mejore sus habilidades de redacción...",
|
338 |
-
'analyze_button': "Analizar texto",
|
339 |
-
'repeated_words': "Palabras repetidas",
|
340 |
-
'legend': "Leyenda: Categorías gramaticales",
|
341 |
-
'arc_diagram': "Análisis sintáctico: Diagrama de arco",
|
342 |
-
'sentence': "Oración",
|
343 |
-
'success_message': "Análisis guardado correctamente.",
|
344 |
-
'error_message': "Hubo un problema al guardar el análisis. Por favor, inténtelo de nuevo.",
|
345 |
-
'warning_message': "Por favor, ingrese un texto para analizar."
|
346 |
-
},
|
347 |
-
'en': {
|
348 |
-
'title': "AIdeaText - Morphological and Syntactic Analysis",
|
349 |
-
'input_label': "Enter a text to analyze (max 5,000 words):",
|
350 |
-
'input_placeholder': "The goal of this app is for you to improve your writing skills...",
|
351 |
-
'analyze_button': "Analyze text",
|
352 |
-
'repeated_words': "Repeated words",
|
353 |
-
'legend': "Legend: Grammatical categories",
|
354 |
-
'arc_diagram': "Syntactic analysis: Arc diagram",
|
355 |
-
'sentence': "Sentence",
|
356 |
-
'success_message': "Analysis saved successfully.",
|
357 |
-
'error_message': "There was a problem saving the analysis. Please try again.",
|
358 |
-
'warning_message': "Please enter a text to analyze."
|
359 |
-
},
|
360 |
-
'fr': {
|
361 |
-
'title': "AIdeaText - Analyse morphologique et syntaxique",
|
362 |
-
'input_label': "Entrez un texte à analyser (max 5 000 mots) :",
|
363 |
-
'input_placeholder': "Le but de cette application est d'améliorer vos compétences en rédaction...",
|
364 |
-
'analyze_button': "Analyser le texte",
|
365 |
-
'repeated_words': "Mots répétés",
|
366 |
-
'legend': "Légende : Catégories grammaticales",
|
367 |
-
'arc_diagram': "Analyse syntaxique : Diagramme en arc",
|
368 |
-
'sentence': "Phrase",
|
369 |
-
'success_message': "Analyse enregistrée avec succès.",
|
370 |
-
'error_message': "Un problème est survenu lors de l'enregistrement de l'analyse. Veuillez réessayer.",
|
371 |
-
'warning_message': "Veuillez entrer un texte à analyser."
|
372 |
-
}
|
373 |
-
}
|
374 |
-
|
375 |
-
t = translations[lang_code]
|
376 |
-
|
377 |
-
input_key = f"morphosyntax_input_{lang_code}"
|
378 |
-
|
379 |
-
if input_key not in st.session_state:
|
380 |
-
st.session_state[input_key] = ""
|
381 |
-
|
382 |
-
sentence_input = st.text_area(
|
383 |
-
t['input_label'],
|
384 |
-
height=150,
|
385 |
-
placeholder=t['input_placeholder'],
|
386 |
-
value=st.session_state[input_key],
|
387 |
-
key=f"text_area_{lang_code}",
|
388 |
-
on_change=lambda: setattr(st.session_state, input_key, st.session_state[f"text_area_{lang_code}"])
|
389 |
-
)
|
390 |
-
|
391 |
-
if st.button(t['analyze_button'], key=f"analyze_button_{lang_code}"):
|
392 |
-
current_input = st.session_state[input_key]
|
393 |
-
if current_input:
|
394 |
-
doc = nlp_models[lang_code](current_input)
|
395 |
-
|
396 |
-
word_colors = get_repeated_words_colors(doc)
|
397 |
-
|
398 |
-
with st.expander(t['repeated_words'], expanded=True):
|
399 |
-
highlighted_text = highlight_repeated_words(doc, word_colors)
|
400 |
-
st.markdown(highlighted_text, unsafe_allow_html=True)
|
401 |
-
|
402 |
-
st.markdown(f"##### {t['legend']}")
|
403 |
-
legend_html = "<div style='display: flex; flex-wrap: wrap;'>"
|
404 |
-
for pos, color in POS_COLORS.items():
|
405 |
-
if pos in POS_TRANSLATIONS[lang_code]:
|
406 |
-
legend_html += f"<div style='margin-right: 10px;'><span style='background-color: {color}; padding: 2px 5px;'>{POS_TRANSLATIONS[lang_code][pos]}</span></div>"
|
407 |
-
legend_html += "</div>"
|
408 |
-
st.markdown(legend_html, unsafe_allow_html=True)
|
409 |
-
|
410 |
-
with st.expander(t['arc_diagram'], expanded=True):
|
411 |
-
sentences = list(doc.sents)
|
412 |
-
arc_diagrams = []
|
413 |
-
for i, sent in enumerate(sentences):
|
414 |
-
st.subheader(f"{t['sentence']} {i+1}")
|
415 |
-
html = displacy.render(sent, style="dep", options={"distance": 100})
|
416 |
-
html = html.replace('height="375"', 'height="200"')
|
417 |
-
html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html)
|
418 |
-
html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"', lambda m: f'<g transform="translate({m.group(1)},50)"', html)
|
419 |
-
st.write(html, unsafe_allow_html=True)
|
420 |
-
arc_diagrams.append(html)
|
421 |
-
|
422 |
-
if store_morphosyntax_result(
|
423 |
-
st.session_state.username,
|
424 |
-
current_input,
|
425 |
-
word_colors,
|
426 |
-
arc_diagrams,
|
427 |
-
):
|
428 |
-
st.success(t['success_message'])
|
429 |
-
else:
|
430 |
-
st.error(t['error_message'])
|
431 |
-
else:
|
432 |
-
st.warning(t['warning_message'])
|
433 |
-
|
434 |
-
###############################################################################################################
|
435 |
-
def display_semantic_analysis_interface(nlp_models, lang_code):
|
436 |
-
translations = {
|
437 |
-
'es': {
|
438 |
-
'title': "AIdeaText - Análisis semántico",
|
439 |
-
'file_uploader': "Cargar archivo de texto",
|
440 |
-
'analyze_button': "Analizar texto",
|
441 |
-
'semantic_relations': "Relaciones Semánticas Relevantes",
|
442 |
-
'success_message': "Análisis semántico guardado correctamente.",
|
443 |
-
'error_message': "Hubo un problema al guardar el análisis semántico. Por favor, inténtelo de nuevo.",
|
444 |
-
'warning_message': "Por favor, cargue un archivo para analizar."
|
445 |
-
},
|
446 |
-
'en': {
|
447 |
-
'title': "AIdeaText - Semantic Analysis",
|
448 |
-
'file_uploader': "Upload text file",
|
449 |
-
'analyze_button': "Analyze text",
|
450 |
-
'semantic_relations': "Relevant Semantic Relations",
|
451 |
-
'success_message': "Semantic analysis saved successfully.",
|
452 |
-
'error_message': "There was a problem saving the semantic analysis. Please try again.",
|
453 |
-
'warning_message': "Please upload a file to analyze."
|
454 |
-
},
|
455 |
-
'fr': {
|
456 |
-
'title': "AIdeaText - Analyse sémantique",
|
457 |
-
'file_uploader': "Télécharger le fichier texte",
|
458 |
-
'analyze_button': "Analyser le texte",
|
459 |
-
'semantic_relations': "Relations Sémantiques Pertinentes",
|
460 |
-
'success_message': "Analyse sémantique enregistrée avec succès.",
|
461 |
-
'error_message': "Un problème est survenu lors de l'enregistrement de l'analyse sémantique. Veuillez réessayer.",
|
462 |
-
'warning_message': "Veuillez télécharger un fichier à analyser."
|
463 |
-
}
|
464 |
-
}
|
465 |
-
|
466 |
-
t = translations[lang_code]
|
467 |
-
st.header(t['title'])
|
468 |
-
|
469 |
-
# Opción para cargar archivo
|
470 |
-
uploaded_file = st.file_uploader(t['file_uploader'], type=['txt'])
|
471 |
-
|
472 |
-
if st.button(t['analyze_button']):
|
473 |
-
if uploaded_file is not None:
|
474 |
-
text_content = uploaded_file.getvalue().decode('utf-8')
|
475 |
-
|
476 |
-
# Realizar el análisis
|
477 |
-
relations_graph = perform_semantic_analysis(text_content, nlp_models[lang_code], lang_code)
|
478 |
-
|
479 |
-
# Mostrar el gráfico de relaciones semánticas
|
480 |
-
with st.expander(t['semantic_relations'], expanded=True):
|
481 |
-
st.pyplot(relations_graph)
|
482 |
-
|
483 |
-
# Guardar el resultado del análisis
|
484 |
-
if store_semantic_result(st.session_state.username, text_content, relations_graph):
|
485 |
-
st.success(t['success_message'])
|
486 |
-
else:
|
487 |
-
st.error(t['error_message'])
|
488 |
-
else:
|
489 |
-
st.warning(t['warning_message'])
|
490 |
-
|
491 |
-
##################################################################################################
|
492 |
-
def display_discourse_analysis_interface(nlp_models, lang_code):
|
493 |
-
translations = {
|
494 |
-
'es': {
|
495 |
-
'title': "AIdeaText - Análisis del discurso",
|
496 |
-
'file_uploader1': "Cargar archivo de texto 1 (Patrón)",
|
497 |
-
'file_uploader2': "Cargar archivo de texto 2 (Comparación)",
|
498 |
-
'analyze_button': "Analizar textos",
|
499 |
-
'comparison': "Comparación de Relaciones Semánticas",
|
500 |
-
'success_message': "Análisis del discurso guardado correctamente.",
|
501 |
-
'error_message': "Hubo un problema al guardar el análisis del discurso. Por favor, inténtelo de nuevo.",
|
502 |
-
'warning_message': "Por favor, cargue ambos archivos para analizar."
|
503 |
-
},
|
504 |
-
'en': {
|
505 |
-
'title': "AIdeaText - Discourse Analysis",
|
506 |
-
'file_uploader1': "Upload text file 1 (Pattern)",
|
507 |
-
'file_uploader2': "Upload text file 2 (Comparison)",
|
508 |
-
'analyze_button': "Analyze texts",
|
509 |
-
'comparison': "Comparison of Semantic Relations",
|
510 |
-
'success_message': "Discourse analysis saved successfully.",
|
511 |
-
'error_message': "There was a problem saving the discourse analysis. Please try again.",
|
512 |
-
'warning_message': "Please upload both files to analyze."
|
513 |
-
},
|
514 |
-
'fr': {
|
515 |
-
'title': "AIdeaText - Analyse du discours",
|
516 |
-
'file_uploader1': "Télécharger le fichier texte 1 (Modèle)",
|
517 |
-
'file_uploader2': "Télécharger le fichier texte 2 (Comparaison)",
|
518 |
-
'analyze_button': "Analyser les textes",
|
519 |
-
'comparison': "Comparaison des Relations Sémantiques",
|
520 |
-
'success_message': "Analyse du discours enregistrée avec succès.",
|
521 |
-
'error_message': "Un problème est survenu lors de l'enregistrement de l'analyse du discours. Veuillez réessayer.",
|
522 |
-
'warning_message': "Veuillez télécharger les deux fichiers à analyser."
|
523 |
-
}
|
524 |
-
}
|
525 |
-
|
526 |
-
t = translations[lang_code]
|
527 |
-
st.header(t['title'])
|
528 |
-
|
529 |
-
col1, col2 = st.columns(2)
|
530 |
-
|
531 |
-
with col1:
|
532 |
-
uploaded_file1 = st.file_uploader(t['file_uploader1'], type=['txt'])
|
533 |
-
|
534 |
-
with col2:
|
535 |
-
uploaded_file2 = st.file_uploader(t['file_uploader2'], type=['txt'])
|
536 |
-
|
537 |
-
if st.button(t['analyze_button']):
|
538 |
-
if uploaded_file1 is not None and uploaded_file2 is not None:
|
539 |
-
text_content1 = uploaded_file1.getvalue().decode('utf-8')
|
540 |
-
text_content2 = uploaded_file2.getvalue().decode('utf-8')
|
541 |
-
|
542 |
-
# Realizar el análisis
|
543 |
-
graph1, graph2 = perform_discourse_analysis(text_content1, text_content2, nlp_models[lang_code], lang_code)
|
544 |
-
|
545 |
-
# Mostrar los gráficos de comparación
|
546 |
-
st.subheader(t['comparison'])
|
547 |
-
col1, col2 = st.columns(2)
|
548 |
-
with col1:
|
549 |
-
st.pyplot(graph1)
|
550 |
-
with col2:
|
551 |
-
st.pyplot(graph2)
|
552 |
-
|
553 |
-
# Guardar el resultado del análisis
|
554 |
-
#if store_discourse_analysis_result(st.session_state.username, text_content1 + "\n\n" + text_content2, graph1, graph2):
|
555 |
-
if store_discourse_analysis_result(st.session_state.username, text_content1, text_content2, graph1, graph2):
|
556 |
-
st.success(t['success_message'])
|
557 |
-
else:
|
558 |
-
st.error(t['error_message'])
|
559 |
-
else:
|
560 |
-
st.warning(t['warning_message'])
|
561 |
-
|
562 |
-
##################################################################################################
|
563 |
-
#def display_saved_discourse_analysis(analysis_data):
|
564 |
-
# img_bytes = base64.b64decode(analysis_data['combined_graph'])
|
565 |
-
# img = plt.imread(io.BytesIO(img_bytes), format='png')
|
566 |
-
|
567 |
-
# st.image(img, use_column_width=True)
|
568 |
-
# st.write("Texto del documento patrón:")
|
569 |
-
# st.write(analysis_data['text1'])
|
570 |
-
# st.write("Texto del documento comparado:")
|
571 |
-
# st.write(analysis_data['text2'])
|
572 |
-
|
573 |
-
##################################################################################################
|
574 |
-
def display_chatbot_interface(lang_code):
|
575 |
-
translations = {
|
576 |
-
'es': {
|
577 |
-
'title': "Expertos en Vacaciones",
|
578 |
-
'input_placeholder': "Escribe tu mensaje aquí...",
|
579 |
-
'initial_message': "¡Hola! ¿Cómo podemos ayudarte?"
|
580 |
-
},
|
581 |
-
'en': {
|
582 |
-
'title': "Vacation Experts",
|
583 |
-
'input_placeholder': "Type your message here...",
|
584 |
-
'initial_message': "Hi! How can we help you?"
|
585 |
-
},
|
586 |
-
'fr': {
|
587 |
-
'title': "Experts en Vacances",
|
588 |
-
'input_placeholder': "Écrivez votre message ici...",
|
589 |
-
'initial_message': "Bonjour! Comment pouvons-nous vous aider?"
|
590 |
-
}
|
591 |
-
}
|
592 |
-
t = translations[lang_code]
|
593 |
-
st.title(t['title'])
|
594 |
-
|
595 |
-
if 'chatbot' not in st.session_state:
|
596 |
-
st.session_state.chatbot = initialize_chatbot()
|
597 |
-
if 'messages' not in st.session_state:
|
598 |
-
st.session_state.messages = [{"role": "assistant", "content": t['initial_message']}]
|
599 |
-
|
600 |
-
# Contenedor principal para el chat
|
601 |
-
chat_container = st.container()
|
602 |
-
|
603 |
-
# Mostrar mensajes existentes
|
604 |
-
with chat_container:
|
605 |
-
for message in st.session_state.messages:
|
606 |
-
with st.chat_message(message["role"]):
|
607 |
-
st.markdown(message["content"])
|
608 |
-
|
609 |
-
# Área de entrada del usuario
|
610 |
-
user_input = st.chat_input(t['input_placeholder'])
|
611 |
-
|
612 |
-
if user_input:
|
613 |
-
# Agregar mensaje del usuario
|
614 |
-
st.session_state.messages.append({"role": "user", "content": user_input})
|
615 |
-
|
616 |
-
# Mostrar mensaje del usuario
|
617 |
-
with chat_container:
|
618 |
-
with st.chat_message("user"):
|
619 |
-
st.markdown(user_input)
|
620 |
-
|
621 |
-
# Generar respuesta del chatbot
|
622 |
-
with chat_container:
|
623 |
-
with st.chat_message("assistant"):
|
624 |
-
message_placeholder = st.empty()
|
625 |
-
full_response = ""
|
626 |
-
for chunk in get_chatbot_response(st.session_state.chatbot, user_input, lang_code):
|
627 |
-
full_response += chunk
|
628 |
-
message_placeholder.markdown(full_response + "▌")
|
629 |
-
message_placeholder.markdown(full_response)
|
630 |
-
|
631 |
-
# Agregar respuesta del asistente a los mensajes
|
632 |
-
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
633 |
-
|
634 |
-
# Guardar la conversación en la base de datos
|
635 |
-
try:
|
636 |
-
store_chat_history(st.session_state.username, st.session_state.messages)
|
637 |
-
st.success("Conversación guardada exitosamente")
|
638 |
-
except Exception as e:
|
639 |
-
st.error(f"Error al guardar la conversación: {str(e)}")
|
640 |
-
logger.error(f"Error al guardar el historial de chat para {st.session_state.username}: {str(e)}")
|
641 |
-
|
642 |
-
# Scroll al final del chat
|
643 |
-
st.markdown('<script>window.scrollTo(0,document.body.scrollHeight);</script>', unsafe_allow_html=True)
|
644 |
-
|
645 |
-
######################################################
|
646 |
-
if __name__ == "__main__":
|
647 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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