AIdeaText commited on
Commit
14300fd
·
verified ·
1 Parent(s): edb914b

Update modules/studentact/student_activities_v2.py

Browse files
modules/studentact/student_activities_v2.py CHANGED
@@ -1,668 +1,669 @@
1
- ##############
2
- #########student_activities.py
3
- import streamlit as st
4
- import re
5
- import io
6
- from io import BytesIO
7
- import pandas as pd
8
- import numpy as np
9
- import time
10
- import matplotlib.pyplot as plt
11
- from datetime import datetime
12
- from spacy import displacy
13
- import random
14
- import base64
15
- import seaborn as sns
16
- import logging
17
-
18
- logger = logging.getLogger(__name__)
19
-
20
- ###################################################################################
21
-
22
- def display_student_progress(username, lang_code, t, student_data):
23
- if not student_data or len(student_data['entries']) == 0:
24
- st.warning(t.get("no_data_warning", "No se encontraron datos para este estudiante."))
25
- st.info(t.get("try_analysis", "Intenta realizar algunos análisis de texto primero."))
26
- return
27
-
28
- st.title(f"{t.get('progress_of', 'Progreso de')} {username}")
29
-
30
- with st.expander(t.get("activities_summary", "Resumen de Actividades y Progreso"), expanded=True):
31
- total_entries = len(student_data['entries'])
32
- st.write(f"{t.get('total_analyses', 'Total de análisis realizados')}: {total_entries}")
33
-
34
- # Gráfico de tipos de análisis
35
- analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
36
- analysis_counts = pd.Series(analysis_types).value_counts()
37
-
38
- fig, ax = plt.subplots(figsize=(8, 4))
39
- analysis_counts.plot(kind='bar', ax=ax)
40
- ax.set_title(t.get("analysis_types_chart", "Tipos de análisis realizados"))
41
- ax.set_xlabel(t.get("analysis_type", "Tipo de análisis"))
42
- ax.set_ylabel(t.get("count", "Cantidad"))
43
- st.pyplot(fig)
44
-
45
- # Histórico de Análisis Morfosintácticos
46
- with st.expander(t.get("morphosyntax_history", "Histórico de Análisis Morfosintácticos")):
47
- morphosyntax_entries = [entry for entry in username['entries'] if entry['analysis_type'] == 'morphosyntax']
48
- if not morphosyntax_entries:
49
- st.warning("No se encontraron análisis morfosintácticos.")
50
- for entry in morphosyntax_entries:
51
- st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
52
- if 'arc_diagrams' in entry and entry['arc_diagrams']:
53
- try:
54
- st.write(entry['arc_diagrams'][0], unsafe_allow_html=True)
55
- except Exception as e:
56
- logger.error(f"Error al mostrar diagrama de arco: {str(e)}")
57
- st.error("Error al mostrar el diagrama de arco.")
58
- else:
59
- st.write(t.get("no_arc_diagram", "No se encontró diagrama de arco para este análisis."))
60
-
61
- # Histórico de Análisis Semánticos
62
- with st.expander(t.get("semantic_history", "Histórico de Análisis Semánticos")):
63
- semantic_entries = [entry for entry in username['entries'] if entry['analysis_type'] == 'semantic']
64
- if not semantic_entries:
65
- st.warning("No se encontraron análisis semánticos.")
66
- for entry in semantic_entries:
67
- st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
68
- if 'key_concepts' in entry:
69
- st.write(t.get("key_concepts", "Conceptos clave:"))
70
- concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in entry['key_concepts']])
71
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
72
- if 'graph' in entry:
73
- try:
74
- img_bytes = base64.b64decode(entry['graph'])
75
- st.image(img_bytes, caption=t.get("conceptual_relations_graph", "Gráfico de relaciones conceptuales"))
76
- except Exception as e:
77
- logger.error(f"Error al mostrar gráfico semántico: {str(e)}")
78
- st.error(t.get("graph_display_error", f"No se pudo mostrar el gráfico: {str(e)}"))
79
-
80
- # Histórico de Análisis Discursivos
81
- with st.expander(t.get("discourse_history", "Histórico de Análisis Discursivos")):
82
- discourse_entries = [entry for entry in username['entries'] if entry['analysis_type'] == 'discourse']
83
- for entry in discourse_entries:
84
- st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
85
- for i in [1, 2]:
86
- if f'key_concepts{i}' in entry:
87
- st.write(f"{t.get('key_concepts', 'Conceptos clave')} {t.get('document', 'documento')} {i}:")
88
- concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in entry[f'key_concepts{i}']])
89
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
90
- try:
91
- if 'combined_graph' in entry and entry['combined_graph']:
92
- img_bytes = base64.b64decode(entry['combined_graph'])
93
- st.image(img_bytes, caption=t.get("combined_graph", "Gráfico combinado"))
94
- elif 'graph1' in entry and 'graph2' in entry:
95
- col1, col2 = st.columns(2)
96
- with col1:
97
- if entry['graph1']:
98
- img_bytes1 = base64.b64decode(entry['graph1'])
99
- st.image(img_bytes1, caption=t.get("graph_doc1", "Gráfico documento 1"))
100
- with col2:
101
- if entry['graph2']:
102
- img_bytes2 = base64.b64decode(entry['graph2'])
103
- st.image(img_bytes2, caption=t.get("graph_doc2", "Gráfico documento 2"))
104
- except Exception as e:
105
- st.error(t.get("graph_display_error", f"No se pudieron mostrar los gráficos: {str(e)}"))
106
-
107
- # Histórico de Conversaciones con el ChatBot
108
- with st.expander(t.get("chatbot_history", "Histórico de Conversaciones con el ChatBot")):
109
- if 'chat_history' in username and username['chat_history']:
110
- for i, chat in enumerate(username['chat_history']):
111
- st.subheader(f"{t.get('conversation', 'Conversación')} {i+1} - {chat['timestamp']}")
112
- for message in chat['messages']:
113
- if message['role'] == 'user':
114
- st.write(f"{t.get('user', 'Usuario')}: {message['content']}")
115
- else:
116
- st.write(f"{t.get('assistant', 'Asistente')}: {message['content']}")
117
- st.write("---")
118
- else:
119
- st.write(t.get("no_chat_history", "No se encontraron conversaciones con el ChatBot."))
120
-
121
- # Añadir logs para depuración
122
- if st.checkbox(t.get("show_debug_data", "Mostrar datos de depuración")):
123
- st.write(t.get("student_debug_data", "Datos del estudiante (para depuración):"))
124
- st.json(username)
125
-
126
- # Mostrar conteo de tipos de análisis
127
- analysis_types = [entry['analysis_type'] for entry in username['entries']]
128
- type_counts = {t: analysis_types.count(t) for t in set(analysis_types)}
129
- st.write("Conteo de tipos de análisis:")
130
- st.write(type_counts)
131
-
132
-
133
-
134
-
135
- '''
136
- ##########versión 25-9-2024---02:30 ################ OK (username)####################
137
-
138
- def display_student_progress(username, lang_code, t, student_data):
139
- st.title(f"{t.get('progress_of', 'Progreso de')} {username}")
140
-
141
- if not student_data or len(student_data.get('entries', [])) == 0:
142
- st.warning(t.get("no_data_warning", "No se encontraron datos para este estudiante."))
143
- st.info(t.get("try_analysis", "Intenta realizar algunos análisis de texto primero."))
144
- return
145
-
146
- with st.expander(t.get("activities_summary", "Resumen de Actividades"), expanded=True):
147
- total_entries = len(student_data['entries'])
148
- st.write(f"{t.get('total_analyses', 'Total de análisis realizados')}: {total_entries}")
149
-
150
- # Gráfico de tipos de análisis
151
- analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
152
- analysis_counts = pd.Series(analysis_types).value_counts()
153
- fig, ax = plt.subplots()
154
- analysis_counts.plot(kind='bar', ax=ax)
155
- ax.set_title(t.get("analysis_types_chart", "Tipos de análisis realizados"))
156
- ax.set_xlabel(t.get("analysis_type", "Tipo de análisis"))
157
- ax.set_ylabel(t.get("count", "Cantidad"))
158
- st.pyplot(fig)
159
-
160
- # Mostrar los últimos análisis morfosintácticos
161
- with st.expander(t.get("morphosyntax_history", "Histórico de Análisis Morfosintácticos")):
162
- morphosyntax_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'morphosyntax']
163
- for entry in morphosyntax_entries[:5]: # Mostrar los últimos 5
164
- st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
165
- if 'arc_diagrams' in entry and entry['arc_diagrams']:
166
- st.components.v1.html(entry['arc_diagrams'][0], height=300, scrolling=True)
167
-
168
- # Añadir secciones similares para análisis semánticos y discursivos si es necesario
169
-
170
- # Mostrar el historial de chat
171
- with st.expander(t.get("chat_history", "Historial de Chat")):
172
- if 'chat_history' in student_data:
173
- for chat in student_data['chat_history'][:5]: # Mostrar las últimas 5 conversaciones
174
- st.subheader(f"{t.get('chat_from', 'Chat del')} {chat['timestamp']}")
175
- for message in chat['messages']:
176
- st.write(f"{message['role'].capitalize()}: {message['content']}")
177
- st.write("---")
178
- else:
179
- st.write(t.get("no_chat_history", "No hay historial de chat disponible."))
180
-
181
-
182
- ##########versión 24-9-2024---17:30 ################ OK FROM--V2 de def get_student_data(username)####################
183
-
184
- def display_student_progress(username, lang_code, t, student_data):
185
- if not student_data or len(student_data['entries']) == 0:
186
- st.warning(t.get("no_data_warning", "No se encontraron datos para este estudiante."))
187
- st.info(t.get("try_analysis", "Intenta realizar algunos análisis de texto primero."))
188
- return
189
-
190
- st.title(f"{t.get('progress_of', 'Progreso de')} {username}")
191
-
192
- with st.expander(t.get("activities_summary", "Resumen de Actividades y Progreso"), expanded=True):
193
- total_entries = len(student_data['entries'])
194
- st.write(f"{t.get('total_analyses', 'Total de análisis realizados')}: {total_entries}")
195
-
196
- # Gráfico de tipos de análisis
197
- analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
198
- analysis_counts = pd.Series(analysis_types).value_counts()
199
-
200
- fig, ax = plt.subplots(figsize=(8, 4))
201
- analysis_counts.plot(kind='bar', ax=ax)
202
- ax.set_title(t.get("analysis_types_chart", "Tipos de análisis realizados"))
203
- ax.set_xlabel(t.get("analysis_type", "Tipo de análisis"))
204
- ax.set_ylabel(t.get("count", "Cantidad"))
205
- st.pyplot(fig)
206
-
207
- # Histórico de Análisis Morfosintácticos
208
- with st.expander(t.get("morphosyntax_history", "Histórico de Análisis Morfosintácticos")):
209
- morphosyntax_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'morphosyntax']
210
- if not morphosyntax_entries:
211
- st.warning("No se encontraron análisis morfosintácticos.")
212
- for entry in morphosyntax_entries:
213
- st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
214
- if 'arc_diagrams' in entry and entry['arc_diagrams']:
215
- try:
216
- st.write(entry['arc_diagrams'][0], unsafe_allow_html=True)
217
- except Exception as e:
218
- logger.error(f"Error al mostrar diagrama de arco: {str(e)}")
219
- st.error("Error al mostrar el diagrama de arco.")
220
- else:
221
- st.write(t.get("no_arc_diagram", "No se encontró diagrama de arco para este análisis."))
222
-
223
- # Histórico de Análisis Semánticos
224
- with st.expander(t.get("semantic_history", "Histórico de Análisis Semánticos")):
225
- semantic_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'semantic']
226
- if not semantic_entries:
227
- st.warning("No se encontraron análisis semánticos.")
228
- for entry in semantic_entries:
229
- st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
230
- if 'key_concepts' in entry:
231
- st.write(t.get("key_concepts", "Conceptos clave:"))
232
- concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in entry['key_concepts']])
233
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
234
- if 'graph' in entry:
235
- try:
236
- img_bytes = base64.b64decode(entry['graph'])
237
- st.image(img_bytes, caption=t.get("conceptual_relations_graph", "Gráfico de relaciones conceptuales"))
238
- except Exception as e:
239
- logger.error(f"Error al mostrar gráfico semántico: {str(e)}")
240
- st.error(t.get("graph_display_error", f"No se pudo mostrar el gráfico: {str(e)}"))
241
-
242
- # Histórico de Análisis Discursivos
243
- with st.expander(t.get("discourse_history", "Histórico de Análisis Discursivos")):
244
- discourse_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'discourse']
245
- for entry in discourse_entries:
246
- st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
247
- for i in [1, 2]:
248
- if f'key_concepts{i}' in entry:
249
- st.write(f"{t.get('key_concepts', 'Conceptos clave')} {t.get('document', 'documento')} {i}:")
250
- concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in entry[f'key_concepts{i}']])
251
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
252
- try:
253
- if 'combined_graph' in entry and entry['combined_graph']:
254
- img_bytes = base64.b64decode(entry['combined_graph'])
255
- st.image(img_bytes, caption=t.get("combined_graph", "Gráfico combinado"))
256
- elif 'graph1' in entry and 'graph2' in entry:
257
- col1, col2 = st.columns(2)
258
- with col1:
259
- if entry['graph1']:
260
- img_bytes1 = base64.b64decode(entry['graph1'])
261
- st.image(img_bytes1, caption=t.get("graph_doc1", "Gráfico documento 1"))
262
- with col2:
263
- if entry['graph2']:
264
- img_bytes2 = base64.b64decode(entry['graph2'])
265
- st.image(img_bytes2, caption=t.get("graph_doc2", "Gráfico documento 2"))
266
- except Exception as e:
267
- st.error(t.get("graph_display_error", f"No se pudieron mostrar los gráficos: {str(e)}"))
268
-
269
- # Histórico de Conversaciones con el ChatBot
270
- with st.expander(t.get("chatbot_history", "Histórico de Conversaciones con el ChatBot")):
271
- if 'chat_history' in student_data and student_data['chat_history']:
272
- for i, chat in enumerate(student_data['chat_history']):
273
- st.subheader(f"{t.get('conversation', 'Conversación')} {i+1} - {chat['timestamp']}")
274
- for message in chat['messages']:
275
- if message['role'] == 'user':
276
- st.write(f"{t.get('user', 'Usuario')}: {message['content']}")
277
- else:
278
- st.write(f"{t.get('assistant', 'Asistente')}: {message['content']}")
279
- st.write("---")
280
- else:
281
- st.write(t.get("no_chat_history", "No se encontraron conversaciones con el ChatBot."))
282
-
283
- # Añadir logs para depuración
284
- if st.checkbox(t.get("show_debug_data", "Mostrar datos de depuración")):
285
- st.write(t.get("student_debug_data", "Datos del estudiante (para depuración):"))
286
- st.json(student_data)
287
-
288
- # Mostrar conteo de tipos de análisis
289
- analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
290
- type_counts = {t: analysis_types.count(t) for t in set(analysis_types)}
291
- st.write("Conteo de tipos de análisis:")
292
- st.write(type_counts)
293
-
294
-
295
- #############################--- Update 16:00 24-9 #########################################
296
- def display_student_progress(username, lang_code, t, student_data):
297
- try:
298
- st.subheader(t.get('student_activities', 'Student Activitie'))
299
-
300
- if not student_data or all(len(student_data.get(key, [])) == 0 for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']):
301
- st.warning(t.get('no_data_warning', 'No analysis data found for this student.'))
302
- return
303
-
304
- # Resumen de actividades
305
- total_analyses = sum(len(student_data.get(key, [])) for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses'])
306
- st.write(f"{t.get('total_analyses', 'Total analyses performed')}: {total_analyses}")
307
-
308
- # Gráfico de tipos de análisis
309
- analysis_counts = {
310
- t.get('morpho_analyses', 'Morphosyntactic Analyses'): len(student_data.get('morphosyntax_analyses', [])),
311
- t.get('semantic_analyses', 'Semantic Analyses'): len(student_data.get('semantic_analyses', [])),
312
- t.get('discourse_analyses', 'Discourse Analyses'): len(student_data.get('discourse_analyses', []))
313
- }
314
- # Configurar el estilo de seaborn para un aspecto más atractivo
315
- sns.set_style("whitegrid")
316
-
317
- # Crear una figura más pequeña
318
- fig, ax = plt.subplots(figsize=(6, 4))
319
-
320
- # Usar colores más atractivos
321
- colors = ['#ff9999', '#66b3ff', '#99ff99']
322
-
323
- # Crear el gráfico de barras
324
- bars = ax.bar(analysis_counts.keys(), analysis_counts.values(), color=colors)
325
-
326
- # Añadir etiquetas de valor encima de cada barra
327
- for bar in bars:
328
- height = bar.get_height()
329
- ax.text(bar.get_x() + bar.get_width()/2., height,
330
- f'{height}',
331
- ha='center', va='bottom')
332
-
333
- # Configurar el título y las etiquetas
334
- ax.set_title(t.get('analysis_types_chart', 'Types of analyses performed'), fontsize=12)
335
- ax.set_ylabel(t.get('count', 'Count'), fontsize=10)
336
-
337
- # Rotar las etiquetas del eje x para mejor legibilidad
338
- plt.xticks(rotation=45, ha='right')
339
-
340
- # Ajustar el diseño para que todo quepa
341
- plt.tight_layout()
342
-
343
- # Mostrar el gráfico en Streamlit
344
- st.pyplot(fig)
345
-
346
- # Mostrar los últimos análisis
347
- for analysis_type in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']:
348
- with st.expander(t.get(f'{analysis_type}_expander', f'{analysis_type.capitalize()} History')):
349
- for analysis in student_data.get(analysis_type, [])[:5]: # Mostrar los últimos 5
350
- st.subheader(f"{t.get('analysis_from', 'Analysis from')} {analysis.get('timestamp', 'N/A')}")
351
- if analysis_type == 'morphosyntax_analyses':
352
- if 'arc_diagrams' in analysis:
353
- st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
354
- elif analysis_type == 'semantic_analyses':
355
- if 'key_concepts' in analysis:
356
- st.write(t.get('key_concepts', 'Key concepts'))
357
- st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis['key_concepts']]))
358
- if 'graph' in analysis:
359
- st.image(base64.b64decode(analysis['graph']))
360
- elif analysis_type == 'discourse_analyses':
361
- for i in [1, 2]:
362
- if f'key_concepts{i}' in analysis:
363
- st.write(f"{t.get('key_concepts', 'Key concepts')} {t.get('document', 'Document')} {i}")
364
- st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis[f'key_concepts{i}']]))
365
- if 'combined_graph' in analysis:
366
- st.image(base64.b64decode(analysis['combined_graph']))
367
-
368
- # Mostrar el historial de chat
369
- with st.expander(t.get('chat_history_expander', 'Chat History')):
370
- for chat in student_data.get('chat_history', [])[:5]: # Mostrar las últimas 5 conversaciones
371
- st.subheader(f"{t.get('chat_from', 'Chat from')} {chat.get('timestamp', 'N/A')}")
372
- for message in chat.get('messages', []):
373
- st.write(f"{message.get('role', 'Unknown').capitalize()}: {message.get('content', 'No content')}")
374
- st.write("---")
375
-
376
- except Exception as e:
377
- logger.error(f"Error in display_student_progress: {str(e)}", exc_info=True)
378
- st.error(t.get('error_loading_progress', 'Error loading student progress. Please try again later.'))
379
-
380
-
381
-
382
-
383
-
384
-
385
-
386
-
387
-
388
-
389
-
390
-
391
-
392
-
393
-
394
-
395
-
396
-
397
-
398
-
399
-
400
-
401
-
402
-
403
-
404
-
405
-
406
- #####################################################################
407
- def display_student_progress(username, lang_code, t, student_data):
408
- st.subheader(t['student_progress'])
409
-
410
- if not student_data or all(len(student_data[key]) == 0 for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']):
411
- st.warning(t['no_data_warning'])
412
- return
413
-
414
- # Resumen de actividades
415
- total_analyses = sum(len(student_data[key]) for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses'])
416
- st.write(f"{t['total_analyses']}: {total_analyses}")
417
-
418
- # Gráfico de tipos de análisis
419
- analysis_counts = {
420
- t['morpho_analyses']: len(student_data['morphosyntax_analyses']),
421
- t['semantic_analyses']: len(student_data['semantic_analyses']),
422
- t['discourse_analyses']: len(student_data['discourse_analyses'])
423
- }
424
- fig, ax = plt.subplots()
425
- ax.bar(analysis_counts.keys(), analysis_counts.values())
426
- ax.set_title(t['analysis_types_chart'])
427
- st.pyplot(fig)
428
-
429
- # Mostrar los últimos análisis
430
- for analysis_type in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']:
431
- with st.expander(t[f'{analysis_type}_expander']):
432
- for analysis in student_data[analysis_type][:5]: # Mostrar los últimos 5
433
- st.subheader(f"{t['analysis_from']} {analysis['timestamp']}")
434
- if analysis_type == 'morphosyntax_analyses':
435
- if 'arc_diagrams' in analysis:
436
- st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
437
- elif analysis_type == 'semantic_analyses':
438
- if 'key_concepts' in analysis:
439
- st.write(t['key_concepts'])
440
- st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis['key_concepts']]))
441
- if 'graph' in analysis:
442
- st.image(base64.b64decode(analysis['graph']))
443
- elif analysis_type == 'discourse_analyses':
444
- for i in [1, 2]:
445
- if f'key_concepts{i}' in analysis:
446
- st.write(f"{t['key_concepts']} {t['document']} {i}")
447
- st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis[f'key_concepts{i}']]))
448
- if 'combined_graph' in analysis:
449
- st.image(base64.b64decode(analysis['combined_graph']))
450
-
451
- # Mostrar el historial de chat
452
- with st.expander(t['chat_history_expander']):
453
- for chat in student_data['chat_history'][:5]: # Mostrar las últimas 5 conversaciones
454
- st.subheader(f"{t['chat_from']} {chat['timestamp']}")
455
- for message in chat['messages']:
456
- st.write(f"{message['role'].capitalize()}: {message['content']}")
457
- st.write("---")
458
-
459
-
460
-
461
- def display_student_progress(username, lang_code, t, student_data):
462
- st.subheader(t['student_activities'])
463
-
464
- if not student_data or all(len(student_data[key]) == 0 for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']):
465
- st.warning(t['no_data_warning'])
466
- return
467
-
468
- # Resumen de actividades
469
- total_analyses = sum(len(student_data[key]) for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses'])
470
- st.write(f"{t['total_analyses']}: {total_analyses}")
471
-
472
- # Gráfico de tipos de análisis
473
- analysis_counts = {
474
- t['morphological_analysis']: len(student_data['morphosyntax_analyses']),
475
- t['semantic_analyses']: len(student_data['semantic_analyses']),
476
- t['discourse_analyses']: len(student_data['discourse_analyses'])
477
- }
478
- fig, ax = plt.subplots()
479
- ax.bar(analysis_counts.keys(), analysis_counts.values())
480
- ax.set_title(t['analysis_types_chart'])
481
- st.pyplot(fig)
482
-
483
- # Mostrar los últimos análisis
484
- for analysis_type in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']:
485
- with st.expander(t[f'{analysis_type}_expander']):
486
- for analysis in student_data[analysis_type][:5]: # Mostrar los últimos 5
487
- st.subheader(f"{t['analysis_from']} {analysis['timestamp']}")
488
- if analysis_type == 'morphosyntax_analyses':
489
- if 'arc_diagrams' in analysis:
490
- st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
491
- elif analysis_type == 'semantic_analyses':
492
- if 'key_concepts' in analysis:
493
- st.write(t['key_concepts'])
494
- st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis['key_concepts']]))
495
- if 'graph' in analysis:
496
- st.image(base64.b64decode(analysis['graph']))
497
- elif analysis_type == 'discourse_analyses':
498
- for i in [1, 2]:
499
- if f'key_concepts{i}' in analysis:
500
- st.write(f"{t['key_concepts']} {t['document']} {i}")
501
- st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis[f'key_concepts{i}']]))
502
- if 'combined_graph' in analysis:
503
- st.image(base64.b64decode(analysis['combined_graph']))
504
-
505
- # Mostrar el historial de chat
506
- with st.expander(t['chat_history_expander']):
507
- for chat in student_data['chat_history'][:5]: # Mostrar las últimas 5 conversaciones
508
- st.subheader(f"{t['chat_from']} {chat['timestamp']}")
509
- for message in chat['messages']:
510
- st.write(f"{message['role'].capitalize()}: {message['content']}")
511
- st.write("---")
512
-
513
-
514
-
515
-
516
- def display_student_progress(username, lang_code, t, student_data):
517
- st.subheader(t['student_activities'])
518
-
519
- if not student_data or all(len(student_data[key]) == 0 for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']):
520
- st.warning(t['no_data_warning'])
521
- return
522
-
523
- # Resumen de actividades
524
- total_analyses = sum(len(student_data[key]) for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses'])
525
- st.write(f"{t['total_analyses']}: {total_analyses}")
526
-
527
- # Gráfico de tipos de análisis
528
- analysis_counts = {
529
- t['morphological_analysis']: len(student_data['morphosyntax_analyses']),
530
- t['semantic_analyses']: len(student_data['semantic_analyses']),
531
- t['discourse_analyses']: len(student_data['discourse_analyses'])
532
- }
533
- fig, ax = plt.subplots()
534
- ax.bar(analysis_counts.keys(), analysis_counts.values())
535
- ax.set_title(t['analysis_types_chart'])
536
- st.pyplot(fig)
537
-
538
- # Mostrar los últimos análisis
539
- for analysis_type in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']:
540
- with st.expander(t[f'{analysis_type}_expander']):
541
- for analysis in student_data[analysis_type][:5]: # Mostrar los últimos 5
542
- st.subheader(f"{t['analysis_from']} {analysis['timestamp']}")
543
- if analysis_type == 'morphosyntax_analyses':
544
- if 'arc_diagrams' in analysis:
545
- st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
546
- elif analysis_type == 'semantic_analyses':
547
- if 'key_concepts' in analysis:
548
- st.write(t['key_concepts'])
549
- st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis['key_concepts']]))
550
- if 'graph' in analysis:
551
- st.image(base64.b64decode(analysis['graph']))
552
- elif analysis_type == 'discourse_analyses':
553
- for i in [1, 2]:
554
- if f'key_concepts{i}' in analysis:
555
- st.write(f"{t['key_concepts']} {t['document']} {i}")
556
- st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis[f'key_concepts{i}']]))
557
- if 'combined_graph' in analysis:
558
- st.image(base64.b64decode(analysis['combined_graph']))
559
-
560
- # Mostrar el historial de chat
561
- with st.expander(t['chat_history_expander']):
562
- for chat in student_data['chat_history'][:5]: # Mostrar las últimas 5 conversaciones
563
- st.subheader(f"{t['chat_from']} {chat['timestamp']}")
564
- for message in chat['messages']:
565
- st.write(f"{message['role'].capitalize()}: {message['content']}")
566
- st.write("---")
567
-
568
-
569
-
570
-
571
- def display_student_progress(username, lang_code, t):
572
- st.subheader(t['student_activities'])
573
- st.write(f"{t['activities_message']} {username}")
574
-
575
- # Aquí puedes agregar más contenido estático o placeholder
576
- st.info(t['activities_placeholder'])
577
-
578
- # Si necesitas mostrar algún dato, puedes usar datos de ejemplo o placeholders
579
- col1, col2, col3 = st.columns(3)
580
- col1.metric(t['morpho_analyses'], "5") # Ejemplo de dato
581
- col2.metric(t['semantic_analyses'], "3") # Ejemplo de dato
582
- col3.metric(t['discourse_analyses'], "2") # Ejemplo de dato
583
-
584
-
585
-
586
- def display_student_progress(username, lang_code, t):
587
- st.title(f"Actividades de {username}")
588
-
589
- # Obtener todos los datos del estudiante
590
- student_data = get_student_data(username)
591
-
592
- if not student_data or len(student_data.get('entries', [])) == 0:
593
- st.warning("No se encontraron datos de análisis para este estudiante.")
594
- st.info("Intenta realizar algunos análisis de texto primero.")
595
- return
596
-
597
- # Resumen de actividades
598
- with st.expander("Resumen de Actividades", expanded=True):
599
- total_entries = len(student_data['entries'])
600
- st.write(f"Total de análisis realizados: {total_entries}")
601
-
602
- # Gráfico de tipos de análisis
603
- analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
604
- analysis_counts = pd.Series(analysis_types).value_counts()
605
- fig, ax = plt.subplots()
606
- analysis_counts.plot(kind='bar', ax=ax)
607
- ax.set_title("Tipos de análisis realizados")
608
- ax.set_xlabel("Tipo de análisis")
609
- ax.set_ylabel("Cantidad")
610
- st.pyplot(fig)
611
-
612
- # Histórico de Análisis Morfosintácticos
613
- with st.expander("Histórico de Análisis Morfosintácticos"):
614
- morpho_analyses = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'morphosyntax']
615
- for analysis in morpho_analyses[:5]: # Mostrar los últimos 5
616
- st.subheader(f"Análisis del {analysis['timestamp']}")
617
- if 'arc_diagrams' in analysis:
618
- st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
619
-
620
- # Histórico de Análisis Semánticos
621
- with st.expander("Histórico de Análisis Semánticos"):
622
- semantic_analyses = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'semantic']
623
- for analysis in semantic_analyses[:5]: # Mostrar los últimos 5
624
- st.subheader(f"Análisis del {analysis['timestamp']}")
625
- if 'key_concepts' in analysis:
626
- concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in analysis['key_concepts']])
627
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
628
- if 'graph' in analysis:
629
- try:
630
- img_bytes = base64.b64decode(analysis['graph'])
631
- st.image(img_bytes, caption="Gráfico de relaciones conceptuales")
632
- except Exception as e:
633
- st.error(f"No se pudo mostrar el gráfico: {str(e)}")
634
-
635
- # Histórico de Análisis Discursivos
636
- with st.expander("Histórico de Análisis Discursivos"):
637
- discourse_analyses = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'discourse']
638
- for analysis in discourse_analyses[:5]: # Mostrar los últimos 5
639
- st.subheader(f"Análisis del {analysis['timestamp']}")
640
- for i in [1, 2]:
641
- if f'key_concepts{i}' in analysis:
642
- concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in analysis[f'key_concepts{i}']])
643
- st.write(f"Conceptos clave del documento {i}:")
644
- st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
645
- if 'combined_graph' in analysis:
646
- try:
647
- img_bytes = base64.b64decode(analysis['combined_graph'])
648
- st.image(img_bytes)
649
- except Exception as e:
650
- st.error(f"No se pudo mostrar el gráfico combinado: {str(e)}")
651
-
652
- # Histórico de Conversaciones con el ChatBot
653
- with st.expander("Histórico de Conversaciones con el ChatBot"):
654
- if 'chat_history' in student_data:
655
- for i, chat in enumerate(student_data['chat_history'][:5]): # Mostrar las últimas 5 conversaciones
656
- st.subheader(f"Conversación {i+1} - {chat['timestamp']}")
657
- for message in chat['messages']:
658
- st.write(f"{message['role'].capitalize()}: {message['content']}")
659
- st.write("---")
660
- else:
661
- st.write("No se encontraron conversaciones con el ChatBot.")
662
-
663
- # Opción para mostrar datos de depuración
664
- if st.checkbox("Mostrar datos de depuración"):
665
- st.write("Datos del estudiante (para depuración):")
666
- st.json(student_data)
667
-
 
668
  '''
 
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
+ logger = logging.getLogger(__name__)
20
+
21
+ ###################################################################################
22
+
23
+ def display_student_progress(username, lang_code, t, student_data):
24
+ if not student_data or len(student_data['entries']) == 0:
25
+ st.warning(t.get("no_data_warning", "No se encontraron datos para este estudiante."))
26
+ st.info(t.get("try_analysis", "Intenta realizar algunos análisis de texto primero."))
27
+ return
28
+
29
+ st.title(f"{t.get('progress_of', 'Progreso de')} {username}")
30
+
31
+ with st.expander(t.get("activities_summary", "Resumen de Actividades y Progreso"), expanded=True):
32
+ total_entries = len(student_data['entries'])
33
+ st.write(f"{t.get('total_analyses', 'Total de análisis realizados')}: {total_entries}")
34
+
35
+ # Gráfico de tipos de análisis
36
+ analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
37
+ analysis_counts = pd.Series(analysis_types).value_counts()
38
+
39
+ fig, ax = plt.subplots(figsize=(8, 4))
40
+ analysis_counts.plot(kind='bar', ax=ax)
41
+ ax.set_title(t.get("analysis_types_chart", "Tipos de análisis realizados"))
42
+ ax.set_xlabel(t.get("analysis_type", "Tipo de análisis"))
43
+ ax.set_ylabel(t.get("count", "Cantidad"))
44
+ st.pyplot(fig)
45
+
46
+ # Histórico de Análisis Morfosintácticos
47
+ with st.expander(t.get("morphosyntax_history", "Histórico de Análisis Morfosintácticos")):
48
+ morphosyntax_entries = [entry for entry in username['entries'] if entry['analysis_type'] == 'morphosyntax']
49
+ if not morphosyntax_entries:
50
+ st.warning("No se encontraron análisis morfosintácticos.")
51
+ for entry in morphosyntax_entries:
52
+ st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
53
+ if 'arc_diagrams' in entry and entry['arc_diagrams']:
54
+ try:
55
+ st.write(entry['arc_diagrams'][0], unsafe_allow_html=True)
56
+ except Exception as e:
57
+ logger.error(f"Error al mostrar diagrama de arco: {str(e)}")
58
+ st.error("Error al mostrar el diagrama de arco.")
59
+ else:
60
+ st.write(t.get("no_arc_diagram", "No se encontró diagrama de arco para este análisis."))
61
+
62
+ # Histórico de Análisis Semánticos
63
+ with st.expander(t.get("semantic_history", "Histórico de Análisis Semánticos")):
64
+ semantic_entries = [entry for entry in username['entries'] if entry['analysis_type'] == 'semantic']
65
+ if not semantic_entries:
66
+ st.warning("No se encontraron análisis semánticos.")
67
+ for entry in semantic_entries:
68
+ st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
69
+ if 'key_concepts' in entry:
70
+ st.write(t.get("key_concepts", "Conceptos clave:"))
71
+ concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in entry['key_concepts']])
72
+ st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
73
+ if 'graph' in entry:
74
+ try:
75
+ img_bytes = base64.b64decode(entry['graph'])
76
+ st.image(img_bytes, caption=t.get("conceptual_relations_graph", "Gráfico de relaciones conceptuales"))
77
+ except Exception as e:
78
+ logger.error(f"Error al mostrar gráfico semántico: {str(e)}")
79
+ st.error(t.get("graph_display_error", f"No se pudo mostrar el gráfico: {str(e)}"))
80
+
81
+ # Histórico de Análisis Discursivos
82
+ with st.expander(t.get("discourse_history", "Histórico de Análisis Discursivos")):
83
+ discourse_entries = [entry for entry in username['entries'] if entry['analysis_type'] == 'discourse']
84
+ for entry in discourse_entries:
85
+ st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
86
+ for i in [1, 2]:
87
+ if f'key_concepts{i}' in entry:
88
+ st.write(f"{t.get('key_concepts', 'Conceptos clave')} {t.get('document', 'documento')} {i}:")
89
+ concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in entry[f'key_concepts{i}']])
90
+ st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
91
+ try:
92
+ if 'combined_graph' in entry and entry['combined_graph']:
93
+ img_bytes = base64.b64decode(entry['combined_graph'])
94
+ st.image(img_bytes, caption=t.get("combined_graph", "Gráfico combinado"))
95
+ elif 'graph1' in entry and 'graph2' in entry:
96
+ col1, col2 = st.columns(2)
97
+ with col1:
98
+ if entry['graph1']:
99
+ img_bytes1 = base64.b64decode(entry['graph1'])
100
+ st.image(img_bytes1, caption=t.get("graph_doc1", "Gráfico documento 1"))
101
+ with col2:
102
+ if entry['graph2']:
103
+ img_bytes2 = base64.b64decode(entry['graph2'])
104
+ st.image(img_bytes2, caption=t.get("graph_doc2", "Gráfico documento 2"))
105
+ except Exception as e:
106
+ st.error(t.get("graph_display_error", f"No se pudieron mostrar los gráficos: {str(e)}"))
107
+
108
+ # Histórico de Conversaciones con el ChatBot
109
+ with st.expander(t.get("chatbot_history", "Histórico de Conversaciones con el ChatBot")):
110
+ if 'chat_history' in username and username['chat_history']:
111
+ for i, chat in enumerate(username['chat_history']):
112
+ st.subheader(f"{t.get('conversation', 'Conversación')} {i+1} - {chat['timestamp']}")
113
+ for message in chat['messages']:
114
+ if message['role'] == 'user':
115
+ st.write(f"{t.get('user', 'Usuario')}: {message['content']}")
116
+ else:
117
+ st.write(f"{t.get('assistant', 'Asistente')}: {message['content']}")
118
+ st.write("---")
119
+ else:
120
+ st.write(t.get("no_chat_history", "No se encontraron conversaciones con el ChatBot."))
121
+
122
+ # Añadir logs para depuración
123
+ if st.checkbox(t.get("show_debug_data", "Mostrar datos de depuración")):
124
+ st.write(t.get("student_debug_data", "Datos del estudiante (para depuración):"))
125
+ st.json(username)
126
+
127
+ # Mostrar conteo de tipos de análisis
128
+ analysis_types = [entry['analysis_type'] for entry in username['entries']]
129
+ type_counts = {t: analysis_types.count(t) for t in set(analysis_types)}
130
+ st.write("Conteo de tipos de análisis:")
131
+ st.write(type_counts)
132
+
133
+
134
+
135
+
136
+ '''
137
+ ##########versión 25-9-2024---02:30 ################ OK (username)####################
138
+
139
+ def display_student_progress(username, lang_code, t, student_data):
140
+ st.title(f"{t.get('progress_of', 'Progreso de')} {username}")
141
+
142
+ if not student_data or len(student_data.get('entries', [])) == 0:
143
+ st.warning(t.get("no_data_warning", "No se encontraron datos para este estudiante."))
144
+ st.info(t.get("try_analysis", "Intenta realizar algunos análisis de texto primero."))
145
+ return
146
+
147
+ with st.expander(t.get("activities_summary", "Resumen de Actividades"), expanded=True):
148
+ total_entries = len(student_data['entries'])
149
+ st.write(f"{t.get('total_analyses', 'Total de análisis realizados')}: {total_entries}")
150
+
151
+ # Gráfico de tipos de análisis
152
+ analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
153
+ analysis_counts = pd.Series(analysis_types).value_counts()
154
+ fig, ax = plt.subplots()
155
+ analysis_counts.plot(kind='bar', ax=ax)
156
+ ax.set_title(t.get("analysis_types_chart", "Tipos de análisis realizados"))
157
+ ax.set_xlabel(t.get("analysis_type", "Tipo de análisis"))
158
+ ax.set_ylabel(t.get("count", "Cantidad"))
159
+ st.pyplot(fig)
160
+
161
+ # Mostrar los últimos análisis morfosintácticos
162
+ with st.expander(t.get("morphosyntax_history", "Histórico de Análisis Morfosintácticos")):
163
+ morphosyntax_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'morphosyntax']
164
+ for entry in morphosyntax_entries[:5]: # Mostrar los últimos 5
165
+ st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
166
+ if 'arc_diagrams' in entry and entry['arc_diagrams']:
167
+ st.components.v1.html(entry['arc_diagrams'][0], height=300, scrolling=True)
168
+
169
+ # Añadir secciones similares para análisis semánticos y discursivos si es necesario
170
+
171
+ # Mostrar el historial de chat
172
+ with st.expander(t.get("chat_history", "Historial de Chat")):
173
+ if 'chat_history' in student_data:
174
+ for chat in student_data['chat_history'][:5]: # Mostrar las últimas 5 conversaciones
175
+ st.subheader(f"{t.get('chat_from', 'Chat del')} {chat['timestamp']}")
176
+ for message in chat['messages']:
177
+ st.write(f"{message['role'].capitalize()}: {message['content']}")
178
+ st.write("---")
179
+ else:
180
+ st.write(t.get("no_chat_history", "No hay historial de chat disponible."))
181
+
182
+
183
+ ##########versión 24-9-2024---17:30 ################ OK FROM--V2 de def get_student_data(username)####################
184
+
185
+ def display_student_progress(username, lang_code, t, student_data):
186
+ if not student_data or len(student_data['entries']) == 0:
187
+ st.warning(t.get("no_data_warning", "No se encontraron datos para este estudiante."))
188
+ st.info(t.get("try_analysis", "Intenta realizar algunos análisis de texto primero."))
189
+ return
190
+
191
+ st.title(f"{t.get('progress_of', 'Progreso de')} {username}")
192
+
193
+ with st.expander(t.get("activities_summary", "Resumen de Actividades y Progreso"), expanded=True):
194
+ total_entries = len(student_data['entries'])
195
+ st.write(f"{t.get('total_analyses', 'Total de análisis realizados')}: {total_entries}")
196
+
197
+ # Gráfico de tipos de análisis
198
+ analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
199
+ analysis_counts = pd.Series(analysis_types).value_counts()
200
+
201
+ fig, ax = plt.subplots(figsize=(8, 4))
202
+ analysis_counts.plot(kind='bar', ax=ax)
203
+ ax.set_title(t.get("analysis_types_chart", "Tipos de análisis realizados"))
204
+ ax.set_xlabel(t.get("analysis_type", "Tipo de análisis"))
205
+ ax.set_ylabel(t.get("count", "Cantidad"))
206
+ st.pyplot(fig)
207
+
208
+ # Histórico de Análisis Morfosintácticos
209
+ with st.expander(t.get("morphosyntax_history", "Histórico de Análisis Morfosintácticos")):
210
+ morphosyntax_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'morphosyntax']
211
+ if not morphosyntax_entries:
212
+ st.warning("No se encontraron análisis morfosintácticos.")
213
+ for entry in morphosyntax_entries:
214
+ st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
215
+ if 'arc_diagrams' in entry and entry['arc_diagrams']:
216
+ try:
217
+ st.write(entry['arc_diagrams'][0], unsafe_allow_html=True)
218
+ except Exception as e:
219
+ logger.error(f"Error al mostrar diagrama de arco: {str(e)}")
220
+ st.error("Error al mostrar el diagrama de arco.")
221
+ else:
222
+ st.write(t.get("no_arc_diagram", "No se encontró diagrama de arco para este análisis."))
223
+
224
+ # Histórico de Análisis Semánticos
225
+ with st.expander(t.get("semantic_history", "Histórico de Análisis Semánticos")):
226
+ semantic_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'semantic']
227
+ if not semantic_entries:
228
+ st.warning("No se encontraron análisis semánticos.")
229
+ for entry in semantic_entries:
230
+ st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
231
+ if 'key_concepts' in entry:
232
+ st.write(t.get("key_concepts", "Conceptos clave:"))
233
+ concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in entry['key_concepts']])
234
+ st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
235
+ if 'graph' in entry:
236
+ try:
237
+ img_bytes = base64.b64decode(entry['graph'])
238
+ st.image(img_bytes, caption=t.get("conceptual_relations_graph", "Gráfico de relaciones conceptuales"))
239
+ except Exception as e:
240
+ logger.error(f"Error al mostrar gráfico semántico: {str(e)}")
241
+ st.error(t.get("graph_display_error", f"No se pudo mostrar el gráfico: {str(e)}"))
242
+
243
+ # Histórico de Análisis Discursivos
244
+ with st.expander(t.get("discourse_history", "Histórico de Análisis Discursivos")):
245
+ discourse_entries = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'discourse']
246
+ for entry in discourse_entries:
247
+ st.subheader(f"{t.get('analysis_of', 'Análisis del')} {entry['timestamp']}")
248
+ for i in [1, 2]:
249
+ if f'key_concepts{i}' in entry:
250
+ st.write(f"{t.get('key_concepts', 'Conceptos clave')} {t.get('document', 'documento')} {i}:")
251
+ concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in entry[f'key_concepts{i}']])
252
+ st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
253
+ try:
254
+ if 'combined_graph' in entry and entry['combined_graph']:
255
+ img_bytes = base64.b64decode(entry['combined_graph'])
256
+ st.image(img_bytes, caption=t.get("combined_graph", "Gráfico combinado"))
257
+ elif 'graph1' in entry and 'graph2' in entry:
258
+ col1, col2 = st.columns(2)
259
+ with col1:
260
+ if entry['graph1']:
261
+ img_bytes1 = base64.b64decode(entry['graph1'])
262
+ st.image(img_bytes1, caption=t.get("graph_doc1", "Gráfico documento 1"))
263
+ with col2:
264
+ if entry['graph2']:
265
+ img_bytes2 = base64.b64decode(entry['graph2'])
266
+ st.image(img_bytes2, caption=t.get("graph_doc2", "Gráfico documento 2"))
267
+ except Exception as e:
268
+ st.error(t.get("graph_display_error", f"No se pudieron mostrar los gráficos: {str(e)}"))
269
+
270
+ # Histórico de Conversaciones con el ChatBot
271
+ with st.expander(t.get("chatbot_history", "Histórico de Conversaciones con el ChatBot")):
272
+ if 'chat_history' in student_data and student_data['chat_history']:
273
+ for i, chat in enumerate(student_data['chat_history']):
274
+ st.subheader(f"{t.get('conversation', 'Conversación')} {i+1} - {chat['timestamp']}")
275
+ for message in chat['messages']:
276
+ if message['role'] == 'user':
277
+ st.write(f"{t.get('user', 'Usuario')}: {message['content']}")
278
+ else:
279
+ st.write(f"{t.get('assistant', 'Asistente')}: {message['content']}")
280
+ st.write("---")
281
+ else:
282
+ st.write(t.get("no_chat_history", "No se encontraron conversaciones con el ChatBot."))
283
+
284
+ # Añadir logs para depuración
285
+ if st.checkbox(t.get("show_debug_data", "Mostrar datos de depuración")):
286
+ st.write(t.get("student_debug_data", "Datos del estudiante (para depuración):"))
287
+ st.json(student_data)
288
+
289
+ # Mostrar conteo de tipos de análisis
290
+ analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
291
+ type_counts = {t: analysis_types.count(t) for t in set(analysis_types)}
292
+ st.write("Conteo de tipos de análisis:")
293
+ st.write(type_counts)
294
+
295
+
296
+ #############################--- Update 16:00 24-9 #########################################
297
+ def display_student_progress(username, lang_code, t, student_data):
298
+ try:
299
+ st.subheader(t.get('student_activities', 'Student Activitie'))
300
+
301
+ if not student_data or all(len(student_data.get(key, [])) == 0 for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']):
302
+ st.warning(t.get('no_data_warning', 'No analysis data found for this student.'))
303
+ return
304
+
305
+ # Resumen de actividades
306
+ total_analyses = sum(len(student_data.get(key, [])) for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses'])
307
+ st.write(f"{t.get('total_analyses', 'Total analyses performed')}: {total_analyses}")
308
+
309
+ # Gráfico de tipos de análisis
310
+ analysis_counts = {
311
+ t.get('morpho_analyses', 'Morphosyntactic Analyses'): len(student_data.get('morphosyntax_analyses', [])),
312
+ t.get('semantic_analyses', 'Semantic Analyses'): len(student_data.get('semantic_analyses', [])),
313
+ t.get('discourse_analyses', 'Discourse Analyses'): len(student_data.get('discourse_analyses', []))
314
+ }
315
+ # Configurar el estilo de seaborn para un aspecto más atractivo
316
+ sns.set_style("whitegrid")
317
+
318
+ # Crear una figura más pequeña
319
+ fig, ax = plt.subplots(figsize=(6, 4))
320
+
321
+ # Usar colores más atractivos
322
+ colors = ['#ff9999', '#66b3ff', '#99ff99']
323
+
324
+ # Crear el gráfico de barras
325
+ bars = ax.bar(analysis_counts.keys(), analysis_counts.values(), color=colors)
326
+
327
+ # Añadir etiquetas de valor encima de cada barra
328
+ for bar in bars:
329
+ height = bar.get_height()
330
+ ax.text(bar.get_x() + bar.get_width()/2., height,
331
+ f'{height}',
332
+ ha='center', va='bottom')
333
+
334
+ # Configurar el título y las etiquetas
335
+ ax.set_title(t.get('analysis_types_chart', 'Types of analyses performed'), fontsize=12)
336
+ ax.set_ylabel(t.get('count', 'Count'), fontsize=10)
337
+
338
+ # Rotar las etiquetas del eje x para mejor legibilidad
339
+ plt.xticks(rotation=45, ha='right')
340
+
341
+ # Ajustar el diseño para que todo quepa
342
+ plt.tight_layout()
343
+
344
+ # Mostrar el gráfico en Streamlit
345
+ st.pyplot(fig)
346
+
347
+ # Mostrar los últimos análisis
348
+ for analysis_type in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']:
349
+ with st.expander(t.get(f'{analysis_type}_expander', f'{analysis_type.capitalize()} History')):
350
+ for analysis in student_data.get(analysis_type, [])[:5]: # Mostrar los últimos 5
351
+ st.subheader(f"{t.get('analysis_from', 'Analysis from')} {analysis.get('timestamp', 'N/A')}")
352
+ if analysis_type == 'morphosyntax_analyses':
353
+ if 'arc_diagrams' in analysis:
354
+ st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
355
+ elif analysis_type == 'semantic_analyses':
356
+ if 'key_concepts' in analysis:
357
+ st.write(t.get('key_concepts', 'Key concepts'))
358
+ st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis['key_concepts']]))
359
+ if 'graph' in analysis:
360
+ st.image(base64.b64decode(analysis['graph']))
361
+ elif analysis_type == 'discourse_analyses':
362
+ for i in [1, 2]:
363
+ if f'key_concepts{i}' in analysis:
364
+ st.write(f"{t.get('key_concepts', 'Key concepts')} {t.get('document', 'Document')} {i}")
365
+ st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis[f'key_concepts{i}']]))
366
+ if 'combined_graph' in analysis:
367
+ st.image(base64.b64decode(analysis['combined_graph']))
368
+
369
+ # Mostrar el historial de chat
370
+ with st.expander(t.get('chat_history_expander', 'Chat History')):
371
+ for chat in student_data.get('chat_history', [])[:5]: # Mostrar las últimas 5 conversaciones
372
+ st.subheader(f"{t.get('chat_from', 'Chat from')} {chat.get('timestamp', 'N/A')}")
373
+ for message in chat.get('messages', []):
374
+ st.write(f"{message.get('role', 'Unknown').capitalize()}: {message.get('content', 'No content')}")
375
+ st.write("---")
376
+
377
+ except Exception as e:
378
+ logger.error(f"Error in display_student_progress: {str(e)}", exc_info=True)
379
+ st.error(t.get('error_loading_progress', 'Error loading student progress. Please try again later.'))
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+
403
+
404
+
405
+
406
+
407
+ #####################################################################
408
+ def display_student_progress(username, lang_code, t, student_data):
409
+ st.subheader(t['student_progress'])
410
+
411
+ if not student_data or all(len(student_data[key]) == 0 for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']):
412
+ st.warning(t['no_data_warning'])
413
+ return
414
+
415
+ # Resumen de actividades
416
+ total_analyses = sum(len(student_data[key]) for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses'])
417
+ st.write(f"{t['total_analyses']}: {total_analyses}")
418
+
419
+ # Gráfico de tipos de análisis
420
+ analysis_counts = {
421
+ t['morpho_analyses']: len(student_data['morphosyntax_analyses']),
422
+ t['semantic_analyses']: len(student_data['semantic_analyses']),
423
+ t['discourse_analyses']: len(student_data['discourse_analyses'])
424
+ }
425
+ fig, ax = plt.subplots()
426
+ ax.bar(analysis_counts.keys(), analysis_counts.values())
427
+ ax.set_title(t['analysis_types_chart'])
428
+ st.pyplot(fig)
429
+
430
+ # Mostrar los últimos análisis
431
+ for analysis_type in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']:
432
+ with st.expander(t[f'{analysis_type}_expander']):
433
+ for analysis in student_data[analysis_type][:5]: # Mostrar los últimos 5
434
+ st.subheader(f"{t['analysis_from']} {analysis['timestamp']}")
435
+ if analysis_type == 'morphosyntax_analyses':
436
+ if 'arc_diagrams' in analysis:
437
+ st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
438
+ elif analysis_type == 'semantic_analyses':
439
+ if 'key_concepts' in analysis:
440
+ st.write(t['key_concepts'])
441
+ st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis['key_concepts']]))
442
+ if 'graph' in analysis:
443
+ st.image(base64.b64decode(analysis['graph']))
444
+ elif analysis_type == 'discourse_analyses':
445
+ for i in [1, 2]:
446
+ if f'key_concepts{i}' in analysis:
447
+ st.write(f"{t['key_concepts']} {t['document']} {i}")
448
+ st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis[f'key_concepts{i}']]))
449
+ if 'combined_graph' in analysis:
450
+ st.image(base64.b64decode(analysis['combined_graph']))
451
+
452
+ # Mostrar el historial de chat
453
+ with st.expander(t['chat_history_expander']):
454
+ for chat in student_data['chat_history'][:5]: # Mostrar las últimas 5 conversaciones
455
+ st.subheader(f"{t['chat_from']} {chat['timestamp']}")
456
+ for message in chat['messages']:
457
+ st.write(f"{message['role'].capitalize()}: {message['content']}")
458
+ st.write("---")
459
+
460
+
461
+
462
+ def display_student_progress(username, lang_code, t, student_data):
463
+ st.subheader(t['student_activities'])
464
+
465
+ if not student_data or all(len(student_data[key]) == 0 for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']):
466
+ st.warning(t['no_data_warning'])
467
+ return
468
+
469
+ # Resumen de actividades
470
+ total_analyses = sum(len(student_data[key]) for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses'])
471
+ st.write(f"{t['total_analyses']}: {total_analyses}")
472
+
473
+ # Gráfico de tipos de análisis
474
+ analysis_counts = {
475
+ t['morphological_analysis']: len(student_data['morphosyntax_analyses']),
476
+ t['semantic_analyses']: len(student_data['semantic_analyses']),
477
+ t['discourse_analyses']: len(student_data['discourse_analyses'])
478
+ }
479
+ fig, ax = plt.subplots()
480
+ ax.bar(analysis_counts.keys(), analysis_counts.values())
481
+ ax.set_title(t['analysis_types_chart'])
482
+ st.pyplot(fig)
483
+
484
+ # Mostrar los últimos análisis
485
+ for analysis_type in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']:
486
+ with st.expander(t[f'{analysis_type}_expander']):
487
+ for analysis in student_data[analysis_type][:5]: # Mostrar los últimos 5
488
+ st.subheader(f"{t['analysis_from']} {analysis['timestamp']}")
489
+ if analysis_type == 'morphosyntax_analyses':
490
+ if 'arc_diagrams' in analysis:
491
+ st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
492
+ elif analysis_type == 'semantic_analyses':
493
+ if 'key_concepts' in analysis:
494
+ st.write(t['key_concepts'])
495
+ st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis['key_concepts']]))
496
+ if 'graph' in analysis:
497
+ st.image(base64.b64decode(analysis['graph']))
498
+ elif analysis_type == 'discourse_analyses':
499
+ for i in [1, 2]:
500
+ if f'key_concepts{i}' in analysis:
501
+ st.write(f"{t['key_concepts']} {t['document']} {i}")
502
+ st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis[f'key_concepts{i}']]))
503
+ if 'combined_graph' in analysis:
504
+ st.image(base64.b64decode(analysis['combined_graph']))
505
+
506
+ # Mostrar el historial de chat
507
+ with st.expander(t['chat_history_expander']):
508
+ for chat in student_data['chat_history'][:5]: # Mostrar las últimas 5 conversaciones
509
+ st.subheader(f"{t['chat_from']} {chat['timestamp']}")
510
+ for message in chat['messages']:
511
+ st.write(f"{message['role'].capitalize()}: {message['content']}")
512
+ st.write("---")
513
+
514
+
515
+
516
+
517
+ def display_student_progress(username, lang_code, t, student_data):
518
+ st.subheader(t['student_activities'])
519
+
520
+ if not student_data or all(len(student_data[key]) == 0 for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']):
521
+ st.warning(t['no_data_warning'])
522
+ return
523
+
524
+ # Resumen de actividades
525
+ total_analyses = sum(len(student_data[key]) for key in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses'])
526
+ st.write(f"{t['total_analyses']}: {total_analyses}")
527
+
528
+ # Gráfico de tipos de análisis
529
+ analysis_counts = {
530
+ t['morphological_analysis']: len(student_data['morphosyntax_analyses']),
531
+ t['semantic_analyses']: len(student_data['semantic_analyses']),
532
+ t['discourse_analyses']: len(student_data['discourse_analyses'])
533
+ }
534
+ fig, ax = plt.subplots()
535
+ ax.bar(analysis_counts.keys(), analysis_counts.values())
536
+ ax.set_title(t['analysis_types_chart'])
537
+ st.pyplot(fig)
538
+
539
+ # Mostrar los últimos análisis
540
+ for analysis_type in ['morphosyntax_analyses', 'semantic_analyses', 'discourse_analyses']:
541
+ with st.expander(t[f'{analysis_type}_expander']):
542
+ for analysis in student_data[analysis_type][:5]: # Mostrar los últimos 5
543
+ st.subheader(f"{t['analysis_from']} {analysis['timestamp']}")
544
+ if analysis_type == 'morphosyntax_analyses':
545
+ if 'arc_diagrams' in analysis:
546
+ st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
547
+ elif analysis_type == 'semantic_analyses':
548
+ if 'key_concepts' in analysis:
549
+ st.write(t['key_concepts'])
550
+ st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis['key_concepts']]))
551
+ if 'graph' in analysis:
552
+ st.image(base64.b64decode(analysis['graph']))
553
+ elif analysis_type == 'discourse_analyses':
554
+ for i in [1, 2]:
555
+ if f'key_concepts{i}' in analysis:
556
+ st.write(f"{t['key_concepts']} {t['document']} {i}")
557
+ st.write(", ".join([f"{concept} ({freq:.2f})" for concept, freq in analysis[f'key_concepts{i}']]))
558
+ if 'combined_graph' in analysis:
559
+ st.image(base64.b64decode(analysis['combined_graph']))
560
+
561
+ # Mostrar el historial de chat
562
+ with st.expander(t['chat_history_expander']):
563
+ for chat in student_data['chat_history'][:5]: # Mostrar las últimas 5 conversaciones
564
+ st.subheader(f"{t['chat_from']} {chat['timestamp']}")
565
+ for message in chat['messages']:
566
+ st.write(f"{message['role'].capitalize()}: {message['content']}")
567
+ st.write("---")
568
+
569
+
570
+
571
+
572
+ def display_student_progress(username, lang_code, t):
573
+ st.subheader(t['student_activities'])
574
+ st.write(f"{t['activities_message']} {username}")
575
+
576
+ # Aquí puedes agregar más contenido estático o placeholder
577
+ st.info(t['activities_placeholder'])
578
+
579
+ # Si necesitas mostrar algún dato, puedes usar datos de ejemplo o placeholders
580
+ col1, col2, col3 = st.columns(3)
581
+ col1.metric(t['morpho_analyses'], "5") # Ejemplo de dato
582
+ col2.metric(t['semantic_analyses'], "3") # Ejemplo de dato
583
+ col3.metric(t['discourse_analyses'], "2") # Ejemplo de dato
584
+
585
+
586
+
587
+ def display_student_progress(username, lang_code, t):
588
+ st.title(f"Actividades de {username}")
589
+
590
+ # Obtener todos los datos del estudiante
591
+ student_data = get_student_data(username)
592
+
593
+ if not student_data or len(student_data.get('entries', [])) == 0:
594
+ st.warning("No se encontraron datos de análisis para este estudiante.")
595
+ st.info("Intenta realizar algunos análisis de texto primero.")
596
+ return
597
+
598
+ # Resumen de actividades
599
+ with st.expander("Resumen de Actividades", expanded=True):
600
+ total_entries = len(student_data['entries'])
601
+ st.write(f"Total de análisis realizados: {total_entries}")
602
+
603
+ # Gráfico de tipos de análisis
604
+ analysis_types = [entry['analysis_type'] for entry in student_data['entries']]
605
+ analysis_counts = pd.Series(analysis_types).value_counts()
606
+ fig, ax = plt.subplots()
607
+ analysis_counts.plot(kind='bar', ax=ax)
608
+ ax.set_title("Tipos de análisis realizados")
609
+ ax.set_xlabel("Tipo de análisis")
610
+ ax.set_ylabel("Cantidad")
611
+ st.pyplot(fig)
612
+
613
+ # Histórico de Análisis Morfosintácticos
614
+ with st.expander("Histórico de Análisis Morfosintácticos"):
615
+ morpho_analyses = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'morphosyntax']
616
+ for analysis in morpho_analyses[:5]: # Mostrar los últimos 5
617
+ st.subheader(f"Análisis del {analysis['timestamp']}")
618
+ if 'arc_diagrams' in analysis:
619
+ st.write(analysis['arc_diagrams'][0], unsafe_allow_html=True)
620
+
621
+ # Histórico de Análisis Semánticos
622
+ with st.expander("Histórico de Análisis Semánticos"):
623
+ semantic_analyses = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'semantic']
624
+ for analysis in semantic_analyses[:5]: # Mostrar los últimos 5
625
+ st.subheader(f"Análisis del {analysis['timestamp']}")
626
+ if 'key_concepts' in analysis:
627
+ concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in analysis['key_concepts']])
628
+ st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
629
+ if 'graph' in analysis:
630
+ try:
631
+ img_bytes = base64.b64decode(analysis['graph'])
632
+ st.image(img_bytes, caption="Gráfico de relaciones conceptuales")
633
+ except Exception as e:
634
+ st.error(f"No se pudo mostrar el gráfico: {str(e)}")
635
+
636
+ # Histórico de Análisis Discursivos
637
+ with st.expander("Histórico de Análisis Discursivos"):
638
+ discourse_analyses = [entry for entry in student_data['entries'] if entry['analysis_type'] == 'discourse']
639
+ for analysis in discourse_analyses[:5]: # Mostrar los últimos 5
640
+ st.subheader(f"Análisis del {analysis['timestamp']}")
641
+ for i in [1, 2]:
642
+ if f'key_concepts{i}' in analysis:
643
+ concepts_str = " | ".join([f"{concept} ({frequency:.2f})" for concept, frequency in analysis[f'key_concepts{i}']])
644
+ st.write(f"Conceptos clave del documento {i}:")
645
+ st.markdown(f"<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px;'>{concepts_str}</div>", unsafe_allow_html=True)
646
+ if 'combined_graph' in analysis:
647
+ try:
648
+ img_bytes = base64.b64decode(analysis['combined_graph'])
649
+ st.image(img_bytes)
650
+ except Exception as e:
651
+ st.error(f"No se pudo mostrar el gráfico combinado: {str(e)}")
652
+
653
+ # Histórico de Conversaciones con el ChatBot
654
+ with st.expander("Histórico de Conversaciones con el ChatBot"):
655
+ if 'chat_history' in student_data:
656
+ for i, chat in enumerate(student_data['chat_history'][:5]): # Mostrar las últimas 5 conversaciones
657
+ st.subheader(f"Conversación {i+1} - {chat['timestamp']}")
658
+ for message in chat['messages']:
659
+ st.write(f"{message['role'].capitalize()}: {message['content']}")
660
+ st.write("---")
661
+ else:
662
+ st.write("No se encontraron conversaciones con el ChatBot.")
663
+
664
+ # Opción para mostrar datos de depuración
665
+ if st.checkbox("Mostrar datos de depuración"):
666
+ st.write("Datos del estudiante (para depuración):")
667
+ st.json(student_data)
668
+
669
  '''