Update modules/discourse/discourse_interface.py
Browse files- modules/discourse/discourse_interface.py +176 -125
modules/discourse/discourse_interface.py
CHANGED
@@ -1,125 +1,176 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
from ..
|
8 |
-
from
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
if
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
#
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
'''
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modules/discourse/discourse/discourse_interface.py
|
2 |
+
|
3 |
+
import streamlit as st
|
4 |
+
import pandas as pd
|
5 |
+
import plotly.graph_objects as go
|
6 |
+
import logging
|
7 |
+
from ..utils.widget_utils import generate_unique_key
|
8 |
+
from .discourse_process import perform_discourse_analysis
|
9 |
+
from ..database.discourse_mongo_db import store_discourse_analysis_result
|
10 |
+
|
11 |
+
logger = logging.getLogger(__name__)
|
12 |
+
|
13 |
+
def display_discourse_interface(lang_code, nlp_models, discourse_t):
|
14 |
+
"""
|
15 |
+
Interfaz para el análisis del discurso
|
16 |
+
Args:
|
17 |
+
lang_code: Código del idioma actual
|
18 |
+
nlp_models: Modelos de spaCy cargados
|
19 |
+
discourse_t: Diccionario de traducciones
|
20 |
+
"""
|
21 |
+
try:
|
22 |
+
# 1. Inicializar estado si no existe
|
23 |
+
if 'discourse_state' not in st.session_state:
|
24 |
+
st.session_state.discourse_state = {
|
25 |
+
'analysis_count': 0,
|
26 |
+
'last_analysis': None,
|
27 |
+
'current_files': None
|
28 |
+
}
|
29 |
+
|
30 |
+
# 2. Título y descripción
|
31 |
+
st.subheader(discourse_t.get('discourse_title', 'Análisis del Discurso'))
|
32 |
+
st.info(discourse_t.get('initial_instruction',
|
33 |
+
'Cargue dos archivos de texto para realizar un análisis comparativo del discurso.'))
|
34 |
+
|
35 |
+
# 3. Área de carga de archivos
|
36 |
+
col1, col2 = st.columns(2)
|
37 |
+
with col1:
|
38 |
+
st.markdown(discourse_t.get('file1_label', "**Documento 1 (Patrón)**"))
|
39 |
+
uploaded_file1 = st.file_uploader(
|
40 |
+
discourse_t.get('file_uploader1', "Cargar archivo 1"),
|
41 |
+
type=['txt'],
|
42 |
+
key=f"discourse_file1_{st.session_state.discourse_state['analysis_count']}"
|
43 |
+
)
|
44 |
+
|
45 |
+
with col2:
|
46 |
+
st.markdown(discourse_t.get('file2_label', "**Documento 2 (Comparación)**"))
|
47 |
+
uploaded_file2 = st.file_uploader(
|
48 |
+
discourse_t.get('file_uploader2', "Cargar archivo 2"),
|
49 |
+
type=['txt'],
|
50 |
+
key=f"discourse_file2_{st.session_state.discourse_state['analysis_count']}"
|
51 |
+
)
|
52 |
+
|
53 |
+
# 4. Botón de análisis
|
54 |
+
col1, col2, col3 = st.columns([1,2,1])
|
55 |
+
with col2:
|
56 |
+
analyze_button = st.button(
|
57 |
+
discourse_t.get('analyze_button', 'Analizar Discurso'),
|
58 |
+
key=generate_unique_key("discourse", "analyze_button"),
|
59 |
+
type="primary",
|
60 |
+
icon="🔍",
|
61 |
+
disabled=not (uploaded_file1 and uploaded_file2),
|
62 |
+
use_container_width=True
|
63 |
+
)
|
64 |
+
|
65 |
+
# 5. Proceso de análisis
|
66 |
+
if analyze_button and uploaded_file1 and uploaded_file2:
|
67 |
+
try:
|
68 |
+
with st.spinner(discourse_t.get('processing', 'Procesando análisis...')):
|
69 |
+
# Leer contenido de archivos
|
70 |
+
text1 = uploaded_file1.getvalue().decode('utf-8')
|
71 |
+
text2 = uploaded_file2.getvalue().decode('utf-8')
|
72 |
+
|
73 |
+
# Realizar análisis
|
74 |
+
result = perform_discourse_analysis(
|
75 |
+
text1,
|
76 |
+
text2,
|
77 |
+
nlp_models[lang_code],
|
78 |
+
lang_code
|
79 |
+
)
|
80 |
+
|
81 |
+
if result['success']:
|
82 |
+
# Guardar estado
|
83 |
+
st.session_state.discourse_result = result
|
84 |
+
st.session_state.discourse_state['analysis_count'] += 1
|
85 |
+
st.session_state.discourse_state['current_files'] = (
|
86 |
+
uploaded_file1.name,
|
87 |
+
uploaded_file2.name
|
88 |
+
)
|
89 |
+
|
90 |
+
# Guardar en base de datos
|
91 |
+
if store_discourse_analysis_result(
|
92 |
+
st.session_state.username,
|
93 |
+
text1,
|
94 |
+
text2,
|
95 |
+
result
|
96 |
+
):
|
97 |
+
st.success(discourse_t.get('success_message', 'Análisis guardado correctamente'))
|
98 |
+
|
99 |
+
# Mostrar resultados
|
100 |
+
display_discourse_results(result, lang_code, discourse_t)
|
101 |
+
else:
|
102 |
+
st.error(discourse_t.get('error_message', 'Error al guardar el análisis'))
|
103 |
+
else:
|
104 |
+
st.error(discourse_t.get('analysis_error', 'Error en el análisis'))
|
105 |
+
|
106 |
+
except Exception as e:
|
107 |
+
logger.error(f"Error en análisis del discurso: {str(e)}")
|
108 |
+
st.error(discourse_t.get('error_processing', f'Error procesando archivos: {str(e)}'))
|
109 |
+
|
110 |
+
# 6. Mostrar resultados previos
|
111 |
+
elif 'discourse_result' in st.session_state and st.session_state.discourse_result is not None:
|
112 |
+
if st.session_state.discourse_state.get('current_files'):
|
113 |
+
st.info(
|
114 |
+
discourse_t.get('current_analysis_message', 'Mostrando análisis de los archivos: {} y {}')
|
115 |
+
.format(*st.session_state.discourse_state['current_files'])
|
116 |
+
)
|
117 |
+
display_discourse_results(
|
118 |
+
st.session_state.discourse_result,
|
119 |
+
lang_code,
|
120 |
+
discourse_t
|
121 |
+
)
|
122 |
+
|
123 |
+
except Exception as e:
|
124 |
+
logger.error(f"Error general en interfaz del discurso: {str(e)}")
|
125 |
+
st.error(discourse_t.get('general_error', 'Se produjo un error. Por favor, intente de nuevo.'))
|
126 |
+
|
127 |
+
def display_discourse_results(result, lang_code, discourse_t):
|
128 |
+
"""
|
129 |
+
Muestra los resultados del análisis del discurso
|
130 |
+
"""
|
131 |
+
if not result.get('success'):
|
132 |
+
st.warning(discourse_t.get('no_results', 'No hay resultados disponibles'))
|
133 |
+
return
|
134 |
+
|
135 |
+
col1, col2 = st.columns(2)
|
136 |
+
|
137 |
+
# Documento 1
|
138 |
+
with col1:
|
139 |
+
with st.expander(discourse_t.get('doc1_title', 'Documento 1'), expanded=True):
|
140 |
+
st.subheader(discourse_t.get('key_concepts', 'Conceptos Clave'))
|
141 |
+
if 'key_concepts1' in result:
|
142 |
+
df1 = pd.DataFrame(result['key_concepts1'], columns=['Concepto', 'Frecuencia'])
|
143 |
+
df1['Frecuencia'] = df1['Frecuencia'].round(2)
|
144 |
+
st.table(df1)
|
145 |
+
|
146 |
+
if 'graph1' in result:
|
147 |
+
st.pyplot(result['graph1'])
|
148 |
+
else:
|
149 |
+
st.warning(discourse_t.get('graph_not_available', 'Gráfico no disponible'))
|
150 |
+
else:
|
151 |
+
st.warning(discourse_t.get('concepts_not_available', 'Conceptos no disponibles'))
|
152 |
+
|
153 |
+
# Documento 2
|
154 |
+
with col2:
|
155 |
+
with st.expander(discourse_t.get('doc2_title', 'Documento 2'), expanded=True):
|
156 |
+
st.subheader(discourse_t.get('key_concepts', 'Conceptos Clave'))
|
157 |
+
if 'key_concepts2' in result:
|
158 |
+
df2 = pd.DataFrame(result['key_concepts2'], columns=['Concepto', 'Frecuencia'])
|
159 |
+
df2['Frecuencia'] = df2['Frecuencia'].round(2)
|
160 |
+
st.table(df2)
|
161 |
+
|
162 |
+
if 'graph2' in result:
|
163 |
+
st.pyplot(result['graph2'])
|
164 |
+
else:
|
165 |
+
st.warning(discourse_t.get('graph_not_available', 'Gráfico no disponible'))
|
166 |
+
else:
|
167 |
+
st.warning(discourse_t.get('concepts_not_available', 'Conceptos no disponibles'))
|
168 |
+
|
169 |
+
# Comparación de conceptos
|
170 |
+
if 'key_concepts1' in result and 'key_concepts2' in result:
|
171 |
+
st.subheader(discourse_t.get('comparison_title', 'Comparación de Conceptos'))
|
172 |
+
try:
|
173 |
+
plot_concept_comparison(result, discourse_t)
|
174 |
+
except Exception as e:
|
175 |
+
logger.error(f"Error en visualización de comparación: {str(e)}")
|
176 |
+
st.warning(discourse_t.get('comparison_error', 'Error al generar la comparación'))
|