Update modules/studentact/student_activities.py
Browse files- modules/studentact/student_activities.py +108 -104
modules/studentact/student_activities.py
CHANGED
@@ -1,105 +1,109 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
import pandas as pd
|
3 |
-
import matplotlib.pyplot as plt
|
4 |
-
import seaborn as sns
|
5 |
-
import base64
|
6 |
-
from io import BytesIO
|
7 |
-
from reportlab.pdfgen import canvas
|
8 |
-
from reportlab.lib.pagesizes import letter
|
9 |
-
from docx import Document
|
10 |
-
from odf.opendocument import OpenDocumentText
|
11 |
-
from odf.text import P
|
12 |
-
from datetime import datetime, timedelta
|
13 |
-
import pytz
|
14 |
-
import logging
|
15 |
-
|
16 |
-
# Configuración de logging
|
17 |
-
logging.basicConfig(level=logging.DEBUG)
|
18 |
-
logger = logging.getLogger(__name__)
|
19 |
-
|
20 |
-
# Importaciones locales
|
21 |
-
try:
|
22 |
-
from ..database.morphosintax_mongo_db import get_student_morphosyntax_data
|
23 |
-
from ..database.
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
ax.
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
105 |
logger.debug("Finalizando display_student_progress")
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import seaborn as sns
|
5 |
+
import base64
|
6 |
+
from io import BytesIO
|
7 |
+
from reportlab.pdfgen import canvas
|
8 |
+
from reportlab.lib.pagesizes import letter
|
9 |
+
from docx import Document
|
10 |
+
from odf.opendocument import OpenDocumentText
|
11 |
+
from odf.text import P
|
12 |
+
from datetime import datetime, timedelta
|
13 |
+
import pytz
|
14 |
+
import logging
|
15 |
+
|
16 |
+
# Configuración de logging
|
17 |
+
logging.basicConfig(level=logging.DEBUG)
|
18 |
+
logger = logging.getLogger(__name__)
|
19 |
+
|
20 |
+
# Importaciones locales
|
21 |
+
try:
|
22 |
+
from ..database.morphosintax_mongo_db import get_student_morphosyntax_data
|
23 |
+
from ..database.semantic_mongo_db import get_student_semantic_data
|
24 |
+
from ..database.discourse_mongo_db import get_student_discourse_data
|
25 |
+
|
26 |
+
from ..database.chat_mono_db import get_chat_history
|
27 |
+
|
28 |
+
logger.info("Importaciones locales exitosas")
|
29 |
+
except ImportError as e:
|
30 |
+
logger.error(f"Error en las importaciones locales: {e}")
|
31 |
+
|
32 |
+
def display_student_progress(username, lang_code, t):
|
33 |
+
logger.debug(f"Iniciando display_student_progress para {username}")
|
34 |
+
|
35 |
+
st.title(f"{t.get('progress_of', 'Progreso de')} {username}")
|
36 |
+
|
37 |
+
# Obtener los datos del estudiante
|
38 |
+
student_data = get_student_morphosyntax_data(username)
|
39 |
+
|
40 |
+
if not student_data or len(student_data.get('entries', [])) == 0:
|
41 |
+
logger.warning(f"No se encontraron datos para el estudiante {username}")
|
42 |
+
st.warning(t.get("no_data_warning", "No se encontraron datos para este estudiante."))
|
43 |
+
st.info(t.get("try_analysis", "Intenta realizar algunos análisis de texto primero."))
|
44 |
+
return
|
45 |
+
|
46 |
+
logger.debug(f"Datos del estudiante obtenidos: {len(student_data['entries'])} entradas")
|
47 |
+
|
48 |
+
# Resumen de actividades
|
49 |
+
with st.expander(t.get("activities_summary", "Resumen de Actividades"), expanded=True):
|
50 |
+
total_entries = len(student_data['entries'])
|
51 |
+
st.write(f"{t.get('total_analyses', 'Total de análisis realizados')}: {total_entries}")
|
52 |
+
|
53 |
+
# Gráfico de tipos de análisis
|
54 |
+
try:
|
55 |
+
analysis_types = [entry.get('analysis_type', 'unknown') for entry in student_data['entries']]
|
56 |
+
analysis_counts = pd.Series(analysis_types).value_counts()
|
57 |
+
fig, ax = plt.subplots()
|
58 |
+
sns.barplot(x=analysis_counts.index, y=analysis_counts.values, ax=ax)
|
59 |
+
ax.set_title(t.get("analysis_types_chart", "Tipos de análisis realizados"))
|
60 |
+
ax.set_xlabel(t.get("analysis_type", "Tipo de análisis"))
|
61 |
+
ax.set_ylabel(t.get("count", "Cantidad"))
|
62 |
+
st.pyplot(fig)
|
63 |
+
except Exception as e:
|
64 |
+
logger.error(f"Error al crear el gráfico: {e}")
|
65 |
+
st.error("No se pudo crear el gráfico de tipos de análisis.")
|
66 |
+
|
67 |
+
# Función para generar el contenido del archivo de actividades de las últimas 48 horas
|
68 |
+
def generate_activity_content_48h():
|
69 |
+
content = f"Actividades de {username} en las últimas 48 horas\n\n"
|
70 |
+
|
71 |
+
two_days_ago = datetime.now(pytz.utc) - timedelta(days=2)
|
72 |
+
|
73 |
+
try:
|
74 |
+
morphosyntax_analyses = get_student_morphosyntax_data(username)
|
75 |
+
recent_morphosyntax = [a for a in morphosyntax_analyses if datetime.fromisoformat(a['timestamp']) > two_days_ago]
|
76 |
+
|
77 |
+
content += f"Análisis morfosintácticos: {len(recent_morphosyntax)}\n"
|
78 |
+
for analysis in recent_morphosyntax:
|
79 |
+
content += f"- Análisis del {analysis['timestamp']}: {analysis['text'][:50]}...\n"
|
80 |
+
|
81 |
+
chat_history = get_chat_history(username, None)
|
82 |
+
recent_chats = [c for c in chat_history if datetime.fromisoformat(c['timestamp']) > two_days_ago]
|
83 |
+
|
84 |
+
content += f"\nConversaciones de chat: {len(recent_chats)}\n"
|
85 |
+
for chat in recent_chats:
|
86 |
+
content += f"- Chat del {chat['timestamp']}: {len(chat['messages'])} mensajes\n"
|
87 |
+
except Exception as e:
|
88 |
+
logger.error(f"Error al generar el contenido de actividades: {e}")
|
89 |
+
content += "Error al recuperar los datos de actividades.\n"
|
90 |
+
|
91 |
+
return content
|
92 |
+
|
93 |
+
# Botones para descargar el histórico de actividades de las últimas 48 horas
|
94 |
+
st.subheader(t.get("download_history_48h", "Descargar Histórico de Actividades (Últimas 48 horas)"))
|
95 |
+
if st.button("Generar reporte de 48 horas"):
|
96 |
+
try:
|
97 |
+
report_content = generate_activity_content_48h()
|
98 |
+
st.text_area("Reporte de 48 horas", report_content, height=300)
|
99 |
+
st.download_button(
|
100 |
+
label="Descargar TXT (48h)",
|
101 |
+
data=report_content,
|
102 |
+
file_name="actividades_48h.txt",
|
103 |
+
mime="text/plain"
|
104 |
+
)
|
105 |
+
except Exception as e:
|
106 |
+
logger.error(f"Error al generar el reporte: {e}")
|
107 |
+
st.error("No se pudo generar el reporte. Por favor, verifica los logs para más detalles.")
|
108 |
+
|
109 |
logger.debug("Finalizando display_student_progress")
|