AIdeaText commited on
Commit
53e753d
·
verified ·
1 Parent(s): b71f653

Update modules/studentact/student_activities_v2.py

Browse files
modules/studentact/student_activities_v2.py CHANGED
@@ -538,7 +538,8 @@ def display_semantic_activities(username: str, t: dict):
538
 
539
  def display_discourse_activities(username: str, t: dict):
540
  """
541
- Muestra actividades de análisis del discurso centradas en las visualizaciones comparativas
 
542
  """
543
  try:
544
  logger.info(f"Recuperando análisis del discurso para {username}")
@@ -552,97 +553,163 @@ def display_discourse_activities(username: str, t: dict):
552
  logger.info(f"Procesando {len(analyses)} análisis del discurso")
553
  for analysis in analyses:
554
  try:
 
 
 
 
 
555
  # Formatear fecha
556
  timestamp = datetime.fromisoformat(analysis['timestamp'].replace('Z', '+00:00'))
557
  formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
558
 
559
- # Título del expander
560
- expander_title = f"{t.get('analysis_date', 'Fecha')}: {formatted_date}"
561
-
562
- with st.expander(expander_title, expanded=False):
563
- # Mostrar conceptos clave en dos columnas
564
  if 'key_concepts1' in analysis and 'key_concepts2' in analysis:
565
  col1, col2 = st.columns(2)
566
 
567
  with col1:
568
- st.subheader(t.get('concepts_text_1', 'Conceptos Texto 1'))
569
  if analysis['key_concepts1']:
570
  df1 = pd.DataFrame(analysis['key_concepts1'], columns=['Concepto', 'Relevancia'])
571
  st.dataframe(df1, use_container_width=True)
572
 
573
  with col2:
574
- st.subheader(t.get('concepts_text_2', 'Conceptos Texto 2'))
575
  if analysis['key_concepts2']:
576
  df2 = pd.DataFrame(analysis['key_concepts2'], columns=['Concepto', 'Relevancia'])
577
  st.dataframe(df2, use_container_width=True)
578
 
579
- # Mostrar visualizaciones semánticas
580
- st.subheader(t.get('semantic_visualization', 'Visualización Semántica'))
581
 
