File size: 10,871 Bytes
58e05a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67201f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58e05a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67201f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58e05a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# modules/studentact/current_situation_interface.py

import streamlit as st
import logging
from ..utils.widget_utils import generate_unique_key
import matplotlib.pyplot as plt
import numpy as np
from ..database.current_situation_mongo_db import store_current_situation_result

from .current_situation_analysis import (
    analyze_text_dimensions, 
    analyze_clarity,
    analyze_reference_clarity,
    analyze_vocabulary_diversity, 
    analyze_cohesion,
    analyze_structure,
    get_dependency_depths, 
    normalize_score, 
    generate_sentence_graphs, 
    generate_word_connections, 
    generate_connection_paths,
    create_vocabulary_network, 
    create_syntax_complexity_graph, 
    create_cohesion_heatmap,     
)

# Configuraci贸n del estilo de matplotlib para el gr谩fico de radar
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['axes.grid'] = True
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.right'] = False

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

def display_current_situation_interface(lang_code, nlp_models, t):
    """
    Interfaz simplificada con gr谩fico de radar para visualizar m茅tricas.
    """
    try:
        # Inicializar estados si no existen
        if 'text_input' not in st.session_state:
            st.session_state.text_input = ""
        if 'show_results' not in st.session_state:
            st.session_state.show_results = False
        if 'current_doc' not in st.session_state:
            st.session_state.current_doc = None
        if 'current_metrics' not in st.session_state:
            st.session_state.current_metrics = None

        # Estilos CSS para mejorar la presentaci贸n
        st.markdown("""
            <style>
                .main-title {
                    margin-bottom: 2rem;
                }
                .stTextArea textarea {
                    border-radius: 0.5rem;
                }
                div[data-testid="column"] {
                    background-color: transparent;
                }
                .metric-container {
                    background-color: #f8f9fa;
                    padding: 1rem;
                    border-radius: 0.5rem;
                    margin-bottom: 1rem;
                }
            </style>
        """, unsafe_allow_html=True)

        st.markdown('<h2 class="main-title">An谩lisis Inicial de Escritura</h2>', unsafe_allow_html=True)
        
        # Container principal con dos columnas
        with st.container():
            input_col, results_col = st.columns([1,2])
            
            with input_col:
                # Funci贸n para manejar cambios en el texto
                def on_text_change():
                    st.session_state.text_input = st.session_state.text_area
                    st.session_state.show_results = False
                
                # Text area con manejo de estado
                text_input = st.text_area(
                    t.get('input_prompt', "Escribe o pega tu texto aqu铆:"),
                    height=400,
                    key="text_area",
                    value=st.session_state.text_input,
                    on_change=on_text_change,
                    help="Este texto ser谩 analizado para darte recomendaciones personalizadas"
                )
                
                if st.button(
                    t.get('analyze_button', "Analizar mi escritura"),
                    type="primary",
                    disabled=not text_input.strip(),
                    use_container_width=True,
                ):
                    try:
                        with st.spinner(t.get('processing', "Analizando...")):
                            doc = nlp_models[lang_code](text_input)
                            metrics = analyze_text_dimensions(doc)
                            
                            # Guardar en MongoDB
                            storage_success = store_current_situation_result(
                                username=st.session_state.username,
                                text=text_input,
                                metrics=metrics,
                                feedback=None
                            )
                            
                            if not storage_success:
                                logger.warning("No se pudo guardar el an谩lisis en la base de datos")
                            
                            st.session_state.current_doc = doc
                            st.session_state.current_metrics = metrics
                            st.session_state.show_results = True
                            st.session_state.text_input = text_input
                            
                    except Exception as e:
                        logger.error(f"Error en an谩lisis: {str(e)}")
                        st.error(t.get('analysis_error', "Error al analizar el texto"))
            
            # Mostrar resultados en la columna derecha
            with results_col:
                if st.session_state.show_results and st.session_state.current_metrics is not None:
                    # Container para los resultados
                    with st.container():
                        st.markdown('<div class="metric-container">', unsafe_allow_html=True)
                        
                        # Crear columnas para las m茅tricas con espaciado uniforme
                        c1, c2, c3, c4 = st.columns([1.2, 1.2, 1.2, 1.2])
                        
                        with c1:
                            st.metric(
                                "Vocabulario",
                                f"{st.session_state.current_metrics['vocabulary']['normalized_score']:.2f}",
                                "Meta: 1.00",
                                delta_color="off",
                                help="Riqueza y variedad del vocabulario utilizado"
                            )
                        with c2:
                            st.metric(
                                "Estructura",
                                f"{st.session_state.current_metrics['structure']['normalized_score']:.2f}",
                                "Meta: 1.00",
                                delta_color="off",
                                help="Organizaci贸n y complejidad de las oraciones"
                            )
                        with c3:
                            st.metric(
                                "Cohesi贸n",
                                f"{st.session_state.current_metrics['cohesion']['normalized_score']:.2f}",
                                "Meta: 1.00",
                                delta_color="off",
                                help="Conexi贸n y fluidez entre ideas"
                            )
                        with c4:
                            st.metric(
                                "Claridad",
                                f"{st.session_state.current_metrics['clarity']['normalized_score']:.2f}",
                                "Meta: 1.00",
                                delta_color="off",
                                help="Facilidad de comprensi贸n del texto"
                            )
                        
                        st.markdown('</div>', unsafe_allow_html=True)
                        
                        # Mostrar el gr谩fico de radar
                        display_radar_chart(st.session_state.current_metrics)

    except Exception as e:
        logger.error(f"Error en interfaz: {str(e)}")
        st.error("Ocurri贸 un error. Por favor, intente de nuevo.")

