File size: 5,505 Bytes
fec99d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# modules/semantic/semantic_live_interface.py
import streamlit as st
from streamlit_float import *
from streamlit_antd_components import *
import pandas as pd
import logging

# Configuración del logger
logger = logging.getLogger(__name__)

# Importaciones locales
from .semantic_process import (
    process_semantic_input,
    format_semantic_results
)

from ..utils.widget_utils import generate_unique_key
from ..database.semantic_mongo_db import store_student_semantic_result
from ..database.chat_mongo_db import store_chat_history, get_chat_history

def display_semantic_live_interface(lang_code, nlp_models, semantic_t):
    """
    Interfaz para el análisis semántico en vivo
    Args:
        lang_code: Código del idioma actual
        nlp_models: Modelos de spaCy cargados
        semantic_t: Diccionario de traducciones semánticas
    """
    try:
        # 1. Inicializar el estado de la sesión para el análisis en vivo
        if 'semantic_live_state' not in st.session_state:
            st.session_state.semantic_live_state = {
                'analysis_count': 0,
                'last_analysis': None,
                'current_text': ''
            }

        # 2. Crear dos columnas
        col1, col2 = st.columns(2)

        # Columna izquierda: Entrada de texto
        with col1:
            st.subheader(semantic_t.get('enter_text', 'Ingrese su texto'))
            
            # Área de texto para input
            text_input = st.text_area(
                semantic_t.get('text_input_label', 'Escriba o pegue su texto aquí'),
                height=400,
                key=f"semantic_live_text_{st.session_state.semantic_live_state['analysis_count']}"
            )

            # Botón de análisis
            analyze_button = st.button(
                semantic_t.get('analyze_button', 'Analizar'),
                key=f"semantic_live_analyze_{st.session_state.semantic_live_state['analysis_count']}",
                type="primary",
                icon="🔍",
                disabled=not text_input,
                use_container_width=True
            )

        # Columna derecha: Visualización de resultados
        with col2:
            st.subheader(semantic_t.get('live_results', 'Resultados en vivo'))

            # Procesar análisis cuando se presiona el botón
            if analyze_button and text_input:
                try:
                    with st.spinner(semantic_t.get('processing', 'Procesando...')):
                        # Realizar análisis
                        analysis_result = process_semantic_input(
                            text_input,
                            lang_code,
                            nlp_models,
                            semantic_t
                        )

                        if analysis_result['success']:
                            # Guardar resultado
                            st.session_state.semantic_live_result = analysis_result
                            st.session_state.semantic_live_state['analysis_count'] += 1
                            
                            # Guardar en base de datos
                            store_student_semantic_result(
                                st.session_state.username,
                                text_input,
                                analysis_result['analysis']
                            )

                            # Mostrar gráfico de conceptos
                            if 'concept_graph' in analysis_result['analysis'] and analysis_result['analysis']['concept_graph'] is not None:
                                st.image(analysis_result['analysis']['concept_graph'])
                            else:
                                st.info(semantic_t.get('no_graph', 'No hay gráfico disponible'))

                            # Mostrar tabla de conceptos clave
                            if 'key_concepts' in analysis_result['analysis'] and analysis_result['analysis']['key_concepts']:
                                st.subheader(semantic_t.get('key_concepts', 'Conceptos Clave'))
                                df = pd.DataFrame(
                                    analysis_result['analysis']['key_concepts'],
                                    columns=[
                                        semantic_t.get('concept', 'Concepto'),
                                        semantic_t.get('frequency', 'Frecuencia')
                                    ]
                                )
                                st.dataframe(
                                    df,
                                    hide_index=True,
                                    column_config={
                                        semantic_t.get('frequency', 'Frecuencia'): st.column_config.NumberColumn(
                                            format="%.2f"
                                        )
                                    }
                                )
                        else:
                            st.error(analysis_result['message'])

                except Exception as e:
                    logger.error(f"Error en análisis semántico en vivo: {str(e)}")
                    st.error(semantic_t.get('error_processing', f'Error al procesar el texto: {str(e)}'))

    except Exception as e:
        logger.error(f"Error general en interfaz semántica en vivo: {str(e)}")
        st.error(semantic_t.get('general_error', "Se produjo un error. Por favor, intente de nuevo."))