# 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_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__) #################################### TEXT_TYPES = { 'academic_article': { 'name': 'Artículo Académico', 'thresholds': { 'vocabulary': {'min': 0.70, 'target': 0.85}, 'structure': {'min': 0.75, 'target': 0.90}, 'cohesion': {'min': 0.65, 'target': 0.80}, 'clarity': {'min': 0.70, 'target': 0.85} } }, 'student_essay': { 'name': 'Trabajo Universitario', 'thresholds': { 'vocabulary': {'min': 0.60, 'target': 0.75}, 'structure': {'min': 0.65, 'target': 0.80}, 'cohesion': {'min': 0.55, 'target': 0.70}, 'clarity': {'min': 0.60, 'target': 0.75} } }, 'general_communication': { 'name': 'Comunicación General', 'thresholds': { 'vocabulary': {'min': 0.50, 'target': 0.65}, 'structure': {'min': 0.55, 'target': 0.70}, 'cohesion': {'min': 0.45, 'target': 0.60}, 'clarity': {'min': 0.50, 'target': 0.65} } } } #################################### def display_current_situation_interface(lang_code, nlp_models, current_situation_t): """ Interfaz simplificada con gráfico de radar para visualizar métricas. """ # Inicializar estados si no existen if 'text_input' not in st.session_state: st.session_state.text_input = "" if 'text_area' not in st.session_state: # Añadir inicialización de text_area st.session_state.text_area = "" 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 try: # Container principal con dos columnas with st.container(): input_col, results_col = st.columns([1,2]) with input_col: # Text area con manejo de estado text_input = st.text_area( current_situation_t['input_prompt'], # Corregido: usar corchetes height=400, key="text_area", value=st.session_state.text_input, help=current_situation_t.get('help', '') # Manejar clave faltante ) # Función para manejar cambios de texto if text_input != st.session_state.text_input: st.session_state.text_input = text_input st.session_state.show_results = False if st.button( current_situation_t['analyze_button'], # Corregido: usar corchetes type="primary", disabled=not text_input.strip(), use_container_width=True, ): try: with st.spinner(current_situation_t['processing']): # Corregido: usar corchetes 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 except Exception as e: logger.error(f"Error en análisis: {str(e)}") st.error(current_situation_t.get('analysis_error', 'Error analyzing text')) # Manejar clave faltante # Mostrar resultados en la columna derecha with results_col: if st.session_state.show_results and st.session_state.current_metrics is not None: # Primero los radio buttons para tipo de texto st.markdown(f"### {current_situation_t['text_type_header']}") # Corregido: usar corchetes text_type = st.radio( "", options=list(TEXT_TYPES.keys()), format_func=lambda x: TEXT_TYPES[x]['name'], horizontal=True, key="text_type_radio", help=current_situation_t.get('text_type_help', '') # Manejar clave faltante ) st.session_state.current_text_type = text_type # Luego mostrar los resultados display_results( metrics=st.session_state.current_metrics, text_type=text_type, current_situation_t=current_situation_t ) except Exception as e: logger.error(f"Error en interfaz principal: {str(e)}") st.error(current_situation_t.get('error_interface', 'Interface error')) # Manejar clave faltante # ... (El resto del archivo mantiene las mismas correcciones con corchetes y get()) ###################################### def display_radar_chart(metrics_config, thresholds, current_situation_t): """ Muestra el gráfico radar con los resultados. """ try: # Preparar datos para el gráfico categories = [m['label'] for m in metrics_config] values_user = [m['value'] for m in metrics_config] min_values = [m['thresholds']['min'] for m in metrics_config] target_values = [m['thresholds']['target'] for m in metrics_config] # Crear y configurar gráfico fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(111, projection='polar') # Configurar radar angles = [n / float(len(categories)) * 2 * np.pi for n in range(len(categories))] angles += angles[:1] values_user += values_user[:1] min_values += min_values[:1] target_values += target_values[:1] # Configurar ejes ax.set_xticks(angles[:-1]) ax.set_xticklabels(categories, fontsize=10) 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) # Dibujar áreas de umbrales ax.plot(angles, min_values, '#e74c3c', linestyle='--', linewidth=1, label='Mínimo', alpha=0.5) ax.plot(angles, target_values, '#2ecc71', linestyle='--', linewidth=1, label='Meta', alpha=0.5) ax.fill_between(angles, target_values, [1]*len(angles), color='#2ecc71', alpha=0.1) ax.fill_between(angles, [0]*len(angles), min_values, color='#e74c3c', alpha=0.1) # Dibujar valores del usuario ax.plot(angles, values_user, '#3498db', linewidth=2, label='Tu escritura') ax.fill(angles, values_user, '#3498db', alpha=0.2) # Ajustar leyenda ax.legend( loc='upper right', bbox_to_anchor=(1.3, 1.1), fontsize=10, frameon=True, facecolor='white', edgecolor='none', shadow=True ) plt.tight_layout() st.pyplot(fig) plt.close() except Exception as e: logger.error(f"Error mostrando gráfico radar: {str(e)}") st.error(current_situation_t['error_chart']) #######################################