File size: 6,146 Bytes
c7330d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19de296
c7330d5
 
c67983b
 
 
3f98e79
 
 
 
 
 
 
 
dd52ef3
df3c320
dd52ef3
 
df3c320
 
 
 
dd52ef3
df3c320
 
 
 
 
 
 
 
 
c67983b
dd52ef3
df3c320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c67983b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd52ef3
c67983b
 
 
 
 
 
 
df3c320
 
c67983b
 
 
 
 
 
dd52ef3
c67983b
 
 
 
 
 
8aeac38
 
dd52ef3
 
 
 
 
 
 
c67983b
dd52ef3
 
 
 
3f98e79
df3c320
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
#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
    Args:
        lang_code: C贸digo del idioma actual
        nlp_models: Modelos de spaCy cargados
        semantic_t: Diccionario de traducciones sem谩nticas
    """
    try:
        # Inicializar estados si no existen
        if 'semantic_analysis_counter' not in st.session_state:
            st.session_state.semantic_analysis_counter = 0
        if 'semantic_current_file' not in st.session_state:
            st.session_state.semantic_current_file = None
        if 'semantic_page' not in st.session_state:
            st.session_state.semantic_page = 'semantic'

        # Contenedor fijo para los controles
        with st.container():
            st.markdown("### Controls")
            # Opci贸n para cargar archivo con key 煤nica
            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: setattr(st.session_state, 'semantic_current_file', uploaded_file)
            )

            # Bot贸n de an谩lisis deshabilitado si no hay archivo
            col1, col2, col3 = st.columns([1,2,1])
            with col1:
                analyze_button = st.button(
                    semantic_t.get('analyze_button', 'Analyze text'),
                    key=f"semantic_analyze_button_{st.session_state.semantic_analysis_counter}",
                    disabled=not uploaded_file,
                    use_container_width=True
                )

                # Bot贸n de exportaci贸n solo visible si hay resultados
                if 'semantic_result' in st.session_state and st.session_state.semantic_result is not None:
                    export_button = st.button(
                        semantic_t.get('export_button', 'Export Analysis'),
                        key=f"semantic_export_{st.session_state.semantic_analysis_counter}",
                        use_container_width=True
                    )
                    if export_button:
                        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}"
                        )

        st.markdown("---")  # Separador

        # Procesar el an谩lisis cuando se presiona el bot贸n
        if analyze_button and uploaded_file is not None:
            try:
                with st.spinner(semantic_t.get('processing', 'Processing...')):
                    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']:
                        st.session_state.semantic_result = analysis_result
                        st.session_state.semantic_analysis_counter += 1
                        
                        # Guardar en la base de datos
                        if store_student_semantic_result(
                            st.session_state.username,
                            text_content,
                            analysis_result['analysis']
                        ):
                            st.success(semantic_t.get('success_message', 'Analysis saved successfully'))
                            # Asegurar que nos mantenemos en la p谩gina sem谩ntica
                            st.session_state.page = 'semantic'
                            # 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)}'))
        
        # Mostrar resultados previos
        elif 'semantic_result' in st.session_state and st.session_state.semantic_result is not None:
            display_semantic_results(
                st.session_state.semantic_result,
                lang_code,
                semantic_t
            )
        else:
            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.")

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