def display_radar_chart(metrics):
    """
    Muestra un gr谩fico de radar con las m茅tricas del usuario y el patr贸n ideal.
    """
    try:
        # Container con proporci贸n reducida
        with st.container():
            # M茅tricas en la parte superior
            col1, col2, col3, col4 = st.columns(4)
            with col1:
                st.metric("Vocabulario", f"{metrics['vocabulary']['normalized_score']:.2f}", "1.00")
            with col2:
                st.metric("Estructura", f"{metrics['structure']['normalized_score']:.2f}", "1.00")
            with col3:
                st.metric("Cohesi贸n", f"{metrics['cohesion']['normalized_score']:.2f}", "1.00")
            with col4:
                st.metric("Claridad", f"{metrics['clarity']['normalized_score']:.2f}", "1.00")

            # Contenedor para el gr谩fico con ancho controlado
            _, graph_col, _ = st.columns([1,2,1])
            
            with graph_col:
                # Preparar datos
                categories = ['Vocabulario', 'Estructura', 'Cohesi贸n', 'Claridad']
                values_user = [
                    metrics['vocabulary']['normalized_score'],
                    metrics['structure']['normalized_score'],
                    metrics['cohesion']['normalized_score'],
                    metrics['clarity']['normalized_score']
                ]
                values_pattern = [1.0, 1.0, 1.0, 1.0]  # Patr贸n ideal

                # Crear figura m谩s compacta
                fig = plt.figure(figsize=(6, 6))
                ax = fig.add_subplot(111, projection='polar')

                # N煤mero de variables
                num_vars = len(categories)

                # Calcular 谩ngulos
                angles = [n / float(num_vars) * 2 * np.pi for n in range(num_vars)]
                angles += angles[:1]

                # Extender valores para cerrar pol铆gonos
                values_user += values_user[:1]
                values_pattern += values_pattern[:1]

                # Configurar ejes y etiquetas
                ax.set_xticks(angles[:-1])
                ax.set_xticklabels(categories, fontsize=8)

                # C铆rculos conc茅ntricos y etiquetas
                circle_ticks = np.arange(0, 1.1, 0.2)  # Reducido a 5 niveles
                ax.set_yticks(circle_ticks)
                ax.set_yticklabels([f'{tick:.1f}' for tick in circle_ticks], fontsize=8)
                ax.set_ylim(0, 1)

                # Dibujar patr贸n ideal
                ax.plot(angles, values_pattern, 'g--', linewidth=1, label='Patr贸n', alpha=0.5)
                ax.fill(angles, values_pattern, 'g', alpha=0.1)

                # Dibujar valores del usuario
                ax.plot(angles, values_user, 'b-', linewidth=2, label='Tu escritura')
                ax.fill(angles, values_user, 'b', alpha=0.2)

                # Leyenda
                ax.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1), fontsize=8)

                # Ajustes finales
                plt.tight_layout()
                st.pyplot(fig)
                plt.close()

    except Exception as e:
        logger.error(f"Error generando gr谩fico de radar: {str(e)}")
        st.error("Error al generar la visualizaci贸n")