582
- # Mostrar gráficos en fila
583
- graph_cols = st.columns(3)
584
-
585
- # Gráfico 1 (si existe)
586
- with graph_cols[0]:
587
- if analysis.get('graph1'):
588
- try:
589
- st.caption(t.get('graph1_caption', 'Grafo Texto 1'))
590
- if isinstance(analysis['graph1'], str) and analysis['graph1'].startswith('data:image'):
591
- import base64
592
- image_bytes = base64.b64decode(analysis['graph1'].split(',')[1])
593
- st.image(image_bytes, use_column_width=True)
594
- elif isinstance(analysis['graph1'], bytes):
595
- st.image(analysis['graph1'], use_column_width=True)
596
- elif analysis['graph1'] is not None:
597
- st.pyplot(analysis['graph1'])
598
- except Exception as e:
599
- logger.error(f"Error mostrando gráfico 1: {str(e)}")
600
- st.error(t.get('error_graph1', 'Error mostrando gráfico 1'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
601
 
602
- # Gráfico 2 (si existe)
603
- with graph_cols[1]:
604
- if analysis.get('graph2'):
605
- try:
606
- st.caption(t.get('graph2_caption', 'Grafo Texto 2'))
607
- if isinstance(analysis['graph2'], str) and analysis['graph2'].startswith('data:image'):
608
- import base64
609
- image_bytes = base64.b64decode(analysis['graph2'].split(',')[1])
610
- st.image(image_bytes, use_column_width=True)
611
- elif isinstance(analysis['graph2'], bytes):
612
- st.image(analysis['graph2'], use_column_width=True)
613
- elif analysis['graph2'] is not None:
614
- st.pyplot(analysis['graph2'])
615
- except Exception as e:
616
- logger.error(f"Error mostrando gráfico 2: {str(e)}")
617
- st.error(t.get('error_graph2', 'Error mostrando gráfico 2'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
618
 
619
- # Gráfico combinado (si existe) - en la última columna
620
- with graph_cols[2]:
621
- if analysis.get('combined_graph'):
622
- try:
623
- st.caption(t.get('combined_graph_caption', 'Grafo Comparativo'))
624
- if isinstance(analysis['combined_graph'], str):
625
- try:
 
 
 
 
 
 
 
 
 
 
 
626
  import base64
627
- # Intentar diferentes formatos de base64
628
- if analysis['combined_graph'].startswith('data:image'):
629
- image_bytes = base64.b64decode(analysis['combined_graph'].split(',')[1])
630
- else:
631
- image_bytes = base64.b64decode(analysis['combined_graph'])
632
- st.image(image_bytes, use_column_width=True)
633
- except:
634
- logger.error("Error decodificando imagen combinada")
635
- elif isinstance(analysis['combined_graph'], bytes):
636
- st.image(analysis['combined_graph'], use_column_width=True)
637
- elif analysis['combined_graph'] is not None:
638
- st.pyplot(analysis['combined_graph'])
639
- except Exception as e:
640
- logger.error(f"Error mostrando gráfico combinado: {str(e)}")
641
- st.error(t.get('error_combined_graph', 'Error mostrando gráfico combinado'))
 
 
 
 
642
 
643
- # Si no hay ningún gráfico disponible
644
  if all(analysis.get(k) is None for k in ['graph1', 'graph2', 'combined_graph']):
645
- st.info(t.get('no_visualizations', 'No hay visualizaciones disponibles para este análisis'))
 
 
 
 
 
 
 
 
646
 
647
  except Exception as e:
648
  logger.error(f"Error procesando análisis individual: {str(e)}")
 
538
 
539
  def display_discourse_activities(username: str, t: dict):
540
  """
541
+ Muestra actividades de análisis del discurso (análisis comparado de textos)
542
+ con enfoque en mostrar los gráficos de manera similar al análisis semántico
543
  """
544
  try:
545
  logger.info(f"Recuperando análisis del discurso para {username}")
 
553
  logger.info(f"Procesando {len(analyses)} análisis del discurso")
554
  for analysis in analyses:
555
  try:
556
+ # Verificar campos necesarios
557
+ if 'timestamp' not in analysis:
558
+ logger.warning(f"Análisis sin timestamp: {analysis.keys()}")
559
+ continue
560
+
561
  # Formatear fecha
562
  timestamp = datetime.fromisoformat(analysis['timestamp'].replace('Z', '+00:00'))
563
  formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
564
 
565
+ # Crear expander para cada análisis
566
+ with st.expander(f"{t.get('analysis_date', 'Fecha')}: {formatted_date}", expanded=False):
567
+ # Mostrar conceptos clave primero - esto da contexto al análisis
 
 
568
  if 'key_concepts1' in analysis and 'key_concepts2' in analysis:
569
  col1, col2 = st.columns(2)
570
 
571
  with col1:
572
+ st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
573
  if analysis['key_concepts1']:
574
  df1 = pd.DataFrame(analysis['key_concepts1'], columns=['Concepto', 'Relevancia'])
575
  st.dataframe(df1, use_container_width=True)
576
 
577
  with col2:
578
+ st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
579
  if analysis['key_concepts2']:
580
  df2 = pd.DataFrame(analysis['key_concepts2'], columns=['Concepto', 'Relevancia'])
581
  st.dataframe(df2, use_container_width=True)
582
 
583
+ # Mostrar los gráficos - siguiendo el estilo de display_semantic_activities
 
584
 
585
+ # Gráfico 1
586
+ if analysis.get('graph1'):
587
+ st.markdown("### " + t.get('graph1_title', 'Red de Conceptos - Texto 1'))
588
+ try:
589
+ image_data = analysis['graph1']
590
+
591
+ # Procesar la imagen según su tipo
592
+ if isinstance(image_data, bytes):
593
+ image_bytes = image_data
594
+ elif isinstance(image_data, str):
595
+ # Intentar decodificar base64
596
+ try:
597
+ if image_data.startswith('data:image'):
598
+ # Formato data URI
599
+ import base64
600
+ image_bytes = base64.b64decode(image_data.split(',')[1])
601
+ else:
602
+ # Base64 directo
603
+ import base64
604
+ image_bytes = base64.b64decode(image_data)
605
+ except:
606
+ logger.error("Error decodificando imagen 1")
607
+ image_bytes = None
608
+ else:
609
+ # Si es otro tipo (como un objeto matplotlib figure)
610
+ st.pyplot(image_data)
611
+ image_bytes = None
612
+
613
+ # Mostrar imagen si tenemos bytes
614
+ if image_bytes:
615
+ st.image(
616
+ image_bytes,
617
+ caption=t.get('graph1_caption', 'Red Semántica del Texto 1'),
618
+ use_column_width=True
619
+ )
620
+ except Exception as e:
621
+ logger.error(f"Error mostrando gráfico 1: {str(e)}")
622
+ st.error(t.get('error_graph1', 'Error al cargar el gráfico del Texto 1'))
623
 
624
+ # Gráfico 2
625
+ if analysis.get('graph2'):
626
+ st.markdown("### " + t.get('graph2_title', 'Red de Conceptos - Texto 2'))
627
+ try:
628
+ image_data = analysis['graph2']
629
+
630
+ # Procesar la imagen según su tipo
631
+ if isinstance(image_data, bytes):
632
+ image_bytes = image_data
633
+ elif isinstance(image_data, str):
634
+ # Intentar decodificar base64
635
+ try:
636
+ if image_data.startswith('data:image'):
637
+ # Formato data URI
638
+ import base64
639
+ image_bytes = base64.b64decode(image_data.split(',')[1])
640
+ else:
641
+ # Base64 directo
642
+ import base64
643
+ image_bytes = base64.b64decode(image_data)
644
+ except:
645
+ logger.error("Error decodificando imagen 2")
646
+ image_bytes = None
647
+ else:
648
+ # Si es otro tipo (como un objeto matplotlib figure)
649
+ st.pyplot(image_data)
650
+ image_bytes = None
651
+
652
+ # Mostrar imagen si tenemos bytes
653
+ if image_bytes:
654
+ st.image(
655
+ image_bytes,
656
+ caption=t.get('graph2_caption', 'Red Semántica del Texto 2'),
657
+ use_column_width=True
658
+ )
659
+ except Exception as e:
660
+ logger.error(f"Error mostrando gráfico 2: {str(e)}")
661
+ st.error(t.get('error_graph2', 'Error al cargar el gráfico del Texto 2'))
662
 
663
+ # Gráfico combinado - el más importante
664
+ if analysis.get('combined_graph'):
665
+ st.markdown("### " + t.get('combined_graph_title', 'Análisis Comparativo de Textos'))
666
+ try:
667
+ image_data = analysis['combined_graph']
668
+
669
+ # Procesar la imagen según su tipo
670
+ if isinstance(image_data, bytes):
671
+ image_bytes = image_data
672
+ elif isinstance(image_data, str):
673
+ # Intentar decodificar base64
674
+ try:
675
+ if image_data.startswith('data:image'):
676
+ # Formato data URI
677
+ import base64
678
+ image_bytes = base64.b64decode(image_data.split(',')[1])
679
+ else:
680
+ # Base64 directo
681
  import base64
682
+ image_bytes = base64.b64decode(image_data)
683
+ except:
684
+ logger.error("Error decodificando imagen combinada")
685
+ image_bytes = None
686
+ else:
687
+ # Si es otro tipo (como un objeto matplotlib figure)
688
+ st.pyplot(image_data)
689
+ image_bytes = None
690
+
691
+ # Mostrar imagen si tenemos bytes
692
+ if image_bytes:
693
+ st.image(
694
+ image_bytes,
695
+ caption=t.get('combined_graph_caption', 'Visualización Comparativa de Redes Semánticas'),
696
+ use_column_width=True
697
+ )
698
+ except Exception as e:
699
+ logger.error(f"Error mostrando gráfico combinado: {str(e)}")
700
+ st.error(t.get('error_combined_graph', 'Error al cargar el gráfico comparativo'))
701
 
702
+ # Si no hay gráficos disponibles
703
  if all(analysis.get(k) is None for k in ['graph1', 'graph2', 'combined_graph']):
704
+ st.info(t.get('no_graphs', 'No hay visualizaciones disponibles para este análisis'))
705
+
706
+ # Si tenemos al menos los conceptos clave, mostrar un mensaje más descriptivo
707
+ if 'key_concepts1' in analysis and 'key_concepts2' in analysis:
708
+ st.markdown(t.get('concepts_only_message',
709
+ """
710
+ **Solo se muestran los conceptos clave extraídos de los textos.**
711
+ Las visualizaciones gráficas no están disponibles para este análisis.
712
+ """))
713
 
714
  except Exception as e:
715
  logger.error(f"Error procesando análisis individual: {str(e)}")