AIdeaText commited on
Commit
26609dc
·
verified ·
1 Parent(s): 5a8e685

Update modules/studentact/student_activities_v2.py

Browse files
modules/studentact/student_activities_v2.py CHANGED
@@ -538,186 +538,155 @@ 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 (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
  #################################################################################
@@ -771,18 +740,3 @@ def display_chat_activities(username: str, t: dict):
771
  st.error(t.get('error_chat', 'Error al mostrar historial del chat'))
772
 
773
  #################################################################################
774
-
775
- def display_discourse_comparison(analysis: dict, t: dict):
776
- """Muestra la comparación de análisis del discurso"""
777
- st.subheader(t.get('comparison_results', 'Resultados de la comparación'))
778
-
779
- col1, col2 = st.columns(2)
780
- with col1:
781
- st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
782
- df1 = pd.DataFrame(analysis['key_concepts1'])
783
- st.dataframe(df1)
784
-
785
- with col2:
786
- st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
787
- df2 = pd.DataFrame(analysis['key_concepts2'])
788
- st.dataframe(df2)
 
538
 
539
  def display_discourse_activities(username: str, t: dict):
540
  """
541
+ Muestra actividades de análisis del discurso en la sección de historial
 
542
  """
543
  try:
544
  logger.info(f"Recuperando análisis del discurso para {username}")
545
 
546
+ # Obtener análisis - usando la función existente
547
+ analyses = get_student_discourse_analysis(username)
548
 
549
+ if not analyses:
550
+ logger.info("No se encontraron análisis del discurso")
 
551
  st.info(t.get('no_discourse_analyses', 'No hay análisis comparados de textos registrados'))
552
  return
553
 
554
+ logger.info(f"Procesando {len(analyses)} análisis del discurso")
 
555
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556
  for analysis in analyses:
557
  try:
558
+ # Formatear fecha - con manejo de errores mejorado
559
  try:
560
  timestamp = datetime.fromisoformat(analysis.get('timestamp', '').replace('Z', '+00:00'))
561
  formatted_date = timestamp.strftime("%d/%m/%Y %H:%M:%S")
562
  except:
563
  formatted_date = str(analysis.get('timestamp', 'Fecha desconocida'))
564
 
565
+ # Crear expander
566
+ with st.expander(f"{t.get('analysis_date', 'Fecha')}: {formatted_date}", expanded=False):
567
+ # Mostrar conceptos si están disponibles
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568
  if 'key_concepts1' in analysis and analysis['key_concepts1']:
569
+ # Usar la función de comparación existente para mostrar conceptos
570
+ display_discourse_comparison(analysis, t)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
571
 
572
+ # Mostrar gráficos - intentando diferentes campos y formatos
573
+ has_graphs = False
574
 
575
+ # Primero intentar el gráfico combinado
576
+ if 'combined_graph' in analysis and analysis['combined_graph']:
577
+ has_graphs = True
578
+ st.markdown(f"### {t.get('combined_graph_title', 'Visualización Comparativa')}")
579
+ try:
580
+ # Si es bytes directamente
581
+ if isinstance(analysis['combined_graph'], bytes):
582
+ st.image(analysis['combined_graph'], use_column_width=True)
583
+ # Si es string base64
584
+ elif isinstance(analysis['combined_graph'], str):
585
+ try:
586
+ import base64
587
+ image_bytes = base64.b64decode(analysis['combined_graph'])
588
+ st.image(image_bytes, use_column_width=True)
589
+ except:
590
+ st.error(t.get('error_decoding', 'Error decodificando imagen'))
591
  else:
592
+ st.error(t.get('unknown_format', 'Formato de imagen desconocido'))
593
+ except Exception as e:
594
+ logger.error(f"Error mostrando combined_graph: {str(e)}")
595
+ st.error(t.get('error_graph', 'Error mostrando visualización'))
596
+
597
+ # Luego intentar gráficos individuales
598
+ for graph_key, title in [
599
+ ('graph1', t.get('graph1_title', 'Visualización Texto 1')),
600
+ ('graph2', t.get('graph2_title', 'Visualización Texto 2'))
601
+ ]:
602
+ if graph_key in analysis and analysis[graph_key]:
603
+ has_graphs = True
604
+ st.markdown(f"### {title}")
605
  try:
606
+ # Si es bytes directamente
607
+ if isinstance(analysis[graph_key], bytes):
608
+ st.image(analysis[graph_key], use_column_width=True)
609
+ # Si es string base64
610
+ elif isinstance(analysis[graph_key], str):
 
611
  try:
612
  import base64
613
+ image_bytes = base64.b64decode(analysis[graph_key])
 
 
 
 
 
614
  st.image(image_bytes, use_column_width=True)
615
  except:
616
+ st.error(t.get('error_decoding', 'Error decodificando imagen'))
 
 
 
 
 
 
617
  else:
618
+ st.error(t.get('unknown_format', 'Formato de imagen desconocido'))
619
  except Exception as e:
620
+ logger.error(f"Error mostrando {graph_key}: {str(e)}")
621
+ st.error(t.get('error_graph', f'Error mostrando {title}'))
 
 
 
622
 
623
+ # Mensaje si no hay gráficos
624
+ if not has_graphs:
625
+ st.info(t.get('no_visualization', 'No hay visualizaciones disponibles'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
626
 
627
  except Exception as e:
628
  logger.error(f"Error procesando análisis individual: {str(e)}")
 
629
  continue
630
+
631
  except Exception as e:
632
+ logger.error(f"Error mostrando análisis del discurso: {str(e)}")
633
  st.error(t.get('error_discourse', 'Error al mostrar análisis comparado de textos'))
634
 
635
+ #################################################################################
636
 
637
+ def display_discourse_comparison(analysis: dict, t: dict):
638
+ """
639
+ Muestra la comparación de conceptos clave en análisis del discurso.
640
+ Mejorada para manejar diferentes formatos y errores.
641
+ """
642
+ st.subheader(t.get('comparison_results', 'Resultados de la comparación'))
643
+
644
+ # Verificar si tenemos los conceptos necesarios
645
+ if not ('key_concepts1' in analysis and analysis['key_concepts1']):
646
+ st.info(t.get('no_concepts', 'No hay conceptos disponibles para comparar'))
647
+ return
648
+
649
+ # Mostrar en dos columnas
650
+ col1, col2 = st.columns(2)
651
+
652
+ # Columna 1: Conceptos del texto 1
653
+ with col1:
654
+ st.markdown(f"**{t.get('concepts_text_1', 'Conceptos Texto 1')}**")
655
+ try:
656
+ # Comprobar formato y crear DataFrame
657
+ if isinstance(analysis['key_concepts1'], list) and len(analysis['key_concepts1']) > 0:
658
+ if isinstance(analysis['key_concepts1'][0], list) and len(analysis['key_concepts1'][0]) == 2:
659
+ df1 = pd.DataFrame(analysis['key_concepts1'], columns=['Concepto', 'Relevancia'])
660
+ st.dataframe(df1)
661
+ else:
662
+ # Si no tiene el formato esperado, mostrar como lista
663
+ st.write(", ".join(str(c) for c in analysis['key_concepts1']))
664
+ else:
665
+ st.write(str(analysis['key_concepts1']))
666
+ except Exception as e:
667
+ logger.error(f"Error mostrando key_concepts1: {str(e)}")
668
+ st.error(t.get('error_concepts1', 'Error mostrando conceptos del Texto 1'))
669
+
670
+ # Columna 2: Conceptos del texto 2
671
+ with col2:
672
+ st.markdown(f"**{t.get('concepts_text_2', 'Conceptos Texto 2')}**")
673
+ if 'key_concepts2' in analysis and analysis['key_concepts2']:
674
+ try:
675
+ # Comprobar formato y crear DataFrame
676
+ if isinstance(analysis['key_concepts2'], list) and len(analysis['key_concepts2']) > 0:
677
+ if isinstance(analysis['key_concepts2'][0], list) and len(analysis['key_concepts2'][0]) == 2:
678
+ df2 = pd.DataFrame(analysis['key_concepts2'], columns=['Concepto', 'Relevancia'])
679
+ st.dataframe(df2)
680
+ else:
681
+ # Si no tiene el formato esperado, mostrar como lista
682
+ st.write(", ".join(str(c) for c in analysis['key_concepts2']))
683
+ else:
684
+ st.write(str(analysis['key_concepts2']))
685
+ except Exception as e:
686
+ logger.error(f"Error mostrando key_concepts2: {str(e)}")
687
+ st.error(t.get('error_concepts2', 'Error mostrando conceptos del Texto 2'))
688
+ else:
689
+ st.info(t.get('no_concepts2', 'No hay conceptos disponibles para el Texto 2'))
690
 
691
 
692
  #################################################################################
 
740
  st.error(t.get('error_chat', 'Error al mostrar historial del chat'))
741
 
742
  #################################################################################