File size: 9,972 Bytes
c7330d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19de296
c7330d5
 
c67983b
 
 
3f98e79
 
ac689f1
3f98e79
dd52ef3
a22a995
dd52ef3
 
ac689f1
 
 
 
dd52ef3
ac689f1
df3c320
ac689f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a22a995
ac689f1
df3c320
ac689f1
 
 
 
df3c320
 
ac689f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df3c320
ac689f1
 
 
 
 
 
 
 
 
 
dd52ef3
ac689f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd52ef3
ac689f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd52ef3
 
 
 
3f98e79
ac689f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e3e643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#modules/semantic/semantic_interface.py
# Importaciones necesarias
import streamlit as st
from streamlit_float import *
from streamlit_antd_components import *
from streamlit.components.v1 import html
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.semantic_export import export_user_interactions


#modules/semantic/semantic_interface.py
# [Mantener las importaciones igual...]

def display_semantic_interface(lang_code, nlp_models, semantic_t):
    """
    Interfaz para el análisis semántico con controles fijos y manejo de estado mejorado
    """
    try:
        # Inicializar estados
        if 'semantic_analysis_counter' not in st.session_state:
            st.session_state.semantic_analysis_counter = 0
        if 'semantic_file_content' not in st.session_state:
            st.session_state.semantic_file_content = None
        if 'semantic_analysis_done' not in st.session_state:
            st.session_state.semantic_analysis_done = False

        # Contenedor principal con bordes
        with st.container():
            st.markdown("### Semantic Analysis Controls")
            st.markdown("---")

            # Sección de carga de archivo
            col_file, _ = st.columns([6, 4])
            with col_file:
                uploaded_file = st.file_uploader(
                    semantic_t.get('file_uploader', 'Upload a text file for analysis'),
                    type=['txt'],
                    key=f"semantic_file_uploader_{st.session_state.semantic_analysis_counter}",
                    on_change=lambda: handle_file_upload(uploaded_file)
                )

            # Contenedor fijo para botones
            st.markdown("---")
            col1, col2, col3, col4 = st.columns([2, 2, 2, 6])
            
            with col1:
                analyze_button = st.button(
                    semantic_t.get('analyze_button', 'Analyze Text'),
                    disabled=not st.session_state.semantic_file_content,
                    use_container_width=True,
                    key="analyze_semantic"
                )

            with col2:
                export_button = st.button(
                    semantic_t.get('export_button', 'Export Analysis'),
                    disabled=not st.session_state.semantic_analysis_done,
                    use_container_width=True,
                    key="export_semantic"
                )

            with col3:
                clear_button = st.button(
                    semantic_t.get('clear_button', 'Clear Analysis'),
                    disabled=not st.session_state.semantic_analysis_done,
                    use_container_width=True,
                    key="clear_semantic"
                )

            st.markdown("---")

            # Procesar análisis
            if analyze_button and st.session_state.semantic_file_content:
                try:
                    with st.spinner(semantic_t.get('processing', 'Processing...')):
                        analysis_result = process_semantic_input(
                            st.session_state.semantic_file_content,
                            lang_code,
                            nlp_models,
                            semantic_t
                        )
                        
                        if analysis_result['success']:
                            st.session_state.semantic_result = analysis_result
                            st.session_state.semantic_analysis_done = True
                            st.session_state.semantic_analysis_counter += 1
                            
                            # Guardar en la base de datos
                            if store_student_semantic_result(
                                st.session_state.username,
                                st.session_state.semantic_file_content,
                                analysis_result['analysis']
                            ):
                                st.success(semantic_t.get('success_message', 'Analysis saved successfully'))
                                # Mostrar resultados
                                display_semantic_results(
                                    analysis_result,
                                    lang_code,
                                    semantic_t
                                )
                            else:
                                st.error(semantic_t.get('error_message', 'Error saving analysis'))
                        else:
                            st.error(analysis_result['message'])
                except Exception as e:
                    logger.error(f"Error en análisis semántico: {str(e)}")
                    st.error(semantic_t.get('error_processing', f'Error processing text: {str(e)}'))

            # Manejo de exportación
            if export_button and st.session_state.semantic_analysis_done:
                pdf_buffer = export_user_interactions(st.session_state.username, 'semantic')
                st.download_button(
                    label=semantic_t.get('download_pdf', 'Download PDF'),
                    data=pdf_buffer,
                    file_name="semantic_analysis.pdf",
                    mime="application/pdf",
                    key=f"semantic_download_{st.session_state.semantic_analysis_counter}"
                )

            # Manejo de limpieza
            if clear_button:
                st.session_state.semantic_file_content = None
                st.session_state.semantic_analysis_done = False
                st.session_state.semantic_result = None
                st.rerun()

            # Mostrar resultados previos o mensaje inicial
            if st.session_state.semantic_analysis_done and 'semantic_result' in st.session_state:
                display_semantic_results(
                    st.session_state.semantic_result,
                    lang_code,
                    semantic_t
                )
            elif not st.session_state.semantic_file_content:
                st.info(semantic_t.get('initial_message', 'Upload a file to begin analysis'))

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

