File size: 10,138 Bytes
8292acf
 
 
 
 
 
 
 
fd182dd
b221c8f
8292acf
 
664f529
8292acf
9fb8ab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664f529
8292acf
664f529
8292acf
664f529
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa115a7
664f529
 
 
 
 
 
 
 
 
 
aa115a7
664f529
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa115a7
 
 
 
 
 
 
 
 
 
664f529
 
aa115a7
664f529
aa115a7
 
 
664f529
 
 
 
 
 
 
 
 
 
aa115a7
 
 
 
 
 
 
 
 
 
664f529
 
aa115a7
664f529
aa115a7
 
 
664f529
 
 
 
 
 
 
aa115a7
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# modules/discourse/discourse/discourse_interface.py

import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import logging
from ..utils.widget_utils import generate_unique_key
from .discourse_process import perform_discourse_analysis
from ..database.chat_mongo_db import store_chat_history
from ..database.discourse_mongo_db import store_student_discourse_result

logger = logging.getLogger(__name__)
#############################################################################################

def display_discourse_interface(lang_code, nlp_models, discourse_t):
    """
    Interfaz para el análisis del discurso
    Args:
        lang_code: Código del idioma actual
        nlp_models: Modelos de spaCy cargados
        discourse_t: Diccionario de traducciones
    """
    try:
        # 1. Inicializar estado si no existe
        if 'discourse_state' not in st.session_state:
            st.session_state.discourse_state = {
                'analysis_count': 0,
                'last_analysis': None,
                'current_files': None
            }

        # 2. Título y descripción
        st.subheader(discourse_t.get('discourse_title', 'Análisis del Discurso'))
        st.info(discourse_t.get('initial_instruction', 
            'Cargue dos archivos de texto para realizar un análisis comparativo del discurso.'))

        # 3. Área de carga de archivos
        col1, col2 = st.columns(2)
        with col1:
            st.markdown(discourse_t.get('file1_label', "**Documento 1 (Patrón)**"))
            uploaded_file1 = st.file_uploader(
                discourse_t.get('file_uploader1', "Cargar archivo 1"),
                type=['txt'],
                key=f"discourse_file1_{st.session_state.discourse_state['analysis_count']}"
            )

        with col2:
            st.markdown(discourse_t.get('file2_label', "**Documento 2 (Comparación)**"))
            uploaded_file2 = st.file_uploader(
                discourse_t.get('file_uploader2', "Cargar archivo 2"),
                type=['txt'],
                key=f"discourse_file2_{st.session_state.discourse_state['analysis_count']}"
            )

        # 4. Botón de análisis
        col1, col2, col3 = st.columns([1,2,1])
        with col1:
            analyze_button = st.button(
                discourse_t.get('discourse_analyze_button', 'Analizar Discurso'),
                key=generate_unique_key("discourse", "analyze_button"),
                type="primary",
                icon="🔍",
                disabled=not (uploaded_file1 and uploaded_file2),
                use_container_width=True
            )

        # 5. Proceso de análisis
        if analyze_button and uploaded_file1 and uploaded_file2:
            try:
                with st.spinner(discourse_t.get('processing', 'Procesando análisis...')):
                    # Leer contenido de archivos
                    text1 = uploaded_file1.getvalue().decode('utf-8')
                    text2 = uploaded_file2.getvalue().decode('utf-8')

                    # Realizar análisis
                    result = perform_discourse_analysis(
                        text1, 
                        text2, 
                        nlp_models[lang_code],
                        lang_code
                    )

                    if result['success']:
                        # Guardar estado
                        st.session_state.discourse_result = result
                        st.session_state.discourse_state['analysis_count'] += 1
                        st.session_state.discourse_state['current_files'] = (
                            uploaded_file1.name,
                            uploaded_file2.name
                        )

                        # Guardar en base de datos
                        if store_student_discourse_result(
                            st.session_state.username,
                            text1,
                            text2,
                            result
                        ):
                            st.success(discourse_t.get('success_message', 'Análisis guardado correctamente'))
                            
                            # Mostrar resultados
                            display_discourse_results(result, lang_code, discourse_t)
                        else:
                            st.error(discourse_t.get('error_message', 'Error al guardar el análisis'))
                    else:
                        st.error(discourse_t.get('analysis_error', 'Error en el análisis'))

            except Exception as e:
                logger.error(f"Error en análisis del discurso: {str(e)}")
                st.error(discourse_t.get('error_processing', f'Error procesando archivos: {str(e)}'))

        # 6. Mostrar resultados previos
        elif 'discourse_result' in st.session_state and st.session_state.discourse_result is not None:
            if st.session_state.discourse_state.get('current_files'):
                st.info(
                    discourse_t.get('current_analysis_message', 'Mostrando análisis de los archivos: {} y {}')
                    .format(*st.session_state.discourse_state['current_files'])
                )
            display_discourse_results(
                st.session_state.discourse_result,
                lang_code,
                discourse_t
            )

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





