Spaces:
Running
Running
#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.chat_mongo_db import store_chat_history, get_chat_history | |
# 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 el estado de la sesi贸n | |
if 'semantic_state' not in st.session_state: | |
st.session_state.semantic_state = { | |
'analysis_count': 0, | |
'last_analysis': None, | |
'current_file': None | |
} | |
# 2. 脕rea de carga de archivo con mensaje informativo | |
st.info(semantic_t.get('initial_instruction', | |
'Para comenzar un nuevo an谩lisis sem谩ntico, cargue un archivo de texto (.txt)')) | |
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_state['analysis_count']}" | |
) | |
# 3. Columnas para los botones y mensajes | |
col1, col2 = st.columns([1,4]) | |
# 4. Bot贸n de an谩lisis | |
with col1: | |
analyze_button = st.button( | |
semantic_t.get('semantic_analyze_button', 'Analyze'), | |
key=f"semantic_analyze_button_{st.session_state.semantic_state['analysis_count']}", | |
type="primary", # Nuevo en Streamlit 1.39.0 | |
icon="馃攳", # Nuevo en Streamlit 1.39.0 | |
disabled=uploaded_file is None, | |
use_container_width=True | |
) | |
# 5. Procesar an谩lisis | |
if analyze_button and uploaded_file is not None: | |
try: | |
with st.spinner(semantic_t.get('processing', 'Processing...')): | |
# Leer contenido del archivo | |
text_content = uploaded_file.getvalue().decode('utf-8') | |
# Realizar an谩lisis | |
analysis_result = process_semantic_input( | |
text_content, | |
lang_code, | |
nlp_models, | |
semantic_t | |
) | |
if analysis_result['success']: | |
# Guardar resultado | |
st.session_state.semantic_result = analysis_result | |
st.session_state.semantic_state['analysis_count'] += 1 | |
st.session_state.semantic_state['current_file'] = uploaded_file.name | |
# Guardar en base de datos | |
if store_student_semantic_result( | |
st.session_state.username, | |
text_content, | |
analysis_result['analysis'] | |
): | |
st.success( | |
semantic_t.get('analysis_complete', | |
'An谩lisis completado y guardado. Para realizar un nuevo an谩lisis, cargue otro archivo.') | |
) | |
# Mostrar resultados | |
display_semantic_results( | |
st.session_state.semantic_result, | |
lang_code, | |
semantic_t | |
) | |
else: | |
st.error(semantic_t.get('error_message', 'Error saving analysis')) | |
else: | |
st.error(analysis_result['message']) | |
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)}')) | |
# 6. Mostrar resultados previos o mensaje inicial | |
elif 'semantic_result' in st.session_state and st.session_state.semantic_result is not None: | |
# Mostrar mensaje sobre el an谩lisis actual | |
st.info( | |
semantic_t.get('current_analysis_message', | |
f'Mostrando an谩lisis del archivo: {st.session_state.semantic_state["current_file"]}. ' | |
'Para realizar un nuevo an谩lisis, cargue otro archivo.') | |
) | |
display_semantic_results( | |
st.session_state.semantic_result, | |
lang_code, | |
semantic_t | |
) | |
else: | |
st.info(semantic_t.get('upload_prompt', 'Cargue un archivo para comenzar el an谩lisis')) | |
except Exception as e: | |
logger.error(f"Error general en interfaz sem谩ntica: {str(e)}") | |
st.error(semantic_t.get('general_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 de conceptos clave. | |
""" | |
# Verificar resultado | |
if semantic_result is None or not semantic_result['success']: | |
st.warning(semantic_t.get('no_results', 'No results available')) | |
return | |
analysis = semantic_result['analysis'] | |
# Crear contenedor para los resultados con proporciones ajustadas | |
col1, col2 = st.columns([1, 2]) | |
# Columna 1: Lista de conceptos clave | |
with col1: | |
st.subheader(semantic_t.get('key_concepts', 'Key Concepts')) | |
if 'key_concepts' in analysis and analysis['key_concepts']: | |
# Crear tabla de conceptos | |
df = pd.DataFrame( | |
analysis['key_concepts'], | |
columns=[ | |
semantic_t.get('concept', 'Concept'), | |
semantic_t.get('frequency', 'Frequency') | |
] | |
) | |
st.dataframe( | |
df, | |
hide_index=True, | |
column_config={ | |
semantic_t.get('frequency', 'Frequency'): st.column_config.NumberColumn( | |
format="%.2f" | |
) | |
}, | |
height=400 | |
) | |
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 and analysis['concept_graph'] is not None: | |
try: | |
# Configurar el estilo de la visualizaci贸n | |
st.markdown( | |
""" | |
<style> | |
.semantic-graph-container { | |
background-color: white; | |
border-radius: 10px; | |
padding: 20px; | |
box-shadow: 0 2px 4px rgba(0,0,0,0.1); | |
margin: 10px 0; | |
} | |
.stImage { | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
} | |
.stImage > img { | |
max-width: 100%; | |
height: auto; | |
object-fit: contain; | |
} | |
</style> | |
""", | |
unsafe_allow_html=True | |
) | |
# Crear contenedor para el grafo | |
with st.container(): | |
st.markdown('<div class="semantic-graph-container">', unsafe_allow_html=True) | |
# Convertir los bytes de la imagen a formato base64 | |
graph_bytes = analysis['concept_graph'] | |
graph_base64 = base64.b64encode(graph_bytes).decode() | |
# Mostrar la imagen con HTML para mayor control | |
st.markdown( | |
f'<img src="data:image/png;base64,{graph_base64}" alt="Concept Graph" style="width:100%;"/>', | |
unsafe_allow_html=True | |
) | |
# Agregar leyenda o descripci贸n si es necesario | |
st.caption(semantic_t.get( | |
'graph_description', | |
'El grosor de las l铆neas indica la fuerza de la relaci贸n. ' | |
'Los colores indican la centralidad del concepto.' | |
)) | |
st.markdown('</div>', unsafe_allow_html=True) | |
# Agregar bot贸n de descarga | |
st.download_button( | |
label=semantic_t.get('download_graph', "Download Graph"), | |
data=graph_bytes, | |
file_name="semantic_graph.png", | |
mime="image/png", | |
) | |
except Exception as e: | |
logger.error(f"Error displaying graph: {str(e)}") | |
st.error(semantic_t.get('graph_error', 'Error displaying the graph')) | |
else: | |
st.info(semantic_t.get('no_graph', 'No concept graph available')) | |
# A帽adir informaci贸n adicional sobre la interpretaci贸n del grafo | |
with st.expander(semantic_t.get('graph_help', "How to interpret this graph")): | |
st.markdown(""" | |
- Las flechas indican la direcci贸n de la relaci贸n entre conceptos | |
- Los colores m谩s intensos indican conceptos m谩s centrales en el texto | |
- El tama帽o de los nodos representa la frecuencia del concepto | |
- El grosor de las l铆neas indica la fuerza de la conexi贸n | |
""") | |
######################################################################################## | |
''' | |
# 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}" | |
) | |
''' |