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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 |
+
def display_morphosyntax_activities(username: str, t: dict):
|
69 |
+
"""Muestra actividades de análisis morfosintáctico"""
|
70 |
+
try:
|
71 |
+
analyses = get_student_morphosyntax_analysis(username)
|
72 |
+
if not analyses:
|
73 |
+
st.info(t.get('no_morpho_analyses', 'No hay análisis morfosintácticos registrados'))
|
74 |
+
return
|
75 |
+
|
76 |
+
for analysis in analyses:
|
77 |
+
with st.expander(
|
78 |
+
f"{t.get('analysis_date', 'Fecha')}: {analysis['timestamp']}",
|
79 |
+
expanded=False
|
80 |
+
):
|
81 |
+
st.text(f"{t.get('analyzed_text', 'Texto analizado')}:")
|
82 |
+
st.write(analysis['text'])
|
83 |
+
|
84 |
+
if 'arc_diagrams' in analysis:
|
85 |
+
st.subheader(t.get('syntactic_diagrams', 'Diagramas sintácticos'))
|
86 |
+
for diagram in analysis['arc_diagrams']:
|
87 |
+
st.write(diagram, unsafe_allow_html=True)
|
88 |
+
|
89 |
+
except Exception as e:
|
90 |
+
logger.error(f"Error mostrando análisis morfosintáctico: {str(e)}")
|
91 |
+
st.error(t.get('error_morpho', 'Error al mostrar análisis morfosintáctico'))
|
92 |
+
|
93 |
+
def display_semantic_activities(username: str, t: dict):
|
94 |
+
"""Muestra actividades de análisis semántico"""
|
95 |
+
try:
|
96 |
+
analyses = get_student_semantic_analysis(username)
|
97 |
+
if not analyses:
|
98 |
+
st.info(t.get('no_semantic_analyses', 'No hay análisis semánticos registrados'))
|
99 |
+
return
|
100 |
+
|
101 |
+
for analysis in analyses:
|
102 |
+
with st.expander(
|
103 |
+
f"{t.get('analysis_date', 'Fecha')}: {analysis['timestamp']}",
|
104 |
+
expanded=False
|
105 |
+
):
|
106 |
+
# Mostrar texto analizado
|
107 |
+
st.text(f"{t.get('analyzed_file', 'Archivo analizado')}:")
|
108 |
+
st.write(analysis['text'])
|
109 |
+
|
110 |
+
# Mostrar conceptos clave
|
111 |
+
if 'key_concepts' in analysis:
|
112 |
+
st.subheader(t.get('key_concepts', 'Conceptos clave'))
|
113 |
+
df = pd.DataFrame(
|
114 |
+
analysis['key_concepts'],
|
115 |
+
columns=['Concepto', 'Frecuencia']
|
116 |
+
)
|
117 |
+
st.dataframe(df)
|
118 |
+
|
119 |
+
# Mostrar gráfico de conceptos
|
120 |
+
if 'concept_graph' in analysis and analysis['concept_graph']:
|
121 |
+
st.subheader(t.get('concept_graph', 'Grafo de conceptos'))
|
122 |
+
image_bytes = base64.b64decode(analysis['concept_graph'])
|
123 |
+
st.image(image_bytes)
|
124 |
+
|
125 |
+
except Exception as e:
|
126 |
+
logger.error(f"Error mostrando análisis semántico: {str(e)}")
|
127 |
+
st.error(t.get('error_semantic', 'Error al mostrar análisis semántico'))
|
128 |
+
|
129 |
+
###################################################################################################
|
130 |
+
|
131 |
+
|
132 |
+
def display_discourse_activities(username: str, t: dict):
|
133 |
+
"""Muestra actividades de análisis del discurso"""
|
134 |
+
try:
|
135 |
+
analyses = get_student_discourse_analysis(username)
|
136 |
+
if not analyses:
|
137 |
+
st.info(t.get('no_discourse_analyses', 'No hay análisis del discurso registrados'))
|
138 |
+
return
|
139 |
+
|
140 |
+
for analysis in analyses:
|
141 |
+
with st.expander(
|
142 |
+
f"{t.get('analysis_date', 'Fecha')}: {analysis['timestamp']}",
|
143 |
+
expanded=False
|
144 |
+
):
|
145 |
+
# Mostrar textos analizados
|
146 |
+
col1, col2 = st.columns(2)
|
147 |
+
with col1:
|
148 |
+
st.text(f"{t.get('text_1', 'Texto 1')}:")
|
149 |
+
st.write(analysis['text1'])
|
150 |
+
with col2:
|
151 |
+
st.text(f"{t.get('text_2', 'Texto 2')}:")
|
152 |
+
st.write(analysis['text2'])
|
153 |
+
|
154 |
+
# Mostrar conceptos clave
|
155 |
+
if 'key_concepts1' in analysis and 'key_concepts2' in analysis:
|
156 |
+
st.subheader(t.get('comparison_results', 'Resultados de la comparación'))
|
157 |
+
|
158 |
+
col1, col2 = st.columns(2)
|
159 |
+
with col1:
|
160 |
+
st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
|
161 |
+
df1 = pd.DataFrame(
|
162 |
+
analysis['key_concepts1'],
|
163 |
+
columns=['Concepto', 'Frecuencia']
|
164 |
+
)
|
165 |
+
st.dataframe(df1)
|
166 |
+
|
167 |
+
with col2:
|
168 |
+
st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
|
169 |
+
df2 = pd.DataFrame(
|
170 |
+
analysis['key_concepts2'],
|
171 |
+
columns=['Concepto', 'Frecuencia']
|
172 |
+
)
|
173 |
+
st.dataframe(df2)
|
174 |
+
|
175 |
+
# Mostrar gráficos
|
176 |
+
if all(key in analysis for key in ['graph1', 'graph2']):
|
177 |
+
st.subheader(t.get('visualizations', 'Visualizaciones'))
|
178 |
+
|
179 |
+
col1, col2 = st.columns(2)
|
180 |
+
with col1:
|
181 |
+
st.markdown(f"**{t.get('graph_text_1', 'Grafo Texto 1')}**")
|
182 |
+
if analysis['graph1']:
|
183 |
+
image_bytes = base64.b64decode(analysis['graph1'])
|
184 |
+
st.image(image_bytes)
|
185 |
+
|
186 |
+
with col2:
|
187 |
+
st.markdown(f"**{t.get('graph_text_2', 'Grafo Texto 2')}**")
|
188 |
+
if analysis['graph2']:
|
189 |
+
image_bytes = base64.b64decode(analysis['graph2'])
|
190 |
+
st.image(image_bytes)
|
191 |
+
|
192 |
+
# Mostrar gráfico combinado si existe
|
193 |
+
if 'combined_graph' in analysis and analysis['combined_graph']:
|
194 |
+
st.subheader(t.get('combined_visualization', 'Visualización Combinada'))
|
195 |
+
image_bytes = base64.b64decode(analysis['combined_graph'])
|
196 |
+
st.image(image_bytes)
|
197 |
+
|
198 |
+
except Exception as e:
|
199 |
+
logger.error(f"Error mostrando análisis del discurso: {str(e)}")
|
200 |
+
st.error(t.get('error_discourse', 'Error al mostrar análisis del discurso'))
|
201 |
+
|
202 |
+
#################################################################################
|
203 |
+
def display_discourse_comparison(analysis: dict, t: dict):
|
204 |
+
"""Muestra la comparación de análisis del discurso"""
|
205 |
+
st.subheader(t.get('comparison_results', 'Resultados de la comparación'))
|
206 |
+
|
207 |
+
col1, col2 = st.columns(2)
|
208 |
+
with col1:
|
209 |
+
st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
|
210 |
+
df1 = pd.DataFrame(analysis['key_concepts1'])
|
211 |
+
st.dataframe(df1)
|
212 |
+
|
213 |
+
with col2:
|
214 |
+
st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
|
215 |
+
df2 = pd.DataFrame(analysis['key_concepts2'])
|
216 |
+
st.dataframe(df2)
|
217 |
+
|
218 |
+
#################################################################################
|
219 |
+
def display_chat_activities(username: str, t: dict):
|
220 |
+
"""
|
221 |
+
Muestra historial de conversaciones del chat
|
222 |
+
"""
|
223 |
+
try:
|
224 |
+
# Obtener historial del chat
|
225 |
+
chat_history = get_chat_history(
|
226 |
+
username=username,
|
227 |
+
analysis_type='sidebar',
|
228 |
+
limit=50
|
229 |
+
)
|
230 |
+
|
231 |
+
if not chat_history:
|
232 |
+
st.info(t.get('no_chat_history', 'No hay conversaciones registradas'))
|
233 |
+
return
|
234 |
+
|
235 |
+
for chat in reversed(chat_history): # Mostrar las más recientes primero
|
236 |
+
try:
|
237 |
+
# Convertir timestamp a datetime para formato
|
238 |
+
timestamp = datetime.fromisoformat(chat['timestamp'].replace('Z', '+00:00'))
|
239 |
+
formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
|
240 |
+
|
241 |
+
with st.expander(
|
242 |
+
f"{t.get('chat_date', 'Fecha de conversación')}: {formatted_date}",
|
243 |
+
expanded=False
|
244 |
+
):
|
245 |
+
if 'messages' in chat and chat['messages']:
|
246 |
+
# Mostrar cada mensaje en la conversación
|
247 |
+
for message in chat['messages']:
|
248 |
+
role = message.get('role', 'unknown')
|
249 |
+
content = message.get('content', '')
|
250 |
+
|
251 |
+
# Usar el componente de chat de Streamlit
|
252 |
+
with st.chat_message(role):
|
253 |
+
st.markdown(content)
|
254 |
+
|
255 |
+
# Agregar separador entre mensajes
|
256 |
+
st.divider()
|
257 |
+
else:
|
258 |
+
st.warning(t.get('invalid_chat_format', 'Formato de chat no válido'))
|
259 |
+
|
260 |
+
except Exception as e:
|
261 |
+
logger.error(f"Error mostrando conversación: {str(e)}")
|
262 |
+
continue
|
263 |
+
|
264 |
+
except Exception as e:
|
265 |
+
logger.error(f"Error mostrando historial del chat: {str(e)}")
|
266 |
+
st.error(t.get('error_chat', 'Error al mostrar historial del chat'))
|