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