def handle_file_upload(uploaded_file):
    """Maneja la carga de archivos y mantiene el estado"""
    if uploaded_file is not None:
        try:
            content = uploaded_file.getvalue().decode('utf-8')
            st.session_state.semantic_file_content = content
            st.session_state.page = 'semantic'  # Mantener en la página semántica
        except Exception as e:
            logger.error(f"Error al cargar archivo: {str(e)}")
            st.error("Error al cargar el archivo. Asegúrese de que es un archivo de texto válido.")
            st.session_state.semantic_file_content = None
    else:
        st.session_state.semantic_file_content = None

# [Resto del código igual...] ###############################################################################################################

def display_semantic_results(result, lang_code, semantic_t):
    """
    Muestra los resultados del análisis semántico en tabs
    """
    if result is None or not result['success']:
        st.warning(semantic_t.get('no_results', 'No results available'))
        return

    analysis = result['analysis']
    
    # Crear tabs para los resultados
    tab1, tab2 = st.tabs([
        semantic_t.get('concepts_tab', 'Key Concepts Analysis'),
        semantic_t.get('entities_tab', 'Entities Analysis')
    ])
    
    # Tab 1: Conceptos Clave
    with tab1:
        col1, col2 = st.columns(2)
        
        # Columna 1: Lista de conceptos
        with col1:
            st.subheader(semantic_t.get('key_concepts', 'Key Concepts'))
            concept_text = "\n".join([
                f"• {concept} ({frequency:.2f})" 
                for concept, frequency in analysis['key_concepts']
            ])
            st.markdown(concept_text)
        
        # Columna 2: Gráfico de conceptos
        with col2:
            st.subheader(semantic_t.get('concept_graph', 'Concepts Graph'))
            st.image(analysis['concept_graph'])
    
    # Tab 2: Entidades
    with tab2:
        col1, col2 = st.columns(2)
        
        # Columna 1: Lista de entidades
        with col1:
            st.subheader(semantic_t.get('identified_entities', 'Identified Entities'))
            if 'entities' in analysis:
                for entity_type, entities in analysis['entities'].items():
                    st.markdown(f"**{entity_type}**")
                    st.markdown("• " + "\n• ".join(entities))
        
        # Columna 2: Gráfico de entidades
        with col2:
            st.subheader(semantic_t.get('entity_graph', 'Entities Graph'))
            st.image(analysis['entity_graph'])

    # Botón de exportación al final
    col1, col2, col3 = st.columns([2,1,2])
    with col2:
        if st.button(
            semantic_t.get('export_button', 'Export Analysis'), 
            key=f"semantic_export_{st.session_state.semantic_analysis_counter}",
            use_container_width=True
        ):
            pdf_buffer = export_user_interactions(st.session_state.username, 'semantic')
            st.download_button(
                label=semantic_t.get('download_pdf', 'Download PDF'),
                data=pdf_buffer,
                file_name="semantic_analysis.pdf",
                mime="application/pdf",
                key=f"semantic_download_{st.session_state.semantic_analysis_counter}"
            )