|
|
|
|
|
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, |
|
) |
|
|
|
|
|
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: |
|
|
|
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 |
|
|
|
st.markdown("## Análisis Inicial de Escritura") |
|
|
|
|
|
with st.container(): |
|
input_col, results_col = st.columns([1,2]) |
|
|
|
with input_col: |
|
|
|
def on_text_change(): |
|
st.session_state.text_input = st.session_state.text_area |
|
st.session_state.show_results = False |
|
|
|
|
|
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) |
|
|
|
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")) |
|
|
|
|
|
with results_col: |
|
if st.session_state.show_results and st.session_state.current_metrics is not None: |
|
display_results(st.session_state.current_metrics) |
|
|
|
def display_results(metrics): |
|
""" |
|
Muestra los resultados del análisis: métricas y gráfico radar. |
|
""" |
|
try: |
|
|
|
metric_cols = st.columns(4, gap="small", vertical_alignment="center", border=True) |
|
|
|
metrics_config = [ |
|
("Vocabulario", metrics['vocabulary']['normalized_score'], "Riqueza y variedad del vocabulario"), |
|
("Estructura", metrics['structure']['normalized_score'], "Organización y complejidad de oraciones"), |
|
("Cohesión", metrics['cohesion']['normalized_score'], "Conexión y fluidez entre ideas"), |
|
("Claridad", metrics['clarity']['normalized_score'], "Facilidad de comprensión del texto") |
|
] |
|
|
|
|
|
for i, (label, value, help_text) in enumerate(metrics_config): |
|
metric_cols[i].metric( |
|
label, |
|
f"{value:.2f}", |
|
"Meta: 1.00", |
|
delta_color="off", |
|
help=help_text |
|
) |
|
|
|
|
|
st.markdown("<div style='margin-top: 1rem;'></div>", unsafe_allow_html=True) |
|
|
|
|
|
left_space, graph_col, right_space = st.columns([1, 2, 1]) |
|
with graph_col: |
|
|
|
categories = [m[0] for m in metrics_config] |
|
values_user = [m[1] for m in metrics_config] |
|
values_pattern = [1.0] * len(categories) |
|
|
|
|
|
fig = plt.figure(figsize=(6, 6)) |
|
ax = fig.add_subplot(111, projection='polar') |
|
|
|
|
|
angles = [n / float(len(categories)) * 2 * np.pi for n in range(len(categories))] |
|
angles += angles[:1] |
|
values_user += values_user[:1] |
|
values_pattern += values_pattern[:1] |
|
|
|
|
|
ax.set_xticks(angles[:-1]) |
|
ax.set_xticklabels(categories, fontsize=8) |
|
circle_ticks = np.arange(0, 1.1, 0.2) |
|
ax.set_yticks(circle_ticks) |
|
ax.set_yticklabels([f'{tick:.1f}' for tick in circle_ticks], fontsize=8) |
|
ax.set_ylim(0, 1) |
|
|
|
|
|
ax.plot(angles, values_pattern, 'g--', linewidth=1, label='Patrón', alpha=0.5) |
|
ax.fill(angles, values_pattern, 'g', alpha=0.1) |
|
ax.plot(angles, values_user, 'b-', linewidth=2, label='Tu escritura') |
|
ax.fill(angles, values_user, 'b', alpha=0.2) |
|
ax.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1), fontsize=8) |
|
|
|
plt.tight_layout() |
|
st.pyplot(fig) |
|
plt.close() |
|
|
|
except Exception as e: |
|
logger.error(f"Error mostrando resultados: {str(e)}") |
|
st.error("Error al mostrar los resultados") |