Update modules/semantic/semantic_interface.py
Browse files
modules/semantic/semantic_interface.py
CHANGED
@@ -1,27 +1,4 @@
|
|
1 |
-
#modules/semantic/semantic_interface.py
|
2 |
-
import streamlit as st
|
3 |
-
from streamlit_float import *
|
4 |
-
from streamlit_antd_components import *
|
5 |
-
from streamlit.components.v1 import html
|
6 |
-
import io
|
7 |
-
from io import BytesIO
|
8 |
-
import base64
|
9 |
-
import matplotlib.pyplot as plt
|
10 |
-
import pandas as pd
|
11 |
-
import re
|
12 |
-
|
13 |
-
from .semantic_process import (
|
14 |
-
process_semantic_input,
|
15 |
-
format_semantic_results
|
16 |
-
)
|
17 |
-
|
18 |
-
from ..utils.widget_utils import generate_unique_key
|
19 |
-
from ..database.semantic_mongo_db import store_student_semantic_result
|
20 |
-
from ..database.semantic_export import export_user_interactions
|
21 |
-
|
22 |
-
import logging
|
23 |
-
logger = logging.getLogger(__name__)
|
24 |
-
|
25 |
def display_semantic_interface(lang_code, nlp_models, semantic_t):
|
26 |
"""
|
27 |
Interfaz para el análisis semántico
|
@@ -36,40 +13,37 @@ def display_semantic_interface(lang_code, nlp_models, semantic_t):
|
|
36 |
if input_key not in st.session_state:
|
37 |
st.session_state[input_key] = ""
|
38 |
|
39 |
-
# Inicializar contador de análisis si no existe
|
40 |
if 'semantic_analysis_counter' not in st.session_state:
|
41 |
st.session_state.semantic_analysis_counter = 0
|
42 |
|
43 |
-
# Campo de entrada de texto
|
44 |
text_input = st.text_area(
|
45 |
semantic_t.get('text_input_label', 'Enter text to analyze'),
|
46 |
height=150,
|
47 |
placeholder=semantic_t.get('text_input_placeholder', 'Enter your text here...'),
|
48 |
value=st.session_state[input_key],
|
49 |
-
key=
|
50 |
)
|
51 |
|
52 |
-
# Opción para cargar archivo
|
53 |
uploaded_file = st.file_uploader(
|
54 |
semantic_t.get('file_uploader', 'Or upload a text file'),
|
55 |
type=['txt'],
|
56 |
-
key=
|
57 |
)
|
58 |
|
59 |
-
# Botón de análisis
|
60 |
analyze_button = st.button(
|
61 |
semantic_t.get('analyze_button', 'Analyze text'),
|
62 |
-
key=
|
63 |
)
|
64 |
|
65 |
if analyze_button:
|
66 |
if text_input or uploaded_file is not None:
|
67 |
try:
|
68 |
with st.spinner(semantic_t.get('processing', 'Processing...')):
|
69 |
-
# Obtener el texto a analizar
|
70 |
text_content = uploaded_file.getvalue().decode('utf-8') if uploaded_file else text_input
|
71 |
|
72 |
-
# Realizar el análisis
|
73 |
analysis_result = process_semantic_input(
|
74 |
text_content,
|
75 |
lang_code,
|
@@ -78,36 +52,33 @@ def display_semantic_interface(lang_code, nlp_models, semantic_t):
|
|
78 |
)
|
79 |
|
80 |
if analysis_result['success']:
|
81 |
-
# Guardar resultado en el estado de la sesión
|
82 |
st.session_state.semantic_result = analysis_result
|
83 |
st.session_state.semantic_analysis_counter += 1
|
84 |
|
85 |
-
#
|
86 |
-
display_semantic_results(
|
87 |
-
analysis_result,
|
88 |
-
lang_code,
|
89 |
-
semantic_t
|
90 |
-
)
|
91 |
-
|
92 |
-
# Guardar en la base de datos
|
93 |
if store_student_semantic_result(
|
94 |
st.session_state.username,
|
95 |
text_content,
|
96 |
analysis_result['analysis']
|
97 |
):
|
98 |
st.success(semantic_t.get('success_message', 'Analysis saved successfully'))
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
else:
|
100 |
st.error(semantic_t.get('error_message', 'Error saving analysis'))
|
101 |
else:
|
102 |
st.error(analysis_result['message'])
|
103 |
-
|
104 |
except Exception as e:
|
105 |
logger.error(f"Error en análisis semántico: {str(e)}")
|
106 |
st.error(semantic_t.get('error_processing', f'Error processing text: {str(e)}'))
|
107 |
else:
|
108 |
st.warning(semantic_t.get('warning_message', 'Please enter text or upload a file'))
|
109 |
-
|
110 |
-
#
|
111 |
elif 'semantic_result' in st.session_state and st.session_state.semantic_result is not None:
|
112 |
display_semantic_results(
|
113 |
st.session_state.semantic_result,
|
@@ -124,10 +95,6 @@ def display_semantic_interface(lang_code, nlp_models, semantic_t):
|
|
124 |
def display_semantic_results(result, lang_code, semantic_t):
|
125 |
"""
|
126 |
Muestra los resultados del análisis semántico
|
127 |
-
Args:
|
128 |
-
result: Resultados del análisis
|
129 |
-
lang_code: Código del idioma
|
130 |
-
semantic_t: Diccionario de traducciones
|
131 |
"""
|
132 |
if result is None or not result['success']:
|
133 |
st.warning(semantic_t.get('no_results', 'No results available'))
|
@@ -136,11 +103,7 @@ def display_semantic_results(result, lang_code, semantic_t):
|
|
136 |
analysis = result['analysis']
|
137 |
|
138 |
# Mostrar conceptos clave
|
139 |
-
with st.expander(
|
140 |
-
semantic_t.get('key_concepts', 'Key Concepts'),
|
141 |
-
expanded=True,
|
142 |
-
key=generate_unique_key("semantic", "key_concepts_expander")
|
143 |
-
):
|
144 |
concept_text = " | ".join([
|
145 |
f"{concept} ({frequency:.2f})"
|
146 |
for concept, frequency in analysis['key_concepts']
|
@@ -148,42 +111,28 @@ def display_semantic_results(result, lang_code, semantic_t):
|
|
148 |
st.write(concept_text)
|
149 |
|
150 |
# Mostrar gráfico de relaciones conceptuales
|
151 |
-
with st.expander(
|
152 |
-
semantic_t.get('conceptual_relations', 'Conceptual Relations'),
|
153 |
-
expanded=True,
|
154 |
-
key=generate_unique_key("semantic", "concept_graph_expander")
|
155 |
-
):
|
156 |
st.image(analysis['concept_graph'])
|
157 |
|
158 |
# Mostrar gráfico de entidades
|
159 |
-
with st.expander(
|
160 |
-
semantic_t.get('entity_relations', 'Entity Relations'),
|
161 |
-
expanded=True,
|
162 |
-
key=generate_unique_key("semantic", "entity_graph_expander")
|
163 |
-
):
|
164 |
st.image(analysis['entity_graph'])
|
165 |
|
166 |
# Mostrar entidades identificadas
|
167 |
if 'entities' in analysis:
|
168 |
-
with st.expander(
|
169 |
-
semantic_t.get('identified_entities', 'Identified Entities'),
|
170 |
-
expanded=True,
|
171 |
-
key=generate_unique_key("semantic", "entities_expander")
|
172 |
-
):
|
173 |
for entity_type, entities in analysis['entities'].items():
|
174 |
st.subheader(entity_type)
|
175 |
st.write(", ".join(entities))
|
176 |
|
177 |
# Botón de exportación
|
178 |
-
if st.button(
|
179 |
-
|
180 |
-
key=generate_unique_key("semantic", "export_button")
|
181 |
-
):
|
182 |
pdf_buffer = export_user_interactions(st.session_state.username, 'semantic')
|
183 |
st.download_button(
|
184 |
label=semantic_t.get('download_pdf', 'Download PDF'),
|
185 |
data=pdf_buffer,
|
186 |
file_name="semantic_analysis.pdf",
|
187 |
mime="application/pdf",
|
188 |
-
key=
|
189 |
)
|
|
|
1 |
+
# modules/semantic/semantic_interface.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
def display_semantic_interface(lang_code, nlp_models, semantic_t):
|
3 |
"""
|
4 |
Interfaz para el análisis semántico
|
|
|
13 |
if input_key not in st.session_state:
|
14 |
st.session_state[input_key] = ""
|
15 |
|
|
|
16 |
if 'semantic_analysis_counter' not in st.session_state:
|
17 |
st.session_state.semantic_analysis_counter = 0
|
18 |
|
19 |
+
# Campo de entrada de texto con key única
|
20 |
text_input = st.text_area(
|
21 |
semantic_t.get('text_input_label', 'Enter text to analyze'),
|
22 |
height=150,
|
23 |
placeholder=semantic_t.get('text_input_placeholder', 'Enter your text here...'),
|
24 |
value=st.session_state[input_key],
|
25 |
+
key=f"semantic_text_area_{st.session_state.semantic_analysis_counter}"
|
26 |
)
|
27 |
|
28 |
+
# Opción para cargar archivo con key única
|
29 |
uploaded_file = st.file_uploader(
|
30 |
semantic_t.get('file_uploader', 'Or upload a text file'),
|
31 |
type=['txt'],
|
32 |
+
key=f"semantic_file_uploader_{st.session_state.semantic_analysis_counter}"
|
33 |
)
|
34 |
|
35 |
+
# Botón de análisis con key única
|
36 |
analyze_button = st.button(
|
37 |
semantic_t.get('analyze_button', 'Analyze text'),
|
38 |
+
key=f"semantic_analyze_button_{st.session_state.semantic_analysis_counter}"
|
39 |
)
|
40 |
|
41 |
if analyze_button:
|
42 |
if text_input or uploaded_file is not None:
|
43 |
try:
|
44 |
with st.spinner(semantic_t.get('processing', 'Processing...')):
|
|
|
45 |
text_content = uploaded_file.getvalue().decode('utf-8') if uploaded_file else text_input
|
46 |
|
|
|
47 |
analysis_result = process_semantic_input(
|
48 |
text_content,
|
49 |
lang_code,
|
|
|
52 |
)
|
53 |
|
54 |
if analysis_result['success']:
|
|
|
55 |
st.session_state.semantic_result = analysis_result
|
56 |
st.session_state.semantic_analysis_counter += 1
|
57 |
|
58 |
+
# Guardar en la base de datos antes de mostrar resultados
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
if store_student_semantic_result(
|
60 |
st.session_state.username,
|
61 |
text_content,
|
62 |
analysis_result['analysis']
|
63 |
):
|
64 |
st.success(semantic_t.get('success_message', 'Analysis saved successfully'))
|
65 |
+
# Mostrar resultados
|
66 |
+
display_semantic_results(
|
67 |
+
analysis_result,
|
68 |
+
lang_code,
|
69 |
+
semantic_t
|
70 |
+
)
|
71 |
else:
|
72 |
st.error(semantic_t.get('error_message', 'Error saving analysis'))
|
73 |
else:
|
74 |
st.error(analysis_result['message'])
|
|
|
75 |
except Exception as e:
|
76 |
logger.error(f"Error en análisis semántico: {str(e)}")
|
77 |
st.error(semantic_t.get('error_processing', f'Error processing text: {str(e)}'))
|
78 |
else:
|
79 |
st.warning(semantic_t.get('warning_message', 'Please enter text or upload a file'))
|
80 |
+
|
81 |
+
# Mostrar resultados previos
|
82 |
elif 'semantic_result' in st.session_state and st.session_state.semantic_result is not None:
|
83 |
display_semantic_results(
|
84 |
st.session_state.semantic_result,
|
|
|
95 |
def display_semantic_results(result, lang_code, semantic_t):
|
96 |
"""
|
97 |
Muestra los resultados del análisis semántico
|
|
|
|
|
|
|
|
|
98 |
"""
|
99 |
if result is None or not result['success']:
|
100 |
st.warning(semantic_t.get('no_results', 'No results available'))
|
|
|
103 |
analysis = result['analysis']
|
104 |
|
105 |
# Mostrar conceptos clave
|
106 |
+
with st.expander(semantic_t.get('key_concepts', 'Key Concepts'), expanded=True):
|
|
|
|
|
|
|
|
|
107 |
concept_text = " | ".join([
|
108 |
f"{concept} ({frequency:.2f})"
|
109 |
for concept, frequency in analysis['key_concepts']
|
|
|
111 |
st.write(concept_text)
|
112 |
|
113 |
# Mostrar gráfico de relaciones conceptuales
|
114 |
+
with st.expander(semantic_t.get('conceptual_relations', 'Conceptual Relations'), expanded=True):
|
|
|
|
|
|
|
|
|
115 |
st.image(analysis['concept_graph'])
|
116 |
|
117 |
# Mostrar gráfico de entidades
|
118 |
+
with st.expander(semantic_t.get('entity_relations', 'Entity Relations'), expanded=True):
|
|
|
|
|
|
|
|
|
119 |
st.image(analysis['entity_graph'])
|
120 |
|
121 |
# Mostrar entidades identificadas
|
122 |
if 'entities' in analysis:
|
123 |
+
with st.expander(semantic_t.get('identified_entities', 'Identified Entities'), expanded=True):
|
|
|
|
|
|
|
|
|
124 |
for entity_type, entities in analysis['entities'].items():
|
125 |
st.subheader(entity_type)
|
126 |
st.write(", ".join(entities))
|
127 |
|
128 |
# Botón de exportación
|
129 |
+
if st.button(semantic_t.get('export_button', 'Export Analysis'),
|
130 |
+
key=f"semantic_export_{st.session_state.semantic_analysis_counter}"):
|
|
|
|
|
131 |
pdf_buffer = export_user_interactions(st.session_state.username, 'semantic')
|
132 |
st.download_button(
|
133 |
label=semantic_t.get('download_pdf', 'Download PDF'),
|
134 |
data=pdf_buffer,
|
135 |
file_name="semantic_analysis.pdf",
|
136 |
mime="application/pdf",
|
137 |
+
key=f"semantic_download_{st.session_state.semantic_analysis_counter}"
|
138 |
)
|