Spaces:
Running
Running
# modules/discourse/discourse/discourse_live_interface.py | |
import streamlit as st | |
from streamlit_float import * | |
from streamlit_antd_components import * | |
import pandas as pd | |
import logging | |
import io | |
import matplotlib.pyplot as plt | |
# Configuración del logger | |
logger = logging.getLogger(__name__) | |
# Importaciones locales | |
from .discourse_process import perform_discourse_analysis | |
from .discourse_interface import display_discourse_results # Añadida esta importación | |
from ..utils.widget_utils import generate_unique_key | |
from ..database.discourse_mongo_db import store_student_discourse_result | |
from ..database.chat_mongo_db import store_chat_history, get_chat_history | |
##################################################################################################### | |
def fig_to_bytes(fig): | |
"""Convierte una figura de matplotlib a bytes.""" | |
try: | |
buf = io.BytesIO() | |
fig.savefig(buf, format='png', dpi=300, bbox_inches='tight') | |
buf.seek(0) | |
return buf.getvalue() | |
except Exception as e: | |
logger.error(f"Error en fig_to_bytes: {str(e)}") | |
return None | |
################################################################################################# | |
def display_discourse_live_interface(lang_code, nlp_models, discourse_t): | |
""" | |
Interfaz para el análisis del discurso en vivo | |
""" | |
try: | |
# [Código anterior igual hasta el análisis] | |
if analyze_button and text_input1 and text_input2: | |
try: | |
with st.spinner(discourse_t.get('processing', 'Procesando...')): | |
# Realizar análisis | |
result = perform_discourse_analysis( | |
text_input1, | |
text_input2, | |
nlp_models[lang_code], | |
lang_code | |
) | |
if result['success']: | |
# Asegurarnos de que ambos gráficos se procesen correctamente | |
for graph_key in ['graph1', 'graph2']: | |
if graph_key in result and result[graph_key] is not None: | |
bytes_key = f'{graph_key}_bytes' | |
graph_bytes = fig_to_bytes(result[graph_key]) | |
if graph_bytes: | |
result[bytes_key] = graph_bytes | |
plt.close(result[graph_key]) # Cerrar la figura después de convertirla | |
st.session_state.discourse_live_state['last_result'] = result | |
st.session_state.discourse_live_state['analysis_count'] += 1 | |
st.session_state.discourse_live_state['text_changed'] = False | |
# Guardar en base de datos | |
store_result = store_student_discourse_result( | |
st.session_state.username, | |
text_input1, | |
text_input2, | |
result | |
) | |
if not store_result: | |
logger.warning("No se pudo guardar el análisis en la base de datos") | |
else: | |
st.error(result.get('message', 'Error en el análisis')) | |
except Exception as e: | |
logger.error(f"Error en análisis: {str(e)}") | |
st.error(discourse_t.get('error_processing', f'Error al procesar el texto: {str(e)}')) | |
# Columna derecha: Visualización de resultados | |
with result_col: | |
st.subheader(discourse_t.get('live_results', 'Resultados en vivo')) | |
if 'last_result' in st.session_state.discourse_live_state and \ | |
st.session_state.discourse_live_state['last_result'] is not None: | |
result = st.session_state.discourse_live_state['last_result'] | |
# Verificar que tenemos ambos gráficos antes de mostrarlos | |
if all(key in result for key in ['graph1', 'graph2', 'graph1_bytes', 'graph2_bytes']): | |
display_discourse_results(result, lang_code, discourse_t) | |
else: | |
logger.error(f"Faltan gráficos en el resultado: {list(result.keys())}") | |
st.error(discourse_t.get('missing_graphs', 'Error: No se pudieron generar todos los gráficos')) | |
elif st.session_state.discourse_live_state.get('text_changed', False): | |
st.info(discourse_t.get('changes_pending', | |
'Los textos han cambiado. Presione Analizar para ver los nuevos resultados.')) | |
else: | |
st.info(discourse_t.get('initial_message', | |
'Ingrese los textos y presione Analizar para ver los resultados.')) | |
except Exception as e: | |
logger.error(f"Error general en interfaz del discurso en vivo: {str(e)}") | |
st.error(discourse_t.get('general_error', "Se produjo un error. Por favor, intente de nuevo.")) |