#modules/semantic/semantic_interface.py import streamlit as st from streamlit_float import * from streamlit_antd_components import * from streamlit.components.v1 import html import spacy_streamlit 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 ############################### 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: # 1. Inicializar estados de sesión if 'semantic_analysis_counter' not in st.session_state: st.session_state.semantic_analysis_counter = 0 input_key = f"semantic_input_{lang_code}" if input_key not in st.session_state: st.session_state[input_key] = "" # 2. Configurar área de entrada (file uploader) uploaded_file = st.file_uploader( semantic_t.get('semantic_file_uploader', 'Upload a text file for semantic analysis'), type=['txt'], key=f"semantic_file_uploader_{st.session_state.semantic_analysis_counter}" ) # 3. Configurar botones de control col1, col2, col3 = st.columns([2,1,2]) with col1: analyze_button = st.button( semantic_t.get('semantic_analyze_button', 'Analyze Semantic'), key=f"semantic_analyze_button_{st.session_state.semantic_analysis_counter}", use_container_width=True ) # 4. Procesar análisis cuando se activa if analyze_button: if uploaded_file is None: st.warning(semantic_t.get('warning_message', 'Please upload a file first')) return try: with st.spinner(semantic_t.get('processing', 'Processing...')): # 4.1 Leer contenido del archivo text_content = uploaded_file.getvalue().decode('utf-8') # 4.2 Realizar análisis semántico analysis_result = process_semantic_input( text_content, lang_code, nlp_models, semantic_t ) if not analysis_result['success']: st.error(analysis_result['message']) return # 4.3 Guardar resultado en el estado de la sesión st.session_state.semantic_result = analysis_result # 4.4 Incrementar el contador de análisis st.session_state.semantic_analysis_counter += 1 # 4.5 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')) # 4.6 Mostrar resultados - CORREGIDO: removido analysis_result redundante display_semantic_results( st.session_state.semantic_result, lang_code, semantic_t ) else: st.error(semantic_t.get('error_message', 'Error saving analysis')) 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)}')) # 5. Mostrar resultados previos si existen 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 ) # 6. Mostrar mensaje inicial 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.") ####################################### def display_semantic_results(semantic_result, lang_code, semantic_t): """ Muestra los resultados del análisis semántico en tabs Args: semantic_result: Diccionario con los resultados del análisis lang_code: Código del idioma actual semantic_t: Diccionario de traducciones semánticas """ # Verificar resultado usando el nombre correcto de la variable if semantic_result is None or not semantic_result['success']: st.warning(semantic_t.get('no_results', 'No results available')) return # Usar semantic_result en lugar de result analysis = semantic_result['analysis'] # Crear tabs para los resultados tab1, tab2 = st.tabs([ semantic_t.get('concepts_tab', 'Key Concepts Analysis'), semantic_t.get('entities_tab', 'Entities Analysis') ]) # Tab 1: Conceptos Clave with tab1: col1, col2 = st.columns(2) # Columna 1: Lista de conceptos with col1: st.subheader(semantic_t.get('key_concepts', 'Key Concepts')) if 'key_concepts' in analysis: concept_text = "\n".join([ f"• {concept} ({frequency:.2f})" for concept, frequency in analysis['key_concepts'] ]) st.markdown(concept_text) else: st.info(semantic_t.get('no_concepts', 'No key concepts found')) # Columna 2: Gráfico de conceptos with col2: st.subheader(semantic_t.get('concept_graph', 'Concepts Graph')) if 'concept_graph' in analysis: st.image(analysis['concept_graph']) else: st.info(semantic_t.get('no_graph', 'No concept graph available')) # Tab 2: Entidades with tab2: col1, col2 = st.columns(2) # Columna 1: Lista de entidades with col1: st.subheader(semantic_t.get('identified_entities', 'Identified Entities')) if 'entities' in analysis: for entity_type, entities in analysis['entities'].items(): st.markdown(f"**{entity_type}**") st.markdown("• " + "\n• ".join(entities)) else: st.info(semantic_t.get('no_entities', 'No entities found')) # Columna 2: Gráfico de entidades with col2: st.subheader(semantic_t.get('entity_graph', 'Entities Graph')) if 'entity_graph' in analysis: st.image(analysis['entity_graph']) else: st.info(semantic_t.get('no_entity_graph', 'No entity graph available')) # Botón de exportación al final if 'semantic_analysis_counter' in st.session_state: col1, col2, col3 = st.columns([2,1,2]) with col2: if st.button( semantic_t.get('export_button', 'Export Analysis'), key=f"semantic_export_{st.session_state.semantic_analysis_counter}", use_container_width=True ): 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}" )