AIdeaText commited on
Commit
c7d5c40
·
verified ·
1 Parent(s): cf1750c

Update modules/studentact/student_activities_v2.py

Browse files
modules/studentact/student_activities_v2.py CHANGED
@@ -515,7 +515,7 @@ def display_semantic_activities(username: str, t: dict):
515
  st.image(
516
  image_bytes,
517
  caption=t.get('concept_network', 'Red de Conceptos'),
518
- use_container_width=True
519
  )
520
  logger.debug("Gráfico mostrado exitosamente")
521
 
@@ -537,9 +537,7 @@ def display_semantic_activities(username: str, t: dict):
537
  ###################################################################################################
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}")
545
  analyses = get_student_discourse_analysis(username)
@@ -552,97 +550,73 @@ 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)}")
@@ -652,6 +626,59 @@ def display_discourse_activities(username: str, t: dict):
652
  logger.error(f"Error mostrando análisis del discurso: {str(e)}")
653
  st.error(t.get('error_discourse', 'Error al mostrar análisis comparado de textos'))
654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655
 
656
  #################################################################################
657
  def display_chat_activities(username: str, t: dict):
@@ -704,18 +731,3 @@ def display_chat_activities(username: str, t: dict):
704
  st.error(t.get('error_chat', 'Error al mostrar historial del chat'))
705
 
706
  #################################################################################
707
- def display_discourse_comparison(analysis: dict, t: dict):
708
- """Muestra la comparación de análisis del discurso"""
709
- # Cambiado para usar "textos comparados" en la UI
710
- st.subheader(t.get('comparison_results', 'Resultados de la comparación'))
711
-
712
- col1, col2 = st.columns(2)
713
- with col1:
714
- st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
715
- df1 = pd.DataFrame(analysis['key_concepts1'])
716
- st.dataframe(df1)
717
-
718
- with col2:
719
- st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
720
- df2 = pd.DataFrame(analysis['key_concepts2'])
721
- st.dataframe(df2)
 
515
  st.image(
516
  image_bytes,
517
  caption=t.get('concept_network', 'Red de Conceptos'),
518
+ use_column_width=True
519
  )
520
  logger.debug("Gráfico mostrado exitosamente")
521
 
 
537
  ###################################################################################################
538
 
539
  def display_discourse_activities(username: str, t: dict):
540
+ """Muestra actividades de análisis del discurso"""
 
 
541
  try:
542
  logger.info(f"Recuperando análisis del discurso para {username}")
543
  analyses = get_student_discourse_analysis(username)
 
550
  logger.info(f"Procesando {len(analyses)} análisis del discurso")
551
  for analysis in analyses:
552
  try:
553
+ # Verificar campos mínimos necesarios
554
+ if 'timestamp' not in analysis:
555
+ logger.warning(f"Análisis sin timestamp: {analysis.keys()}")
556
+ continue
557
+
558
  # Formatear fecha
559
  timestamp = datetime.fromisoformat(analysis['timestamp'].replace('Z', '+00:00'))
560
  formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
561
 
562
+ with st.expander(f"{t.get('analysis_date', 'Fecha')}: {formatted_date}", expanded=False):
563
+ # Mostrar conceptos clave en fila
 
 
 
564
  if 'key_concepts1' in analysis and 'key_concepts2' in analysis:
565
+ st.markdown("### Conceptos clave")
566
 
567
+ # Documento 1
568
+ st.markdown("**Documento 1**")
569
+ if analysis['key_concepts1']:
570
+ # Extraer solo los conceptos sin la frecuencia
571
+ concepts1 = [concept for concept, _ in analysis['key_concepts1']]
572
+ # Mostrar en formato de fila
573
+ st.markdown(", ".join([f"**{concept}**" for concept in concepts1]))
574
 
575
+ # Documento 2
576
+ st.markdown("**Documento 2**")
577
+ if analysis['key_concepts2']:
578
+ # Extraer solo los conceptos sin la frecuencia
579
+ concepts2 = [concept for concept, _ in analysis['key_concepts2']]
580
+ # Mostrar en formato de fila
581
+ st.markdown(", ".join([f"**{concept}**" for concept in concepts2]))
582
 
583
+ # Mostrar gráficos
584
+ st.markdown("### Visualización comparativa")
585
 
586
+ # Verificar y mostrar gráficos si existen
587
+ graph_col1, graph_col2 = st.columns(2)
588
+ has_graphs = False
589
 
590
+ with graph_col1:
591
+ if 'graph1' in analysis and analysis['graph1']:
 
592
  try:
593
+ # Verificar que sea bytes
594
+ if isinstance(analysis['graph1'], bytes):
595
+ st.image(analysis['graph1'],
596
+ caption="Documento 1",
597
+ use_container_width=True) # Usar use_container_width en lugar de use_column_width
598
+ has_graphs = True
599
+ else:
600
+ logger.warning(f"graph1 no es bytes: {type(analysis['graph1'])}")
601
+ except Exception as img_error:
602
+ logger.error(f"Error mostrando graph1: {str(img_error)}")
 
 
603
 
604
+ with graph_col2:
605
+ if 'graph2' in analysis and analysis['graph2']:
 
606
  try:
607
+ # Verificar que sea bytes
608
+ if isinstance(analysis['graph2'], bytes):
609
+ st.image(analysis['graph2'],
610
+ caption="Documento 2",
611
+ use_container_width=True) # Usar use_container_width en lugar de use_column_width
612
+ has_graphs = True
613
+ else:
614
+ logger.warning(f"graph2 no es bytes: {type(analysis['graph2'])}")
615
+ except Exception as img_error:
616
+ logger.error(f"Error mostrando graph2: {str(img_error)}")
 
 
617
 
618
+ if not has_graphs:
619
+ st.info(t.get('no_visualization', 'No hay visualización comparativa disponible'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620
 
621
  except Exception as e:
622
  logger.error(f"Error procesando análisis individual: {str(e)}")
 
626
  logger.error(f"Error mostrando análisis del discurso: {str(e)}")
627
  st.error(t.get('error_discourse', 'Error al mostrar análisis comparado de textos'))
628
 
629
+ #################################################################################
630
+
631
+ def display_discourse_comparison(analysis: dict, t: dict):
632
+ """
633
+ Muestra la comparación de conceptos clave en análisis del discurso.
634
+ Formato horizontal simplificado.
635
+ """
636
+ st.subheader(t.get('comparison_results', 'Resultados de la comparación'))
637
+
638
+ # Verificar si tenemos los conceptos necesarios
639
+ if not ('key_concepts1' in analysis and analysis['key_concepts1']):
640
+ st.info(t.get('no_concepts', 'No hay conceptos disponibles para comparar'))
641
+ return
642
+
643
+ # Conceptos del Texto 1 - Formato horizontal
644
+ st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}:**")
645
+ try:
646
+ # Comprobar formato y mostrar horizontalmente
647
+ if isinstance(analysis['key_concepts1'], list) and len(analysis['key_concepts1']) > 0:
648
+ if isinstance(analysis['key_concepts1'][0], list) and len(analysis['key_concepts1'][0]) == 2:
649
+ # Formatear como "concepto (valor), concepto2 (valor2), ..."
650
+ concepts_text = ", ".join([f"{c[0]} ({c[1]})" for c in analysis['key_concepts1'][:10]])
651
+ st.markdown(f"*{concepts_text}*")
652
+ else:
653
+ # Si no tiene el formato esperado, mostrar como lista simple
654
+ st.markdown(", ".join(str(c) for c in analysis['key_concepts1'][:10]))
655
+ else:
656
+ st.write(str(analysis['key_concepts1']))
657
+ except Exception as e:
658
+ logger.error(f"Error mostrando key_concepts1: {str(e)}")
659
+ st.error(t.get('error_concepts1', 'Error mostrando conceptos del Texto 1'))
660
+
661
+ # Conceptos del Texto 2 - Formato horizontal
662
+ st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}:**")
663
+ if 'key_concepts2' in analysis and analysis['key_concepts2']:
664
+ try:
665
+ # Comprobar formato y mostrar horizontalmente
666
+ if isinstance(analysis['key_concepts2'], list) and len(analysis['key_concepts2']) > 0:
667
+ if isinstance(analysis['key_concepts2'][0], list) and len(analysis['key_concepts2'][0]) == 2:
668
+ # Formatear como "concepto (valor), concepto2 (valor2), ..."
669
+ concepts_text = ", ".join([f"{c[0]} ({c[1]})" for c in analysis['key_concepts2'][:10]])
670
+ st.markdown(f"*{concepts_text}*")
671
+ else:
672
+ # Si no tiene el formato esperado, mostrar como lista simple
673
+ st.markdown(", ".join(str(c) for c in analysis['key_concepts2'][:10]))
674
+ else:
675
+ st.write(str(analysis['key_concepts2']))
676
+ except Exception as e:
677
+ logger.error(f"Error mostrando key_concepts2: {str(e)}")
678
+ st.error(t.get('error_concepts2', 'Error mostrando conceptos del Texto 2'))
679
+ else:
680
+ st.info(t.get('no_concepts2', 'No hay conceptos disponibles para el Texto 2'))
681
+
682
 
683
  #################################################################################
684
  def display_chat_activities(username: str, t: dict):
 
731
  st.error(t.get('error_chat', 'Error al mostrar historial del chat'))
732
 
733
  #################################################################################