File size: 11,546 Bytes
d73c879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8df9d97
d73c879
 
 
6d8e031
d73c879
8387dd2
d73c879
 
85836ea
d73c879
 
6d8e031
d73c879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d8e031
d73c879
 
 
6d8e031
d73c879
 
 
 
 
 
 
 
6d8e031
d73c879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858f976
 
d73c879
858f976
d73c879
 
 
 
 
 
6d8e031
d73c879
 
 
 
 
 
 
 
 
 
 
 
6d8e031
d73c879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d8e031
d73c879
 
 
85836ea
b86c7ed
 
6eff03a
b86c7ed
 
 
6eff03a
b86c7ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eff03a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02a0cc
8dadb07
6eff03a
0f12970
 
 
 
e02a0cc
 
d73c879
 
 
 
e02a0cc
d73c879
 
 
 
 
 
 
 
 
6eff03a
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#modules/semantic/semantic_interface.py
import streamlit as st
from streamlit_float import *
from streamlit_antd_components import *
from streamlit.components.v1 import html
import spacy_streamlit
import io
from io import BytesIO
import base64
import matplotlib.pyplot as plt
import pandas as pd
import re
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

# from ..database.semantic_export import export_user_interactions


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

# En semantic_interface.py
def display_semantic_interface(lang_code, nlp_models, semantic_t):
    try:
        # 1. Inicializar el estado de la sesión
        if 'semantic_state' not in st.session_state:
            st.session_state.semantic_state = {
                'analysis_count': 0,
                'last_analysis': None,
                'current_file': None,
                'pending_analysis': False  # Nuevo flag para controlar el análisis pendiente
            }

        # 2. Área de carga de archivo con mensaje informativo
        st.info(semantic_t.get('semantic_initial_instruction', 
            'Para comenzar un nuevo análisis semántico, cargue un archivo de texto (.txt)'))
            
        uploaded_file = st.file_uploader(
            semantic_t.get('semantic_file_uploader', 'Ingresar un archivo de texto para análisis semántico'),
            type=['txt'],
            key=f"semantic_file_uploader_{st.session_state.semantic_state['analysis_count']}"
        )

        # 2.1 Verificar si hay un archivo cargado y un análisis pendiente
        if uploaded_file is not None and st.session_state.semantic_state.get('pending_analysis', False):
            try:
                with st.spinner(semantic_t.get('semantic_processing', 'Semantic processing...')):
                    # Realizar análisis
                    text_content = uploaded_file.getvalue().decode('utf-8')
                    
                    analysis_result = process_semantic_input(
                        text_content, 
                        lang_code,
                        nlp_models,
                        semantic_t
                    )
                    
                    if analysis_result['success']:
                        # Guardar resultado
                        st.session_state.semantic_result = analysis_result
                        st.session_state.semantic_state['analysis_count'] += 1
                        st.session_state.semantic_state['current_file'] = uploaded_file.name
                        
                        # Guardar en base de datos
                        storage_success = store_student_semantic_result(
                            st.session_state.username,
                            text_content,
                            analysis_result['analysis']
                        )
                        
                        if storage_success:
                            st.success(
                                semantic_t.get('semantic_analysis_complete', 
                                'Análisis completado y guardado. Para realizar un nuevo análisis, cargue otro archivo.')
                            )
                        else:
                            st.error(semantic_t.get('semanctic_error_saving_message', 'There was a problem saving the semantic analysis. Please try again.'))
                    else:
                        st.error(analysis_result['message'])
                    
                # Restablecer el flag de análisis pendiente
                st.session_state.semantic_state['pending_analysis'] = False
                    
            except Exception as e:
                logger.error(f"Error en análisis semántico: {str(e)}")
                st.error(semantic_t.get('semantic_error_processing_message', f'Error processing text: {str(e)}'))
                # Restablecer el flag de análisis pendiente en caso de error
                st.session_state.semantic_state['pending_analysis'] = False

        # 3. Columnas para los botones y mensajes
        col1, col2 = st.columns([1,4])
        
        # 4. Botón de análisis
        with col1:
            analyze_button = st.button(
                semantic_t.get('semantic_analyze_button', 'Analyze'),
                key=f"semantic_analyze_button_{st.session_state.semantic_state['analysis_count']}",
                type="primary",
                icon="🔍",
                disabled=uploaded_file is None,
                use_container_width=True
            )

        # 5. Procesar análisis
        if analyze_button and uploaded_file is not None:
            # En lugar de realizar el análisis inmediatamente, establecer el flag
            st.session_state.semantic_state['pending_analysis'] = True
            # Forzar la recarga de la aplicación
            st.rerun()
        
        # 6. Mostrar resultados previos o mensaje inicial
        elif 'semantic_result' in st.session_state and st.session_state.semantic_result is not None:
            # Mostrar mensaje sobre el análisis actual
            st.info(
                semantic_t.get('current_analysis_message', 
                'Mostrando análisis del archivo: {}. Para realizar un nuevo análisis, cargue otro archivo.'
                ).format(st.session_state.semantic_state["current_file"])
            )
                        
            display_semantic_results(
                st.session_state.semantic_result,
                lang_code,
                semantic_t
            )
        else:
            st.info(semantic_t.get('semantic_upload_prompt', 'Cargue un archivo para comenzar el análisis semántico'))

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


