AIdeaText commited on
Commit
4f94a7c
·
verified ·
1 Parent(s): 8dabcf3

Update modules/studentact/student_activities_v2.py

Browse files
modules/studentact/student_activities_v2.py CHANGED
@@ -535,10 +535,16 @@ def display_semantic_activities(username: str, t: dict):
535
 
536
 
537
  ###################################################################################################
 
538
  def display_discourse_activities(username: str, t: dict):
539
- """Muestra actividades de análisis del discurso (mostrado como 'Análisis comparado de textos' en la UI)"""
 
 
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:
@@ -551,26 +557,220 @@ def display_discourse_activities(username: str, t: dict):
551
  for analysis in analyses:
552
  try:
553
  # Verificar campos mínimos necesarios
554
- if not all(key in analysis for key in ['timestamp', 'combined_graph']):
555
- logger.warning(f"Análisis incompleto: {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
- if analysis['combined_graph']:
564
- logger.debug("Decodificando gráfico combinado")
565
- try:
566
- image_bytes = base64.b64decode(analysis['combined_graph'])
567
- st.image(image_bytes, use_column_width=True)
568
- logger.debug("Gráfico mostrado exitosamente")
569
- except Exception as img_error:
570
- logger.error(f"Error decodificando imagen: {str(img_error)}")
571
- st.error(t.get('error_loading_graph', 'Error al cargar el gráfico'))
572
- else:
573
- st.info(t.get('no_visualization', 'No hay visualización comparativa disponible'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
 
575
  except Exception as e:
576
  logger.error(f"Error procesando análisis individual: {str(e)}")
 
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
+ """
543
  try:
544
  logger.info(f"Recuperando análisis del discurso para {username}")
545
+
546
+ # Obtener análisis del discurso con el tipo correcto
547
+ from ..database.discourse_mongo_db import get_student_discourse_analysis
548
  analyses = get_student_discourse_analysis(username)
549
 
550
  if not analyses:
 
557
  for analysis in analyses:
558
  try:
559
  # Verificar campos mínimos necesarios
560
+ if 'timestamp' not in analysis:
561
+ logger.warning(f"Análisis sin timestamp: {analysis.keys()}")
562
  continue
563
 
564
  # Formatear fecha
565
+ try:
566
+ timestamp = datetime.fromisoformat(analysis['timestamp'].replace('Z', '+00:00'))
567
+ formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
568
+ except Exception as e:
569
+ logger.error(f"Error al formatear timestamp: {str(e)}")
570
+ formatted_date = str(analysis.get('timestamp', 'Fecha desconocida'))
571
 
572
+ # Crear el título del expander
573
+ expander_title = f"{t.get('analysis_date', 'Fecha')}: {formatted_date}"
574
+
575
+ with st.expander(expander_title, expanded=False):
576
+ # Crear pestañas para los textos y la comparación
577
+ tabs = st.tabs([
578
+ t.get('text1_tab', 'Texto 1 (Patrón)'),
579
+ t.get('text2_tab', 'Texto 2 (Comparación)'),
580
+ t.get('comparison_tab', 'Análisis Comparativo')
581
+ ])
582
+
583
+ # Tab para Texto 1
584
+ with tabs[0]:
585
+ if 'text1' in analysis and analysis['text1']:
586
+ st.text_area(
587
+ "Texto 1",
588
+ value=analysis['text1'],
589
+ height=150,
590
+ disabled=True,
591
+ label_visibility="collapsed",
592
+ key=f"text1_{str(analysis['_id'])}"
593
+ )
594
+
595
+ # Mostrar conceptos clave del texto 1
596
+ if 'key_concepts1' in analysis and analysis['key_concepts1']:
597
+ st.subheader(t.get('key_concepts1', 'Conceptos clave (Texto 1)'))
598
+
599
+ # Crear una tabla/dataframe de conceptos
600
+ concept_data = analysis['key_concepts1']
601
+ if concept_data and len(concept_data) > 0:
602
+ # Verificar formato de los datos
603
+ if isinstance(concept_data[0], list) and len(concept_data[0]) == 2:
604
+ # Formato esperado: [["concepto", valor], ...]
605
+ df = pd.DataFrame(concept_data, columns=['Concepto', 'Relevancia'])
606
+ st.dataframe(df, use_container_width=True)
607
+ else:
608
+ st.write(concept_data) # Mostrar como está si no tiene el formato esperado
609
+ else:
610
+ st.info(t.get('no_concepts1', 'No hay conceptos clave disponibles para el Texto 1'))
611
+
612
+ # Mostrar gráfico si existe
613
+ if 'graph1' in analysis and analysis['graph1']:
614
+ st.subheader(t.get('graph1', 'Visualización del Texto 1'))
615
+ try:
616
+ if isinstance(analysis['graph1'], str) and analysis['graph1'].startswith('data:image'):
617
+ # Manejo para string base64
618
+ import base64
619
+ image_bytes = base64.b64decode(analysis['graph1'].split(',')[1])
620
+ st.image(image_bytes, use_column_width=True)
621
+ elif isinstance(analysis['graph1'], bytes):
622
+ # Manejo para bytes directos
623
+ st.image(analysis['graph1'], use_column_width=True)
624
+ else:
625
+ # Otro tipo de gráfico (matplotlib, etc.)
626
+ st.pyplot(analysis['graph1'])
627
+ except Exception as e:
628
+ logger.error(f"Error mostrando gráfico 1: {str(e)}")
629
+ st.error(t.get('error_graph1', 'Error al mostrar el gráfico del Texto 1'))
630
+ else:
631
+ st.info(t.get('no_text1', 'Texto 1 no disponible'))
632
+
633
+ # Tab para Texto 2
634
+ with tabs[1]:
635
+ if 'text2' in analysis and analysis['text2']:
636
+ st.text_area(
637
+ "Texto 2",
638
+ value=analysis['text2'],
639
+ height=150,
640
+ disabled=True,
641
+ label_visibility="collapsed",
642
+ key=f"text2_{str(analysis['_id'])}"
643
+ )
644
+
645
+ # Mostrar conceptos clave del texto 2
646
+ if 'key_concepts2' in analysis and analysis['key_concepts2']:
647
+ st.subheader(t.get('key_concepts2', 'Conceptos clave (Texto 2)'))
648
+
649
+ # Crear una tabla/dataframe de conceptos
650
+ concept_data = analysis['key_concepts2']
651
+ if concept_data and len(concept_data) > 0:
652
+ # Verificar formato de los datos
653
+ if isinstance(concept_data[0], list) and len(concept_data[0]) == 2:
654
+ # Formato esperado: [["concepto", valor], ...]
655
+ df = pd.DataFrame(concept_data, columns=['Concepto', 'Relevancia'])
656
+ st.dataframe(df, use_container_width=True)
657
+ else:
658
+ st.write(concept_data) # Mostrar como está si no tiene el formato esperado
659
+ else:
660
+ st.info(t.get('no_concepts2', 'No hay conceptos clave disponibles para el Texto 2'))
661
+
662
+ # Mostrar gráfico si existe
663
+ if 'graph2' in analysis and analysis['graph2']:
664
+ st.subheader(t.get('graph2', 'Visualización del Texto 2'))
665
+ try:
666
+ if isinstance(analysis['graph2'], str) and analysis['graph2'].startswith('data:image'):
667
+ # Manejo para string base64
668
+ import base64
669
+ image_bytes = base64.b64decode(analysis['graph2'].split(',')[1])
670
+ st.image(image_bytes, use_column_width=True)
671
+ elif isinstance(analysis['graph2'], bytes):
672
+ # Manejo para bytes directos
673
+ st.image(analysis['graph2'], use_column_width=True)
674
+ else:
675
+ # Otro tipo de gráfico (matplotlib, etc.)
676
+ st.pyplot(analysis['graph2'])
677
+ except Exception as e:
678
+ logger.error(f"Error mostrando gráfico 2: {str(e)}")
679
+ st.error(t.get('error_graph2', 'Error al mostrar el gráfico del Texto 2'))
680
+ else:
681
+ # Caso especial: si text2 está ausente pero text1 está presente
682
+ # mostrar text1 aquí también (para documentos de un solo texto)
683
+ if 'text1' in analysis and analysis['text1']:
684
+ st.info(t.get('using_text1', 'Usando el mismo texto como referencia.'))
685
+ st.text_area(
686
+ "Texto 1 como referencia",
687
+ value=analysis['text1'],
688
+ height=150,
689
+ disabled=True,
690
+ label_visibility="collapsed",
691
+ key=f"text1_ref_{str(analysis['_id'])}"
692
+ )
693
+ else:
694
+ st.info(t.get('no_text2', 'Texto 2 no disponible'))
695
+
696
+ # Tab para Comparación
697
+ with tabs[2]:
698
+ # Mostrar gráfico combinado si existe
699
+ if 'combined_graph' in analysis and analysis['combined_graph']:
700
+ st.subheader(t.get('combined_visualization', 'Visualización comparativa'))
701
+ try:
702
+ if isinstance(analysis['combined_graph'], str):
703
+ # Si es string base64
704
+ if analysis['combined_graph'].startswith('data:image'):
705
+ import base64
706
+ image_bytes = base64.b64decode(analysis['combined_graph'].split(',')[1])
707
+ else:
708
+ # Podría ser base64 sin prefijo
709
+ try:
710
+ import base64
711
+ image_bytes = base64.b64decode(analysis['combined_graph'])
712
+ except:
713
+ st.text(analysis['combined_graph'][:100] + "...") # Mostrar parte como texto
714
+ raise ValueError("Formato de gráfico combinado no reconocido")
715
+
716
+ st.image(image_bytes, use_column_width=True)
717
+ elif isinstance(analysis['combined_graph'], bytes):
718
+ # Si son bytes directos
719
+ st.image(analysis['combined_graph'], use_column_width=True)
720
+ else:
721
+ # Otro tipo de gráfico
722
+ st.pyplot(analysis['combined_graph'])
723
+ except Exception as e:
724
+ logger.error(f"Error mostrando gráfico combinado: {str(e)}")
725
+ st.error(t.get('error_combined_graph', 'Error al mostrar la visualización comparativa'))
726
+ else:
727
+ # Mostrar comparación de conceptos lado a lado
728
+ if ('key_concepts1' in analysis and analysis['key_concepts1'] and
729
+ 'key_concepts2' in analysis and analysis['key_concepts2']):
730
+
731
+ st.subheader(t.get('concept_comparison', 'Comparación de conceptos clave'))
732
+ col1, col2 = st.columns(2)
733
+
734
+ with col1:
735
+ st.markdown(f"**{t.get('text1_concepts', 'Conceptos del Texto 1')}**")
736
+ concept_data1 = analysis['key_concepts1']
737
+ if concept_data1 and len(concept_data1) > 0:
738
+ if isinstance(concept_data1[0], list) and len(concept_data1[0]) == 2:
739
+ df1 = pd.DataFrame(concept_data1, columns=['Concepto', 'Relevancia'])
740
+ st.dataframe(df1, use_container_width=True)
741
+ else:
742
+ st.write(concept_data1)
743
+
744
+ with col2:
745
+ st.markdown(f"**{t.get('text2_concepts', 'Conceptos del Texto 2')}**")
746
+ concept_data2 = analysis['key_concepts2']
747
+ if concept_data2 and len(concept_data2) > 0:
748
+ if isinstance(concept_data2[0], list) and len(concept_data2[0]) == 2:
749
+ df2 = pd.DataFrame(concept_data2, columns=['Concepto', 'Relevancia'])
750
+ st.dataframe(df2, use_container_width=True)
751
+ else:
752
+ st.write(concept_data2)
753
+
754
+ # Mostrar conceptos en común (intersección)
755
+ if (isinstance(analysis['key_concepts1'], list) and
756
+ isinstance(analysis['key_concepts2'], list)):
757
+
758
+ concepts1 = [item[0] for item in analysis['key_concepts1'] if isinstance(item, list) and len(item) == 2]
759
+ concepts2 = [item[0] for item in analysis['key_concepts2'] if isinstance(item, list) and len(item) == 2]
760
+
761
+ common_concepts = set(concepts1).intersection(set(concepts2))
762
+
763
+ if common_concepts:
764
+ st.subheader(t.get('common_concepts', 'Conceptos en común'))
765
+ st.write(", ".join(common_concepts))
766
+ else:
767
+ st.info(t.get('no_common_concepts', 'No se encontraron conceptos en común entre los textos'))
768
+ else:
769
+ st.info(t.get('no_comparison_data', 'No hay datos suficientes para la comparación'))
770
+
771
+ # Nota sobre la comparación
772
+ st.info(t.get('comparison_note',
773
+ 'La funcionalidad de comparación avanzada estará disponible en una próxima actualización.'))
774
 
775
  except Exception as e:
776
  logger.error(f"Error procesando análisis individual: {str(e)}")