AIdeaText commited on
Commit
664f529
verified
1 Parent(s): 9fbca90

Update modules/discourse/discourse_interface.py

Browse files
Files changed (1) hide show
  1. modules/discourse/discourse_interface.py +113 -111
modules/discourse/discourse_interface.py CHANGED
@@ -10,121 +10,123 @@ from ..database.chat_mongo_db import store_chat_history
10
  from ..database.discourse_mongo_db import store_student_discourse_result
11
 
12
  logger = logging.getLogger(__name__)
 
13
 
14
- def display_discourse_interface(lang_code, nlp_models, discourse_t):
15
  """
16
- Interfaz para el an谩lisis del discurso
17
- Args:
18
- lang_code: C贸digo del idioma actual
19
- nlp_models: Modelos de spaCy cargados
20
- discourse_t: Diccionario de traducciones
21
  """
22
- try:
23
- # 1. Inicializar estado si no existe
24
- if 'discourse_state' not in st.session_state:
25
- st.session_state.discourse_state = {
26
- 'analysis_count': 0,
27
- 'last_analysis': None,
28
- 'current_files': None
29
- }
30
-
31
- # 2. T铆tulo y descripci贸n
32
- st.subheader(discourse_t.get('discourse_title', 'An谩lisis del Discurso'))
33
- st.info(discourse_t.get('initial_instruction',
34
- 'Cargue dos archivos de texto para realizar un an谩lisis comparativo del discurso.'))
35
-
36
- # 3. 脕rea de carga de archivos
37
- col1, col2 = st.columns(2)
38
- with col1:
39
- st.markdown(discourse_t.get('file1_label', "**Documento 1 (Patr贸n)**"))
40
- uploaded_file1 = st.file_uploader(
41
- discourse_t.get('file_uploader1', "Cargar archivo 1"),
42
- type=['txt'],
43
- key=f"discourse_file1_{st.session_state.discourse_state['analysis_count']}"
44
- )
45
-
46
- with col2:
47
- st.markdown(discourse_t.get('file2_label', "**Documento 2 (Comparaci贸n)**"))
48
- uploaded_file2 = st.file_uploader(
49
- discourse_t.get('file_uploader2', "Cargar archivo 2"),
50
- type=['txt'],
51
- key=f"discourse_file2_{st.session_state.discourse_state['analysis_count']}"
52
- )
53
-
54
- # 4. Bot贸n de an谩lisis
55
- col1, col2, col3 = st.columns([1,2,1])
56
- with col1:
57
- analyze_button = st.button(
58
- discourse_t.get('discourse_analyze_button', 'Analizar Discurso'),
59
- key=generate_unique_key("discourse", "analyze_button"),
60
- type="primary",
61
- icon="馃攳",
62
- disabled=not (uploaded_file1 and uploaded_file2),
63
- use_container_width=True
64
- )
65
-
66
- # 5. Proceso de an谩lisis
67
- if analyze_button and uploaded_file1 and uploaded_file2:
68
- try:
69
- with st.spinner(discourse_t.get('processing', 'Procesando an谩lisis...')):
70
- # Leer contenido de archivos
71
- text1 = uploaded_file1.getvalue().decode('utf-8')
72
- text2 = uploaded_file2.getvalue().decode('utf-8')
73
-
74
- # Realizar an谩lisis
75
- result = perform_discourse_analysis(
76
- text1,
77
- text2,
78
- nlp_models[lang_code],
79
- lang_code
80
- )
81
-
82
- if result['success']:
83
- # Guardar estado
84
- st.session_state.discourse_result = result
85
- st.session_state.discourse_state['analysis_count'] += 1
86
- st.session_state.discourse_state['current_files'] = (
87
- uploaded_file1.name,
88
- uploaded_file2.name
89
- )
90
-
91
- # Guardar en base de datos
92
- if store_student_discourse_result(
93
- st.session_state.username,
94
- text1,
95
- text2,
96
- result
97
- ):
98
- st.success(discourse_t.get('success_message', 'An谩lisis guardado correctamente'))
99
-
100
- # Mostrar resultados
101
- display_discourse_results(result, lang_code, discourse_t)
102
- else:
103
- st.error(discourse_t.get('error_message', 'Error al guardar el an谩lisis'))
104
- else:
105
- st.error(discourse_t.get('analysis_error', 'Error en el an谩lisis'))
106
-
107
- except Exception as e:
108
- logger.error(f"Error en an谩lisis del discurso: {str(e)}")
109
- st.error(discourse_t.get('error_processing', f'Error procesando archivos: {str(e)}'))
110
-
111
- # 6. Mostrar resultados previos
112
- elif 'discourse_result' in st.session_state and st.session_state.discourse_result is not None:
113
- if st.session_state.discourse_state.get('current_files'):
114
- st.info(
115
- discourse_t.get('current_analysis_message', 'Mostrando an谩lisis de los archivos: {} y {}')
116
- .format(*st.session_state.discourse_state['current_files'])
117
- )
118
- display_discourse_results(
119
- st.session_state.discourse_result,
120
- lang_code,
121
- discourse_t
122
- )
123
-
124
- except Exception as e:
125
- logger.error(f"Error general en interfaz del discurso: {str(e)}")
126
- st.error(discourse_t.get('general_error', 'Se produjo un error. Por favor, intente de nuevo.'))
 
 
 
 
127
 
 
128
  def display_discourse_results(result, lang_code, discourse_t):