#######################################
def display_semantic_results(semantic_result, lang_code, semantic_t):
    """
    Muestra los resultados del análisis semántico de conceptos clave.
    """
    if semantic_result is None or not semantic_result['success']:
        st.warning(semantic_t.get('semantic_no_results', 'No semantic results available'))
        return

    analysis = semantic_result['analysis']

    # Mostrar conceptos clave en formato horizontal
    st.subheader(semantic_t.get('key_concepts', 'Key Concepts'))
    if 'key_concepts' in analysis and analysis['key_concepts']:
        # Crear tabla de conceptos
        df = pd.DataFrame(
            analysis['key_concepts'],
            columns=[
                semantic_t.get('concept', 'Concept'),
                semantic_t.get('frequency', 'Frequency')
            ]
        )
        
        # Convertir DataFrame a formato horizontal
        st.write(
            """
            <style>
            .concept-table {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                margin-bottom: 20px;
            }
            .concept-item {
                background-color: #f0f2f6;
                border-radius: 5px;
                padding: 8px 12px;
                display: flex;
                align-items: center;
                gap: 8px;
            }
            .concept-name {
                font-weight: bold;
            }
            .concept-freq {
                color: #666;
                font-size: 0.9em;
            }
            </style>
            <div class="concept-table">
            """ + 
            ''.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 df.values
            ]) +
            "</div>",
            unsafe_allow_html=True
        )
    else:
        st.info(semantic_t.get('semantic_no_key_concepts', 'No key semantic concepts found'))

    # Gráfico de conceptos
    # st.subheader(semantic_t.get('concept_graph', 'Concepts Graph'))
    #Colocar aquí el bloque de código 
    if 'concept_graph' in analysis and analysis['concept_graph'] is not None:
        try:
            # Container para el grafo con estilos mejorados
            st.markdown(
                """
                <style>
                .graph-container {
                    background-color: white;
                    border-radius: 10px;
                    padding: 20px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    margin: 10px 0;
                }
                .button-container {
                    display: flex;
                    gap: 10px;
                    margin: 10px 0;
                }
                </style>
                """,
                unsafe_allow_html=True
            )
    #Colocar aquí el bloque de código 

            with st.container():
                st.markdown('<div class="graph-container">', unsafe_allow_html=True)
                
                # Mostrar grafo
                graph_bytes = analysis['concept_graph']
                graph_base64 = base64.b64encode(graph_bytes).decode()
                st.markdown(
                    f'<img src="data:image/png;base64,{graph_base64}" alt="Concept Graph" style="width:100%;"/>',
                    unsafe_allow_html=True
                )
                
                # Leyenda del grafo
                #st.caption(semantic_t.get(
                #    'graph_description',
                #    'Visualización de relaciones entre conceptos clave identificados en el texto.'
                #))
                
                st.markdown('</div>', unsafe_allow_html=True)

            # Expandible con la interpretación
            with st.expander("📊 " + semantic_t.get('semantic_graph_interpretation', "Interpretación del gráfico semántico")):
                 st.markdown(f"""
                    - 🔀 {semantic_t.get('semantic_arrow_meaning', 'Las flechas indican la dirección de la relación entre conceptos')}
                    - 🎨 {semantic_t.get('semantic_color_meaning', 'Los colores más intensos indican conceptos más centrales en el texto')}
                    - ⭕ {semantic_t.get('semantic_size_meaning', 'El tamaño de los nodos representa la frecuencia del concepto')}
                    - ↔️ {semantic_t.get('semantic_thickness_meaning', 'El grosor de las líneas indica la fuerza de la conexión')}
                """)
            
            # Contenedor para botones
            col1, col2 = st.columns([1,4])
            with col1:
                st.download_button(
                    label="📥 " + semantic_t.get('download_semantic_network_graph', "Descargar gráfico de red semántica"),
                    data=graph_bytes,
                    file_name="semantic_graph.png",
                    mime="image/png",
                    use_container_width=True
                )
        
        except Exception as e:
            logger.error(f"Error displaying graph: {str(e)}")
            st.error(semantic_t.get('graph_error', 'Error displaying the graph'))
    else:
        st.info(semantic_t.get('no_graph', 'No concept graph available'))