Create current_situation_interface.py
Browse files
modules/studentact/current_situation_interface.py
ADDED
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modules/studentact/current_situation_interface.py
|
2 |
+
|
3 |
+
import streamlit as st
|
4 |
+
import logging
|
5 |
+
from ..utils.widget_utils import generate_unique_key
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
import numpy as np
|
8 |
+
from ..database.current_situation_mongo_db import store_current_situation_result
|
9 |
+
|
10 |
+
from .current_situation_analysis import (
|
11 |
+
analyze_text_dimensions,
|
12 |
+
analyze_clarity,
|
13 |
+
analyze_reference_clarity,
|
14 |
+
analyze_vocabulary_diversity,
|
15 |
+
analyze_cohesion,
|
16 |
+
analyze_structure,
|
17 |
+
get_dependency_depths,
|
18 |
+
normalize_score,
|
19 |
+
generate_sentence_graphs,
|
20 |
+
generate_word_connections,
|
21 |
+
generate_connection_paths,
|
22 |
+
create_vocabulary_network,
|
23 |
+
create_syntax_complexity_graph,
|
24 |
+
create_cohesion_heatmap,
|
25 |
+
)
|
26 |
+
|
27 |
+
# Configuraci贸n del estilo de matplotlib para el gr谩fico de radar
|
28 |
+
plt.rcParams['font.family'] = 'sans-serif'
|
29 |
+
plt.rcParams['axes.grid'] = True
|
30 |
+
plt.rcParams['axes.spines.top'] = False
|
31 |
+
plt.rcParams['axes.spines.right'] = False
|
32 |
+
|
33 |
+
logger = logging.getLogger(__name__)
|
34 |
+
####################################
|
35 |
+
|
36 |
+
def display_current_situation_interface(lang_code, nlp_models, t):
|
37 |
+
"""
|
38 |
+
Interfaz simplificada con gr谩fico de radar para visualizar m茅tricas.
|
39 |
+
"""
|
40 |
+
try:
|
41 |
+
# Inicializar estados si no existen
|
42 |
+
if 'text_input' not in st.session_state:
|
43 |
+
st.session_state.text_input = ""
|
44 |
+
if 'show_results' not in st.session_state:
|
45 |
+
st.session_state.show_results = False
|
46 |
+
if 'current_doc' not in st.session_state:
|
47 |
+
st.session_state.current_doc = None
|
48 |
+
if 'current_metrics' not in st.session_state:
|
49 |
+
st.session_state.current_metrics = None
|
50 |
+
|
51 |
+
st.markdown("## An谩lisis Inicial de Escritura")
|
52 |
+
|
53 |
+
# Container principal con dos columnas
|
54 |
+
with st.container():
|
55 |
+
input_col, results_col = st.columns([1,2])
|
56 |
+
|
57 |
+
with input_col:
|
58 |
+
#st.markdown("### Ingresa tu texto")
|
59 |
+
|
60 |
+
# Funci贸n para manejar cambios en el texto
|
61 |
+
def on_text_change():
|
62 |
+
st.session_state.text_input = st.session_state.text_area
|
63 |
+
st.session_state.show_results = False
|
64 |
+
|
65 |
+
# Text area con manejo de estado
|
66 |
+
text_input = st.text_area(
|
67 |
+
t.get('input_prompt', "Escribe o pega tu texto aqu铆:"),
|
68 |
+
height=400,
|
69 |
+
key="text_area",
|
70 |
+
value=st.session_state.text_input,
|
71 |
+
on_change=on_text_change,
|
72 |
+
help="Este texto ser谩 analizado para darte recomendaciones personalizadas"
|
73 |
+
)
|
74 |
+
|
75 |
+
if st.button(
|
76 |
+
t.get('analyze_button', "Analizar mi escritura"),
|
77 |
+
type="primary",
|
78 |
+
disabled=not text_input.strip(),
|
79 |
+
use_container_width=True,
|
80 |
+
):
|
81 |
+
try:
|
82 |
+
with st.spinner(t.get('processing', "Analizando...")):
|
83 |
+
doc = nlp_models[lang_code](text_input)
|
84 |
+
metrics = analyze_text_dimensions(doc)
|
85 |
+
|
86 |
+
# Guardar en MongoDB
|
87 |
+
storage_success = store_current_situation_result(
|
88 |
+
username=st.session_state.username,
|
89 |
+
text=text_input,
|
90 |
+
metrics=metrics,
|
91 |
+
feedback=None
|
92 |
+
)
|
93 |
+
|
94 |
+
if not storage_success:
|
95 |
+
logger.warning("No se pudo guardar el an谩lisis en la base de datos")
|
96 |
+
|
97 |
+
st.session_state.current_doc = doc
|
98 |
+
st.session_state.current_metrics = metrics
|
99 |
+
st.session_state.show_results = True
|
100 |
+
st.session_state.text_input = text_input
|
101 |
+
|
102 |
+
except Exception as e:
|
103 |
+
logger.error(f"Error en an谩lisis: {str(e)}")
|
104 |
+
st.error(t.get('analysis_error', "Error al analizar el texto"))
|
105 |
+
|
106 |
+
# Mostrar resultados en la columna derecha
|
107 |
+
with results_col:
|
108 |
+
if st.session_state.show_results and st.session_state.current_metrics is not None:
|
109 |
+
display_radar_chart(st.session_state.current_metrics)
|
110 |
+
|
111 |
+
except Exception as e:
|
112 |
+
logger.error(f"Error en interfaz: {str(e)}")
|
113 |
+
st.error("Ocurri贸 un error. Por favor, intente de nuevo.")
|
114 |
+
|
115 |
+
def display_radar_chart(metrics):
|
116 |
+
"""
|
117 |
+
Muestra un gr谩fico de radar con las m茅tricas del usuario y el patr贸n ideal.
|
118 |
+
"""
|
119 |
+
try:
|
120 |
+
# Container con proporci贸n reducida
|
121 |
+
with st.container():
|
122 |
+
# M茅tricas en la parte superior
|
123 |
+
col1, col2, col3, col4 = st.columns(4)
|
124 |
+
with col1:
|
125 |
+
st.metric("Vocabulario", f"{metrics['vocabulary']['normalized_score']:.2f}", "1.00")
|
126 |
+
with col2:
|
127 |
+
st.metric("Estructura", f"{metrics['structure']['normalized_score']:.2f}", "1.00")
|
128 |
+
with col3:
|
129 |
+
st.metric("Cohesi贸n", f"{metrics['cohesion']['normalized_score']:.2f}", "1.00")
|
130 |
+
with col4:
|
131 |
+
st.metric("Claridad", f"{metrics['clarity']['normalized_score']:.2f}", "1.00")
|
132 |
+
|
133 |
+
# Contenedor para el gr谩fico con ancho controlado
|
134 |
+
_, graph_col, _ = st.columns([1,2,1])
|
135 |
+
|
136 |
+
with graph_col:
|
137 |
+
# Preparar datos
|
138 |
+
categories = ['Vocabulario', 'Estructura', 'Cohesi贸n', 'Claridad']
|
139 |
+
values_user = [
|
140 |
+
metrics['vocabulary']['normalized_score'],
|
141 |
+
metrics['structure']['normalized_score'],
|
142 |
+
metrics['cohesion']['normalized_score'],
|
143 |
+
metrics['clarity']['normalized_score']
|
144 |
+
]
|
145 |
+
values_pattern = [1.0, 1.0, 1.0, 1.0] # Patr贸n ideal
|
146 |
+
|
147 |
+
# Crear figura m谩s compacta
|
148 |
+
fig = plt.figure(figsize=(6, 6))
|
149 |
+
ax = fig.add_subplot(111, projection='polar')
|
150 |
+
|
151 |
+
# N煤mero de variables
|
152 |
+
num_vars = len(categories)
|
153 |
+
|
154 |
+
# Calcular 谩ngulos
|
155 |
+
angles = [n / float(num_vars) * 2 * np.pi for n in range(num_vars)]
|
156 |
+
angles += angles[:1]
|
157 |
+
|
158 |
+
# Extender valores para cerrar pol铆gonos
|
159 |
+
values_user += values_user[:1]
|
160 |
+
values_pattern += values_pattern[:1]
|
161 |
+
|
162 |
+
# Configurar ejes y etiquetas
|
163 |
+
ax.set_xticks(angles[:-1])
|
164 |
+
ax.set_xticklabels(categories, fontsize=8)
|
165 |
+
|
166 |
+
# C铆rculos conc茅ntricos y etiquetas
|
167 |
+
circle_ticks = np.arange(0, 1.1, 0.2) # Reducido a 5 niveles
|
168 |
+
ax.set_yticks(circle_ticks)
|
169 |
+
ax.set_yticklabels([f'{tick:.1f}' for tick in circle_ticks], fontsize=8)
|
170 |
+
ax.set_ylim(0, 1)
|
171 |
+
|
172 |
+
# Dibujar patr贸n ideal
|
173 |
+
ax.plot(angles, values_pattern, 'g--', linewidth=1, label='Patr贸n', alpha=0.5)
|
174 |
+
ax.fill(angles, values_pattern, 'g', alpha=0.1)
|
175 |
+
|
176 |
+
# Dibujar valores del usuario
|
177 |
+
ax.plot(angles, values_user, 'b-', linewidth=2, label='Tu escritura')
|
178 |
+
ax.fill(angles, values_user, 'b', alpha=0.2)
|
179 |
+
|
180 |
+
# Leyenda
|
181 |
+
ax.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1), fontsize=8)
|
182 |
+
|
183 |
+
# Ajustes finales
|
184 |
+
plt.tight_layout()
|
185 |
+
st.pyplot(fig)
|
186 |
+
plt.close()
|
187 |
+
|
188 |
+
except Exception as e:
|
189 |
+
logger.error(f"Error generando gr谩fico de radar: {str(e)}")
|
190 |
+
st.error("Error al generar la visualizaci贸n")
|