File size: 6,619 Bytes
d05879e
 
 
 
 
 
 
9bcd9c9
 
d05879e
 
 
 
 
 
38239d9
d05879e
 
 
 
9bcd9c9
 
 
 
 
 
 
 
 
 
 
d05879e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bcd9c9
 
 
 
 
 
d05879e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bcd9c9
d05879e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8bf136
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# modules/discourse/discourse/discourse_live_interface.py

import streamlit as st
from streamlit_float import *
from streamlit_antd_components import *
import pandas as pd
import logging
import io
import matplotlib.pyplot as plt

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

# Importaciones locales
from .discourse_process import perform_discourse_analysis
from .discourse_interface import display_discourse_results  # A帽adida esta importaci贸n
from ..utils.widget_utils import generate_unique_key
from ..database.discourse_mongo_db import store_student_discourse_result
from ..database.chat_mongo_db import store_chat_history, get_chat_history

def fig_to_bytes(fig):
    """Convierte una figura de matplotlib a bytes."""
    try:
        buf = io.BytesIO()
        fig.savefig(buf, format='png', dpi=300, bbox_inches='tight')
        buf.seek(0)
        return buf.getvalue()
    except Exception as e:
        logger.error(f"Error en fig_to_bytes: {str(e)}")
        return None

def display_discourse_live_interface(lang_code, nlp_models, discourse_t):
    """
    Interfaz para el an谩lisis del discurso en vivo
    """
    try:
        # 1. Inicializar el estado de la sesi贸n
        if 'discourse_live_state' not in st.session_state:
            st.session_state.discourse_live_state = {
                'analysis_count': 0,
                'current_text1': '',
                'current_text2': '',
                'last_result': None,
                'text_changed': False
            }

        # 2. Funci贸n para manejar cambios en los textos
        def on_text1_change():
            current_text = st.session_state.discourse_live_text1
            st.session_state.discourse_live_state['current_text1'] = current_text
            st.session_state.discourse_live_state['text_changed'] = True

        def on_text2_change():
            current_text = st.session_state.discourse_live_text2
            st.session_state.discourse_live_state['current_text2'] = current_text
            st.session_state.discourse_live_state['text_changed'] = True

        # 3. Crear columnas con proporci贸n 1:3
        input_col, result_col = st.columns([1, 3])

        # Columna izquierda: Entrada de textos
        with input_col:
            st.subheader(discourse_t.get('enter_text', 'Ingrese sus textos'))
            
            # Primer 谩rea de texto
            st.markdown("**Texto 1 (Patr贸n)**")
            text_input1 = st.text_area(
                "Texto 1",
                height=250,
                key="discourse_live_text1",
                value=st.session_state.discourse_live_state.get('current_text1', ''),
                on_change=on_text1_change,
                label_visibility="collapsed"
            )

            # Segundo 谩rea de texto
            st.markdown("**Texto 2 (Comparaci贸n)**")
            text_input2 = st.text_area(
                "Texto 2",
                height=250,
                key="discourse_live_text2",
                value=st.session_state.discourse_live_state.get('current_text2', ''),
                on_change=on_text2_change,
                label_visibility="collapsed"
            )

            # Bot贸n de an谩lisis
            analyze_button = st.button(
                discourse_t.get('analyze_button', 'Analizar'),
                key="discourse_live_analyze",
                type="primary",
                icon="馃攳",
                disabled=not (text_input1 and text_input2),
                use_container_width=True
            )

            if analyze_button and text_input1 and text_input2:
                try:
                    with st.spinner(discourse_t.get('processing', 'Procesando...')):
                        # Realizar an谩lisis
                        result = perform_discourse_analysis(
                            text_input1,
                            text_input2,
                            nlp_models[lang_code],
                            lang_code
                        )

                        if result['success']:
                            # Convertir gr谩ficos a bytes antes de guardar
                            if 'graph1' in result:
                                result['graph1_bytes'] = fig_to_bytes(result['graph1'])
                            if 'graph2' in result:
                                result['graph2_bytes'] = fig_to_bytes(result['graph2'])

                            st.session_state.discourse_live_state['last_result'] = result
                            st.session_state.discourse_live_state['analysis_count'] += 1
                            st.session_state.discourse_live_state['text_changed'] = False
                            
                            # Guardar en base de datos
                            store_student_discourse_result(
                                st.session_state.username,
                                text_input1,
                                text_input2,
                                result
                            )
                        else:
                            st.error(result.get('message', 'Error en el an谩lisis'))

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

                    
        # Columna derecha: Visualizaci贸n de resultados
        with result_col:
            st.subheader(discourse_t.get('live_results', 'Resultados en vivo'))

            if 'last_result' in st.session_state.discourse_live_state and \
               st.session_state.discourse_live_state['last_result'] is not None:
                
                # Mostrar resultados usando la misma funci贸n que el an谩lisis normal
                display_discourse_results(
                    st.session_state.discourse_live_state['last_result'],
                    lang_code,
                    discourse_t
                )

            elif st.session_state.discourse_live_state.get('text_changed', False):
                st.info(discourse_t.get('changes_pending', 
                    'Los textos han cambiado. Presione Analizar para ver los nuevos resultados.'))
            else:
                st.info(discourse_t.get('initial_message', 
                    'Ingrese los textos y presione Analizar para ver los resultados.'))

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