##########################################################################################

def display_discourse_results(result, lang_code, discourse_t):
    """
    Muestra los resultados del análisis del discurso con conceptos en formato horizontal
    """
    if not result.get('success'):
        st.warning(discourse_t.get('no_results', 'No hay resultados disponibles'))
        return

    # Estilo CSS para los conceptos horizontales
    st.markdown("""
        <style>
        .concepts-container {
            display: flex;
            flex-wrap: nowrap;
            gap: 8px;
            padding: 12px;
            background-color: #f8f9fa;
            border-radius: 8px;
            overflow-x: auto;
            margin-bottom: 15px;
            white-space: nowrap;
        }
        .concept-item {
            background-color: white;
            border-radius: 4px;
            padding: 6px 10px;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
            flex-shrink: 0;
            min-width: fit-content;
        }
        .concept-name {
            font-weight: 500;
            color: #1f2937;
            font-size: 0.85em;
        }
        .concept-freq {
            color: #6b7280;
            font-size: 0.75em;
        }
        .graph-container {
            background-color: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-top: 10px;
        }
        </style>
    """, unsafe_allow_html=True)

    col1, col2 = st.columns(2)

    # Documento 1
    with col1:
        with st.expander(discourse_t.get('doc1_title', 'Documento 1'), expanded=True):
            st.subheader(discourse_t.get('key_concepts', 'Conceptos Clave'))
            if 'key_concepts1' in result:
                # Crear HTML para conceptos horizontales de manera más compacta
                concepts_html = f"""
                    <div class="concepts-container">
                        {''.join([
                            f'<div class="concept-item"><span class="concept-name">{concept}</span>'
                            f'<span class="concept-freq">({freq:.2f})</span></div>'
                            for concept, freq in result['key_concepts1']
                        ])}
                    </div>
                """
                st.markdown(concepts_html, unsafe_allow_html=True)

                # Mostrar grafo
                if 'graph1' in result:
                    st.markdown('<div class="graph-container">', unsafe_allow_html=True)
                    st.pyplot(result['graph1'])
                    st.markdown('</div>', unsafe_allow_html=True)
                else:
                    st.warning(discourse_t.get('graph_not_available', 'Gráfico no disponible'))
            else:
                st.warning(discourse_t.get('concepts_not_available', 'Conceptos no disponibles'))

    # Documento 2
    with col2:
        with st.expander(discourse_t.get('doc2_title', 'Documento 2'), expanded=True):
            st.subheader(discourse_t.get('key_concepts', 'Conceptos Clave'))
            if 'key_concepts2' in result:
                # Crear HTML para conceptos horizontales de manera más compacta
                concepts_html = f"""
                    <div class="concepts-container">
                        {''.join([
                            f'<div class="concept-item"><span class="concept-name">{concept}</span>'
                            f'<span class="concept-freq">({freq:.2f})</span></div>'
                            for concept, freq in result['key_concepts2']
                        ])}
                    </div>
                """
                st.markdown(concepts_html, unsafe_allow_html=True)

                # Mostrar grafo
                if 'graph2' in result:
                    st.markdown('<div class="graph-container">', unsafe_allow_html=True)
                    st.pyplot(result['graph2'])
                    st.markdown('</div>', unsafe_allow_html=True)
                else:
                    st.warning(discourse_t.get('graph_not_available', 'Gráfico no disponible'))
            else:
                st.warning(discourse_t.get('concepts_not_available', 'Conceptos no disponibles'))

    # Nota informativa sobre la comparación
    st.info(discourse_t.get('comparison_note', 
        'La funcionalidad de comparación detallada estará disponible en una próxima actualización.'))