129
  """
130
  Muestra los resultados del an谩lisis del discurso
 
10
  from ..database.discourse_mongo_db import store_student_discourse_result
11
 
12
  logger = logging.getLogger(__name__)
13
+ #############################################################################################
14
 
15
+ def display_discourse_results(result, lang_code, discourse_t):
16
  """
17
+ Muestra los resultados del an谩lisis del discurso con conceptos en formato horizontal
 
 
 
 
18
  """
19
+ if not result.get('success'):
20
+ st.warning(discourse_t.get('no_results', 'No hay resultados disponibles'))
21
+ return
22
+
23
+ # Estilo CSS para los conceptos horizontales
24
+ st.markdown("""
25
+ <style>
26
+ .concepts-container {
27
+ display: flex;
28
+ flex-wrap: nowrap;
29
+ gap: 8px;
30
+ padding: 12px;
31
+ background-color: #f8f9fa;
32
+ border-radius: 8px;
33
+ overflow-x: auto;
34
+ margin-bottom: 15px;
35
+ }
36
+ .concept-item {
37
+ background-color: white;
38
+ border-radius: 4px;
39
+ padding: 6px 10px;
40
+ display: inline-flex;
41
+ align-items: center;
42
+ gap: 4px;
43
+ box-shadow: 0 1px 2px rgba(0,0,0,0.1);
44
+ flex-shrink: 0;
45
+ }
46
+ .concept-name {
47
+ font-weight: 500;
48
+ color: #1f2937;
49
+ font-size: 0.85em;
50
+ }
51
+ .concept-freq {
52
+ color: #6b7280;
53
+ font-size: 0.75em;
54
+ }
55
+ .graph-container {
56
+ background-color: white;
57
+ border-radius: 8px;
58
+ padding: 15px;
59
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
60
+ margin-top: 10px;
61
+ }
62
+ </style>
63
+ """, unsafe_allow_html=True)
64
+
65
+ col1, col2 = st.columns(2)
66
+
67
+ # Documento 1
68
+ with col1:
69
+ with st.expander(discourse_t.get('doc1_title', 'Documento 1'), expanded=True):
70
+ st.subheader(discourse_t.get('key_concepts', 'Conceptos Clave'))
71
+ if 'key_concepts1' in result:
72
+ # Crear HTML para conceptos horizontales
73
+ concepts_html = '<div class="concepts-container">'
74
+ for concept, freq in result['key_concepts1']:
75
+ concepts_html += f"""
76
+ <div class="concept-item">
77
+ <span class="concept-name">{concept}</span>
78
+ <span class="concept-freq">({freq:.2f})</span>
79
+ </div>
80
+ """
81
+ concepts_html += '</div>'
82
+ st.markdown(concepts_html, unsafe_allow_html=True)
83
+
84
+ if 'graph1' in result:
85
+ with st.container():
86
+ st.markdown('<div class="graph-container">', unsafe_allow_html=True)
87
+ st.pyplot(result['graph1'])
88
+ st.markdown('</div>', unsafe_allow_html=True)
89
+ else:
90
+ st.warning(discourse_t.get('graph_not_available', 'Gr谩fico no disponible'))
91
+ else:
92
+ st.warning(discourse_t.get('concepts_not_available', 'Conceptos no disponibles'))
93
+
94
+ # Documento 2
95
+ with col2:
96
+ with st.expander(discourse_t.get('doc2_title', 'Documento 2'), expanded=True):
97
+ st.subheader(discourse_t.get('key_concepts', 'Conceptos Clave'))
98
+ if 'key_concepts2' in result:
99
+ # Crear HTML para conceptos horizontales
100
+ concepts_html = '<div class="concepts-container">'
101
+ for concept, freq in result['key_concepts2']:
102
+ concepts_html += f"""
103
+ <div class="concept-item">
104
+ <span class="concept-name">{concept}</span>
105
+ <span class="concept-freq">({freq:.2f})</span>
106
+ </div>
107
+ """
108
+ concepts_html += '</div>'
109
+ st.markdown(concepts_html, unsafe_allow_html=True)
110
+
111
+ if 'graph2' in result:
112
+ with st.container():
113
+ st.markdown('<div class="graph-container">', unsafe_allow_html=True)
114
+ st.pyplot(result['graph2'])
115
+ st.markdown('</div>', unsafe_allow_html=True)
116
+ else:
117
+ st.warning(discourse_t.get('graph_not_available', 'Gr谩fico no disponible'))
118
+ else:
119
+ st.warning(discourse_t.get('concepts_not_available', 'Conceptos no disponibles'))
120
+
121
+ # Nota informativa sobre la comparaci贸n
122
+ st.info(discourse_t.get('comparison_note',
123
+ 'La funcionalidad de comparaci贸n detallada estar谩 disponible en una pr贸xima actualizaci贸n.'))
124
+
125
+
126
+
127
+
128
 
129
+ ##########################################################################################
130
  def display_discourse_results(result, lang_code, discourse_t):
131
  """
132
  Muestra los resultados del an谩lisis del discurso