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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
##############
|
2 |
+
###modules/studentact/student_activities_v2.py
|
3 |
+
|
4 |
+
import streamlit as st
|
5 |
+
import re
|
6 |
+
import io
|
7 |
+
from io import BytesIO
|
8 |
+
import pandas as pd
|
9 |
+
import numpy as np
|
10 |
+
import time
|
11 |
+
import matplotlib.pyplot as plt
|
12 |
+
from datetime import datetime
|
13 |
+
from spacy import displacy
|
14 |
+
import random
|
15 |
+
import base64
|
16 |
+
import seaborn as sns
|
17 |
+
import logging
|
18 |
+
|
19 |
+
# Importaciones de la base de datos
|
20 |
+
from ..database.morphosintax_mongo_db import get_student_morphosyntax_analysis
|
21 |
+
from ..database.semantic_mongo_db import get_student_semantic_analysis
|
22 |
+
from ..database.discourse_mongo_db import get_student_discourse_analysis
|
23 |
+
from ..database.chat_mongo_db import get_chat_history
|
24 |
+
|
25 |
+
logger = logging.getLogger(__name__)
|
26 |
+
|
27 |
+
###################################################################################
|
28 |
+
|
29 |
+
def display_student_activities(username: str, lang_code: str, t: dict):
|
30 |
+
"""
|
31 |
+
Muestra todas las actividades del estudiante
|
32 |
+
Args:
|
33 |
+
username: Nombre del estudiante
|
34 |
+
lang_code: Código del idioma
|
35 |
+
t: Diccionario de traducciones
|
36 |
+
"""
|
37 |
+
try:
|
38 |
+
st.header(t.get('activities_title', 'Mis Actividades'))
|
39 |
+
|
40 |
+
# Tabs para diferentes tipos de análisis
|
41 |
+
tabs = st.tabs([
|
42 |
+
t.get('morpho_activities', 'Análisis Morfosintáctico'),
|
43 |
+
t.get('semantic_activities', 'Análisis Semántico'),
|
44 |
+
t.get('discourse_activities', 'Análisis del Discurso'),
|
45 |
+
t.get('chat_activities', 'Conversaciones con el Asistente')
|
46 |
+
])
|
47 |
+
|
48 |
+
# Tab de Análisis Morfosintáctico
|
49 |
+
with tabs[0]:
|
50 |
+
display_morphosyntax_activities(username, t)
|
51 |
+
|
52 |
+
# Tab de Análisis Semántico
|
53 |
+
with tabs[1]:
|
54 |
+
display_semantic_activities(username, t)
|
55 |
+
|
56 |
+
# Tab de Análisis del Discurso
|
57 |
+
with tabs[2]:
|
58 |
+
display_discourse_activities(username, t)
|
59 |
+
|
60 |
+
# Tab de Conversaciones del Chat
|
61 |
+
with tabs[3]:
|
62 |
+
display_chat_activities(username, t)
|
63 |
+
|
64 |
+
except Exception as e:
|
65 |
+
logger.error(f"Error mostrando actividades: {str(e)}")
|
66 |
+
st.error(t.get('error_loading_activities', 'Error al cargar las actividades'))
|
67 |
+
|
68 |
+
|
69 |
+
###############################################################################################
|
70 |
+
def display_morphosyntax_activities(username: str, t: dict):
|
71 |
+
"""Muestra actividades de análisis morfosintáctico"""
|
72 |
+
try:
|
73 |
+
analyses = get_student_morphosyntax_analysis(username)
|
74 |
+
if not analyses:
|
75 |
+
st.info(t.get('no_morpho_analyses', 'No hay análisis morfosintácticos registrados'))
|
76 |
+
return
|
77 |
+
|
78 |
+
for analysis in analyses:
|
79 |
+
with st.expander(
|
80 |
+
f"{t.get('analysis_date', 'Fecha')}: {analysis['timestamp']}",
|
81 |
+
expanded=False
|
82 |
+
):
|
83 |
+
st.text(f"{t.get('analyzed_text', 'Texto analizado')}:")
|
84 |
+
st.write(analysis['text'])
|
85 |
+
|
86 |
+
if 'arc_diagrams' in analysis:
|
87 |
+
st.subheader(t.get('syntactic_diagrams', 'Diagramas sintácticos'))
|
88 |
+
for diagram in analysis['arc_diagrams']:
|
89 |
+
st.write(diagram, unsafe_allow_html=True)
|
90 |
+
|
91 |
+
except Exception as e:
|
92 |
+
logger.error(f"Error mostrando análisis morfosintáctico: {str(e)}")
|
93 |
+
st.error(t.get('error_morpho', 'Error al mostrar análisis morfosintáctico'))
|
94 |
+
|
95 |
+
|
96 |
+
###############################################################################################
|
97 |
+
def display_semantic_activities(username: str, t: dict):
|
98 |
+
"""Muestra actividades de análisis semántico"""
|
99 |
+
try:
|
100 |
+
logger.info(f"Recuperando análisis semántico para {username}")
|
101 |
+
analyses = get_student_semantic_analysis(username)
|
102 |
+
|
103 |
+
if not analyses:
|
104 |
+
logger.info("No se encontraron análisis semánticos")
|
105 |
+
st.info(t.get('no_semantic_analyses', 'No hay análisis semánticos registrados'))
|
106 |
+
return
|
107 |
+
|
108 |
+
logger.info(f"Procesando {len(analyses)} análisis semánticos")
|
109 |
+
for analysis in analyses:
|
110 |
+
try:
|
111 |
+
# Verificar campos mínimos necesarios
|
112 |
+
if not all(key in analysis for key in ['timestamp', 'concept_graph']):
|
113 |
+
logger.warning(f"Análisis incompleto: {analysis.keys()}")
|
114 |
+
continue
|
115 |
+
|
116 |
+
# Formatear fecha
|
117 |
+
timestamp = datetime.fromisoformat(analysis['timestamp'].replace('Z', '+00:00'))
|
118 |
+
formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
|
119 |
+
|
120 |
+
with st.expander(f"{t.get('analysis_date', 'Fecha')}: {formatted_date}", expanded=False):
|
121 |
+
if analysis['concept_graph']:
|
122 |
+
logger.debug("Decodificando gráfico de conceptos")
|
123 |
+
try:
|
124 |
+
image_bytes = base64.b64decode(analysis['concept_graph'])
|
125 |
+
st.image(image_bytes, use_column_width=True)
|
126 |
+
logger.debug("Gráfico mostrado exitosamente")
|
127 |
+
except Exception as img_error:
|
128 |
+
logger.error(f"Error decodificando imagen: {str(img_error)}")
|
129 |
+
st.error(t.get('error_loading_graph', 'Error al cargar el gráfico'))
|
130 |
+
else:
|
131 |
+
st.info(t.get('no_graph', 'No hay visualización disponible'))
|
132 |
+
|
133 |
+
except Exception as e:
|
134 |
+
logger.error(f"Error procesando análisis individual: {str(e)}")
|
135 |
+
continue
|
136 |
+
|
137 |
+
except Exception as e:
|
138 |
+
logger.error(f"Error mostrando análisis semántico: {str(e)}")
|
139 |
+
st.error(t.get('error_semantic', 'Error al mostrar análisis semántico'))
|
140 |
+
|
141 |
+
|
142 |
+
###################################################################################################
|
143 |
+
def display_discourse_activities(username: str, t: dict):
|
144 |
+
"""Muestra actividades de análisis del discurso"""
|
145 |
+
try:
|
146 |
+
logger.info(f"Recuperando análisis del discurso para {username}")
|
147 |
+
analyses = get_student_discourse_analysis(username)
|
148 |
+
|
149 |
+
if not analyses:
|
150 |
+
logger.info("No se encontraron análisis del discurso")
|
151 |
+
st.info(t.get('no_discourse_analyses', 'No hay análisis del discurso registrados'))
|
152 |
+
return
|
153 |
+
|
154 |
+
logger.info(f"Procesando {len(analyses)} análisis del discurso")
|
155 |
+
for analysis in analyses:
|
156 |
+
try:
|
157 |
+
# Verificar campos mínimos necesarios
|
158 |
+
if not all(key in analysis for key in ['timestamp', 'combined_graph']):
|
159 |
+
logger.warning(f"Análisis incompleto: {analysis.keys()}")
|
160 |
+
continue
|
161 |
+
|
162 |
+
# Formatear fecha
|
163 |
+
timestamp = datetime.fromisoformat(analysis['timestamp'].replace('Z', '+00:00'))
|
164 |
+
formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
|
165 |
+
|
166 |
+
with st.expander(f"{t.get('analysis_date', 'Fecha')}: {formatted_date}", expanded=False):
|
167 |
+
if analysis['combined_graph']:
|
168 |
+
logger.debug("Decodificando gráfico combinado")
|
169 |
+
try:
|
170 |
+
image_bytes = base64.b64decode(analysis['combined_graph'])
|
171 |
+
st.image(image_bytes, use_column_width=True)
|
172 |
+
logger.debug("Gráfico mostrado exitosamente")
|
173 |
+
except Exception as img_error:
|
174 |
+
logger.error(f"Error decodificando imagen: {str(img_error)}")
|
175 |
+
st.error(t.get('error_loading_graph', 'Error al cargar el gráfico'))
|
176 |
+
else:
|
177 |
+
st.info(t.get('no_visualization', 'No hay visualización comparativa disponible'))
|
178 |
+
|
179 |
+
except Exception as e:
|
180 |
+
logger.error(f"Error procesando análisis individual: {str(e)}")
|
181 |
+
continue
|
182 |
+
|
183 |
+
except Exception as e:
|
184 |
+
logger.error(f"Error mostrando análisis del discurso: {str(e)}")
|
185 |
+
st.error(t.get('error_discourse', 'Error al mostrar análisis del discurso'))
|
186 |
+
|
187 |
+
#################################################################################
|
188 |
+
def display_discourse_comparison(analysis: dict, t: dict):
|
189 |
+
"""Muestra la comparación de análisis del discurso"""
|
190 |
+
st.subheader(t.get('comparison_results', 'Resultados de la comparación'))
|
191 |
+
|
192 |
+
col1, col2 = st.columns(2)
|
193 |
+
with col1:
|
194 |
+
st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
|
195 |
+
df1 = pd.DataFrame(analysis['key_concepts1'])
|
196 |
+
st.dataframe(df1)
|
197 |
+
|
198 |
+
with col2:
|
199 |
+
st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
|
200 |
+
df2 = pd.DataFrame(analysis['key_concepts2'])
|
201 |
+
st.dataframe(df2)
|
202 |
+
|
203 |
+
#################################################################################
|
204 |
+
def display_chat_activities(username: str, t: dict):
|
205 |
+
"""
|
206 |
+
Muestra historial de conversaciones del chat
|
207 |
+
"""
|
208 |
+
try:
|
209 |
+
# Obtener historial del chat
|
210 |
+
chat_history = get_chat_history(
|
211 |
+
username=username,
|
212 |
+
analysis_type='sidebar',
|
213 |
+
limit=50
|
214 |
+
)
|
215 |
+
|
216 |
+
if not chat_history:
|
217 |
+
st.info(t.get('no_chat_history', 'No hay conversaciones registradas'))
|
218 |
+
return
|
219 |
+
|
220 |
+
for chat in reversed(chat_history): # Mostrar las más recientes primero
|
221 |
+
try:
|
222 |
+
# Convertir timestamp a datetime para formato
|
223 |
+
timestamp = datetime.fromisoformat(chat['timestamp'].replace('Z', '+00:00'))
|
224 |
+
formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
|
225 |
+
|
226 |
+
with st.expander(
|
227 |
+
f"{t.get('chat_date', 'Fecha de conversación')}: {formatted_date}",
|
228 |
+
expanded=False
|
229 |
+
):
|
230 |
+
if 'messages' in chat and chat['messages']:
|
231 |
+
# Mostrar cada mensaje en la conversación
|
232 |
+
for message in chat['messages']:
|
233 |
+
role = message.get('role', 'unknown')
|
234 |
+
content = message.get('content', '')
|
235 |
+
|
236 |
+
# Usar el componente de chat de Streamlit
|
237 |
+
with st.chat_message(role):
|
238 |
+
st.markdown(content)
|
239 |
+
|
240 |
+
# Agregar separador entre mensajes
|
241 |
+
st.divider()
|
242 |
+
else:
|
243 |
+
st.warning(t.get('invalid_chat_format', 'Formato de chat no válido'))
|
244 |
+
|
245 |
+
except Exception as e:
|
246 |
+
logger.error(f"Error mostrando conversación: {str(e)}")
|
247 |
+
continue
|
248 |
+
|
249 |
+
except Exception as e:
|
250 |
+
logger.error(f"Error mostrando historial del chat: {str(e)}")
|
251 |
+
st.error(t.get('error_chat', 'Error al mostrar historial del chat'))
|