Update modules/studentact/student_activities_v2.py
Browse files
modules/studentact/student_activities_v2.py
CHANGED
@@ -536,185 +536,49 @@ def display_semantic_activities(username: str, t: dict):
|
|
536 |
|
537 |
###################################################################################################
|
538 |
def display_discourse_activities(username: str, t: dict):
|
539 |
-
"""
|
540 |
-
Muestra actividades de análisis del discurso (mostrado como 'Análisis comparado de textos' en la UI)
|
541 |
-
Versión simplificada que muestra cualquier dato disponible
|
542 |
-
"""
|
543 |
try:
|
544 |
logger.info(f"Recuperando análisis del discurso para {username}")
|
545 |
-
|
546 |
-
# Importación inline para evitar circularidad
|
547 |
-
from ..database.mongo_db import get_collection
|
548 |
-
|
549 |
-
# Obtener la colección directamente para evitar cualquier filtrado
|
550 |
-
collection = get_collection('student_discourse_analysis')
|
551 |
-
if not collection:
|
552 |
-
st.info(t.get('no_discourse_analyses', 'No hay análisis comparados de textos registrados'))
|
553 |
-
return
|
554 |
-
|
555 |
-
# Consulta básica - solo por username para capturar todos los registros posibles
|
556 |
-
query = {"username": username}
|
557 |
-
|
558 |
-
# Ejecutar consulta
|
559 |
-
try:
|
560 |
-
analyses = list(collection.find(query).sort("timestamp", -1))
|
561 |
-
logger.info(f"Recuperados {len(analyses)} análisis para {username}")
|
562 |
-
except Exception as e:
|
563 |
-
logger.error(f"Error recuperando análisis: {str(e)}")
|
564 |
-
analyses = []
|
565 |
|
566 |
if not analyses:
|
567 |
-
|
|
|
568 |
return
|
569 |
|
570 |
-
|
571 |
for analysis in analyses:
|
572 |
try:
|
|
|
|
|
|
|
|
|
|
|
573 |
# Formatear fecha
|
574 |
-
|
575 |
-
|
576 |
-
formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
|
577 |
-
except:
|
578 |
-
formatted_date = str(analysis.get('timestamp', 'Fecha desconocida'))
|
579 |
-
|
580 |
-
# Crear título del expander
|
581 |
-
expander_title = f"{t.get('analysis_date', 'Fecha')}: {formatted_date}"
|
582 |
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
"
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
)
|
595 |
-
|
596 |
-
# 2. Mostrar conceptos clave si existen
|
597 |
-
if 'key_concepts1' in analysis and analysis['key_concepts1']:
|
598 |
-
st.subheader(t.get('key_concepts', 'Conceptos clave'))
|
599 |
-
|
600 |
-
col1, col2 = st.columns(2)
|
601 |
-
|
602 |
-
with col1:
|
603 |
-
st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
|
604 |
-
try:
|
605 |
-
# Mostrar como dataframe o texto según formato
|
606 |
-
if isinstance(analysis['key_concepts1'], list):
|
607 |
-
if len(analysis['key_concepts1']) > 0:
|
608 |
-
if isinstance(analysis['key_concepts1'][0], list):
|
609 |
-
df = pd.DataFrame(analysis['key_concepts1'], columns=['Concepto', 'Relevancia'])
|
610 |
-
st.dataframe(df)
|
611 |
-
else:
|
612 |
-
st.write(", ".join(str(c) for c in analysis['key_concepts1']))
|
613 |
-
else:
|
614 |
-
st.write(str(analysis['key_concepts1']))
|
615 |
-
except:
|
616 |
-
st.write(str(analysis['key_concepts1']))
|
617 |
-
|
618 |
-
with col2:
|
619 |
-
if 'key_concepts2' in analysis and analysis['key_concepts2']:
|
620 |
-
st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
|
621 |
-
try:
|
622 |
-
# Mostrar como dataframe o texto según formato
|
623 |
-
if isinstance(analysis['key_concepts2'], list):
|
624 |
-
if len(analysis['key_concepts2']) > 0:
|
625 |
-
if isinstance(analysis['key_concepts2'][0], list):
|
626 |
-
df = pd.DataFrame(analysis['key_concepts2'], columns=['Concepto', 'Relevancia'])
|
627 |
-
st.dataframe(df)
|
628 |
-
else:
|
629 |
-
st.write(", ".join(str(c) for c in analysis['key_concepts2']))
|
630 |
-
else:
|
631 |
-
st.write(str(analysis['key_concepts2']))
|
632 |
-
except:
|
633 |
-
st.write(str(analysis['key_concepts2']))
|
634 |
-
|
635 |
-
# 3. Mostrar cualquier gráfico disponible
|
636 |
-
st.subheader(t.get('visualizations', 'Visualizaciones'))
|
637 |
-
|
638 |
-
# Revisar todos los campos que podrían contener gráficos
|
639 |
-
graph_fields = ['graph1', 'graph2', 'combined_graph']
|
640 |
-
found_graphs = False
|
641 |
-
|
642 |
-
for field in graph_fields:
|
643 |
-
if field in analysis and analysis[field]:
|
644 |
-
found_graphs = True
|
645 |
-
|
646 |
-
# Título según el tipo de gráfico
|
647 |
-
if field == 'graph1':
|
648 |
-
title = t.get('graph1_title', 'Gráfico Texto 1')
|
649 |
-
elif field == 'graph2':
|
650 |
-
title = t.get('graph2_title', 'Gráfico Texto 2')
|
651 |
-
else:
|
652 |
-
title = t.get('combined_graph_title', 'Gráfico Combinado')
|
653 |
-
|
654 |
-
st.markdown(f"**{title}**")
|
655 |
-
|
656 |
-
# Mostrar el gráfico según su tipo
|
657 |
-
graph_data = analysis[field]
|
658 |
-
|
659 |
-
try:
|
660 |
-
# Si es bytes, mostrar directamente
|
661 |
-
if isinstance(graph_data, bytes):
|
662 |
-
st.image(graph_data, use_column_width=True)
|
663 |
-
|
664 |
-
# Si es string, intentar decodificar como base64
|
665 |
-
elif isinstance(graph_data, str):
|
666 |
-
try:
|
667 |
-
import base64
|
668 |
-
# Intentar diferentes formatos de base64
|
669 |
-
if graph_data.startswith('data:image'):
|
670 |
-
image_bytes = base64.b64decode(graph_data.split(',')[1])
|
671 |
-
else:
|
672 |
-
image_bytes = base64.b64decode(graph_data)
|
673 |
-
|
674 |
-
st.image(image_bytes, use_column_width=True)
|
675 |
-
except:
|
676 |
-
# Si falla la decodificación, mostrar como texto si no es muy largo
|
677 |
-
if len(graph_data) < 100:
|
678 |
-
st.text(f"Datos no decodificables: {graph_data}")
|
679 |
-
else:
|
680 |
-
st.text(f"Datos no decodificables (muy largos)")
|
681 |
-
|
682 |
-
# Otros tipos (matplotlib, etc.)
|
683 |
-
else:
|
684 |
-
st.write(f"Gráfico presente pero en formato no mostrable")
|
685 |
-
except Exception as e:
|
686 |
-
st.error(f"Error mostrando gráfico: {str(e)}")
|
687 |
-
|
688 |
-
# Si no hay gráficos, mostrar mensaje
|
689 |
-
if not found_graphs:
|
690 |
-
st.info(t.get('no_graphs', 'No hay gráficos disponibles para este análisis'))
|
691 |
-
|
692 |
-
# Mostrar botón para generar nuevos gráficos (para futura implementación)
|
693 |
-
# st.button("Regenerar gráficos", key=f"btn_regenerate_{str(analysis.get('_id', 'unknown'))}")
|
694 |
-
|
695 |
-
# 4. Mostrar campos adicionales que puedan ser útiles
|
696 |
-
with st.expander("Ver datos adicionales", expanded=False):
|
697 |
-
# Filtrar campos para mostrar solo los relevantes
|
698 |
-
filtered_data = {k: v for k, v in analysis.items()
|
699 |
-
if k not in ['_id', 'username', 'timestamp', 'text1', 'text2',
|
700 |
-
'graph1', 'graph2', 'combined_graph',
|
701 |
-
'key_concepts1', 'key_concepts2']
|
702 |
-
and not isinstance(v, bytes)
|
703 |
-
and not (isinstance(v, str) and len(v) > 200)}
|
704 |
-
|
705 |
-
if filtered_data:
|
706 |
-
st.json(filtered_data)
|
707 |
-
else:
|
708 |
-
st.text("No hay datos adicionales disponibles")
|
709 |
|
710 |
except Exception as e:
|
711 |
logger.error(f"Error procesando análisis individual: {str(e)}")
|
712 |
-
st.error(f"Error procesando análisis: {str(e)}")
|
713 |
continue
|
714 |
|
715 |
except Exception as e:
|
716 |
-
logger.error(f"Error
|
717 |
-
st.error(t.get('error_discourse', 'Error al mostrar análisis
|
|
|
718 |
|
719 |
#################################################################################
|
720 |
def display_chat_activities(username: str, t: dict):
|
@@ -767,3 +631,18 @@ def display_chat_activities(username: str, t: dict):
|
|
767 |
st.error(t.get('error_chat', 'Error al mostrar historial del chat'))
|
768 |
|
769 |
#################################################################################
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
536 |
|
537 |
###################################################################################################
|
538 |
def display_discourse_activities(username: str, t: dict):
|
539 |
+
"""Muestra actividades de análisis del discurso"""
|
|
|
|
|
|
|
540 |
try:
|
541 |
logger.info(f"Recuperando análisis del discurso para {username}")
|
542 |
+
analyses = get_student_discourse_analysis(username)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
543 |
|
544 |
if not analyses:
|
545 |
+
logger.info("No se encontraron análisis del discurso")
|
546 |
+
st.info(t.get('no_discourse_analyses', 'No hay análisis del discurso registrados'))
|
547 |
return
|
548 |
|
549 |
+
logger.info(f"Procesando {len(analyses)} análisis del discurso")
|
550 |
for analysis in analyses:
|
551 |
try:
|
552 |
+
# Verificar campos mínimos necesarios
|
553 |
+
if not all(key in analysis for key in ['timestamp', 'combined_graph']):
|
554 |
+
logger.warning(f"Análisis incompleto: {analysis.keys()}")
|
555 |
+
continue
|
556 |
+
|
557 |
# Formatear fecha
|
558 |
+
timestamp = datetime.fromisoformat(analysis['timestamp'].replace('Z', '+00:00'))
|
559 |
+
formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
|
|
|
|
|
|
|
|
|
|
|
|
|
560 |
|
561 |
+
with st.expander(f"{t.get('analysis_date', 'Fecha')}: {formatted_date}", expanded=False):
|
562 |
+
if analysis['combined_graph']:
|
563 |
+
logger.debug("Decodificando gráfico combinado")
|
564 |
+
try:
|
565 |
+
image_bytes = base64.b64decode(analysis['combined_graph'])
|
566 |
+
st.image(image_bytes, use_column_width=True)
|
567 |
+
logger.debug("Gráfico mostrado exitosamente")
|
568 |
+
except Exception as img_error:
|
569 |
+
logger.error(f"Error decodificando imagen: {str(img_error)}")
|
570 |
+
st.error(t.get('error_loading_graph', 'Error al cargar el gráfico'))
|
571 |
+
else:
|
572 |
+
st.info(t.get('no_visualization', 'No hay visualización comparativa disponible'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
573 |
|
574 |
except Exception as e:
|
575 |
logger.error(f"Error procesando análisis individual: {str(e)}")
|
|
|
576 |
continue
|
577 |
|
578 |
except Exception as e:
|
579 |
+
logger.error(f"Error mostrando análisis del discurso: {str(e)}")
|
580 |
+
st.error(t.get('error_discourse', 'Error al mostrar análisis del discurso'))
|
581 |
+
|
582 |
|
583 |
#################################################################################
|
584 |
def display_chat_activities(username: str, t: dict):
|
|
|
631 |
st.error(t.get('error_chat', 'Error al mostrar historial del chat'))
|
632 |
|
633 |
#################################################################################
|
634 |
+
|
635 |
+
def display_discourse_comparison(analysis: dict, t: dict):
|
636 |
+
"""Muestra la comparación de análisis del discurso"""
|
637 |
+
st.subheader(t.get('comparison_results', 'Resultados de la comparación'))
|
638 |
+
|
639 |
+
col1, col2 = st.columns(2)
|
640 |
+
with col1:
|
641 |
+
st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
|
642 |
+
df1 = pd.DataFrame(analysis['key_concepts1'])
|
643 |
+
st.dataframe(df1)
|
644 |
+
|
645 |
+
with col2:
|
646 |
+
st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
|
647 |
+
df2 = pd.DataFrame(analysis['key_concepts2'])
|
648 |
+
st.dataframe(df2)
|