|
|
|
|
|
import streamlit as st |
|
import pandas as pd |
|
import plotly.graph_objects as go |
|
import logging |
|
from ..utils.widget_utils import generate_unique_key |
|
from .discourse_process import perform_discourse_analysis |
|
from ..database.chat_mongo_db import store_chat_history |
|
from ..database.discourse_mongo_db import store_student_discourse_result |
|
|
|
logger = logging.getLogger(__name__) |
|
|
|
def display_discourse_interface(lang_code, nlp_models, discourse_t): |
|
""" |
|
Interfaz para el análisis del discurso |
|
Args: |
|
lang_code: Código del idioma actual |
|
nlp_models: Modelos de spaCy cargados |
|
discourse_t: Diccionario de traducciones |
|
""" |
|
try: |
|
|
|
if 'discourse_state' not in st.session_state: |
|
st.session_state.discourse_state = { |
|
'analysis_count': 0, |
|
'last_analysis': None, |
|
'current_files': None |
|
} |
|
|
|
|
|
st.subheader(discourse_t.get('discourse_title', 'Análisis del Discurso')) |
|
st.info(discourse_t.get('initial_instruction', |
|
'Cargue dos archivos de texto para realizar un análisis comparativo del discurso.')) |
|
|
|
|
|
col1, col2 = st.columns(2) |
|
with col1: |
|
st.markdown(discourse_t.get('file1_label', "**Documento 1 (Patrón)**")) |
|
uploaded_file1 = st.file_uploader( |
|
discourse_t.get('file_uploader1', "Cargar archivo 1"), |
|
type=['txt'], |
|
key=f"discourse_file1_{st.session_state.discourse_state['analysis_count']}" |
|
) |
|
|
|
with col2: |
|
st.markdown(discourse_t.get('file2_label', "**Documento 2 (Comparación)**")) |
|
uploaded_file2 = st.file_uploader( |
|
discourse_t.get('file_uploader2', "Cargar archivo 2"), |
|
type=['txt'], |
|
key=f"discourse_file2_{st.session_state.discourse_state['analysis_count']}" |
|
) |
|
|
|
|
|
col1, col2, col3 = st.columns([1,2,1]) |
|
with col1: |
|
analyze_button = st.button( |
|
discourse_t.get('discourse_analyze_button', 'Analizar Discurso'), |
|
key=generate_unique_key("discourse", "analyze_button"), |
|
type="primary", |
|
icon="🔍", |
|
disabled=not (uploaded_file1 and uploaded_file2), |
|
use_container_width=True |
|
) |
|
|
|
|
|
if analyze_button and uploaded_file1 and uploaded_file2: |
|
try: |
|
with st.spinner(discourse_t.get('processing', 'Procesando análisis...')): |
|
|
|
text1 = uploaded_file1.getvalue().decode('utf-8') |
|
text2 = uploaded_file2.getvalue().decode('utf-8') |
|
|
|
|
|
result = perform_discourse_analysis( |
|
text1, |
|
text2, |
|
nlp_models[lang_code], |
|
lang_code |
|
) |
|
|
|
if result['success']: |
|
|
|
st.session_state.discourse_result = result |
|
st.session_state.discourse_state['analysis_count'] += 1 |
|
st.session_state.discourse_state['current_files'] = ( |
|
uploaded_file1.name, |
|
uploaded_file2.name |
|
) |
|
|
|
|
|
if store_student_discourse_result( |
|
st.session_state.username, |
|
text1, |
|
text2, |
|
result |
|
): |
|
st.success(discourse_t.get('success_message', 'Análisis guardado correctamente')) |
|
|
|
|
|
display_discourse_results(result, lang_code, discourse_t) |
|
else: |
|
st.error(discourse_t.get('error_message', 'Error al guardar el análisis')) |
|
else: |
|
st.error(discourse_t.get('analysis_error', 'Error en el análisis')) |
|
|
|
except Exception as e: |
|
logger.error(f"Error en análisis del discurso: {str(e)}") |
|
st.error(discourse_t.get('error_processing', f'Error procesando archivos: {str(e)}')) |
|
|
|
|
|
elif 'discourse_result' in st.session_state and st.session_state.discourse_result is not None: |
|
if st.session_state.discourse_state.get('current_files'): |
|
st.info( |
|
discourse_t.get('current_analysis_message', 'Mostrando análisis de los archivos: {} y {}') |
|
.format(*st.session_state.discourse_state['current_files']) |
|
) |
|
display_discourse_results( |
|
st.session_state.discourse_result, |
|
lang_code, |
|
discourse_t |
|
) |
|
|
|
except Exception as e: |
|
logger.error(f"Error general en interfaz del discurso: {str(e)}") |
|
st.error(discourse_t.get('general_error', 'Se produjo un error. Por favor, intente de nuevo.')) |
|
|
|
|
|
|
|
|
|
|
|
def display_discourse_results(result, lang_code, discourse_t): |
|
""" |
|
Muestra los resultados del análisis del discurso |
|
""" |
|
if not result.get('success'): |
|
st.warning(discourse_t.get('no_results', 'No hay resultados disponibles')) |
|
return |
|
|
|
|
|
st.markdown(""" |
|
<style> |
|
.concepts-container { |
|
display: flex; |
|
flex-wrap: nowrap; |
|
gap: 8px; |
|
padding: 12px; |
|
background-color: #f8f9fa; |
|
border-radius: 8px; |
|
overflow-x: auto; |
|
margin-bottom: 15px; |
|
white-space: nowrap; |
|
} |
|
.concept-item { |
|
background-color: white; |
|
border-radius: 4px; |
|
padding: 6px 10px; |
|
display: inline-flex; |
|
align-items: center; |
|
gap: 4px; |
|
box-shadow: 0 1px 2px rgba(0,0,0,0.1); |
|
flex-shrink: 0; |
|
} |
|
.concept-name { |
|
font-weight: 500; |
|
color: #1f2937; |
|
font-size: 0.85em; |
|
} |
|
.concept-freq { |
|
color: #6b7280; |
|
font-size: 0.75em; |
|
} |
|
.graph-container { |
|
background-color: white; |
|
padding: 15px; |
|
border-radius: 8px; |
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1); |
|
margin-top: 10px; |
|
} |
|
</style> |
|
""", unsafe_allow_html=True) |
|
|
|
col1, col2 = st.columns(2) |
|
|
|
|
|
with col1: |
|
st.subheader(discourse_t.get('doc1_title', 'Documento 1')) |
|
st.markdown(discourse_t.get('key_concepts', 'Conceptos Clave')) |
|
if 'key_concepts1' in result: |
|
concepts_html = f""" |
|
<div class="concepts-container"> |
|
{''.join([ |
|
f'<div class="concept-item"><span class="concept-name">{concept}</span>' |
|
f'<span class="concept-freq">({freq:.2f})</span></div>' |
|
for concept, freq in result['key_concepts1'] |
|
])} |
|
</div> |
|
""" |
|
st.markdown(concepts_html, unsafe_allow_html=True) |
|
|
|
if 'graph1' in result: |
|
st.markdown('<div class="graph-container">', unsafe_allow_html=True) |
|
st.pyplot(result['graph1']) |
|
|
|
|
|
button_col1, spacer_col1 = st.columns([1,4]) |
|
with button_col1: |
|
if 'graph1_bytes' in result: |
|
st.download_button( |
|
label="📥 " + discourse_t.get('download_graph', "Download"), |
|
data=result['graph1_bytes'], |
|
file_name="discourse_graph1.png", |
|
mime="image/png", |
|
use_container_width=True |
|
) |
|
|
|
|
|
st.markdown("**📊 Interpretación del grafo:**") |
|
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 |
|
""") |
|
|
|
st.markdown('</div>', unsafe_allow_html=True) |
|
else: |
|
st.warning(discourse_t.get('graph_not_available', 'Gráfico no disponible')) |
|
else: |
|
st.warning(discourse_t.get('concepts_not_available', 'Conceptos no disponibles')) |
|
|
|
|
|
with col2: |
|
st.subheader(discourse_t.get('doc2_title', 'Documento 2')) |
|
st.markdown(discourse_t.get('key_concepts', 'Conceptos Clave')) |
|
if 'key_concepts2' in result: |
|
concepts_html = f""" |
|
<div class="concepts-container"> |
|
{''.join([ |
|
f'<div class="concept-item"><span class="concept-name">{concept}</span>' |
|
f'<span class="concept-freq">({freq:.2f})</span></div>' |
|
for concept, freq in result['key_concepts2'] |
|
])} |
|
</div> |
|
""" |
|
st.markdown(concepts_html, unsafe_allow_html=True) |
|
|
|
if 'graph2' in result: |
|
st.markdown('<div class="graph-container">', unsafe_allow_html=True) |
|
st.pyplot(result['graph2']) |
|
|
|
|
|
button_col2, spacer_col2 = st.columns([1,4]) |
|
with button_col2: |
|
if 'graph2_bytes' in result: |
|
st.download_button( |
|
label="📥 " + discourse_t.get('download_graph', "Download"), |
|
data=result['graph2_bytes'], |
|
file_name="discourse_graph2.png", |
|
mime="image/png", |
|
use_container_width=True |
|
) |
|
|
|
|
|
st.markdown("**📊 Interpretación del grafo:**") |
|
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 |
|
""") |
|
|
|
st.markdown('</div>', unsafe_allow_html=True) |
|
else: |
|
st.warning(discourse_t.get('graph_not_available', 'Gráfico no disponible')) |
|
else: |
|
st.warning(discourse_t.get('concepts_not_available', 'Conceptos no disponibles')) |
|
|
|
|
|
st.info(discourse_t.get('comparison_note', |
|
'La funcionalidad de comparación detallada estará disponible en una próxima actualización.')) |