Spaces:
Sleeping
Sleeping
Delete modules/semantic/semantic_interface.py
Browse files
modules/semantic/semantic_interface.py
DELETED
|
@@ -1,266 +0,0 @@
|
|
| 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 spacy_streamlit
|
| 7 |
-
import io
|
| 8 |
-
from io import BytesIO
|
| 9 |
-
import base64
|
| 10 |
-
import matplotlib.pyplot as plt
|
| 11 |
-
import pandas as pd
|
| 12 |
-
import re
|
| 13 |
-
import logging
|
| 14 |
-
|
| 15 |
-
# Configuración del logger
|
| 16 |
-
logger = logging.getLogger(__name__)
|
| 17 |
-
|
| 18 |
-
# Importaciones locales
|
| 19 |
-
from .semantic_process import (
|
| 20 |
-
process_semantic_input,
|
| 21 |
-
format_semantic_results
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
from ..utils.widget_utils import generate_unique_key
|
| 25 |
-
from ..database.semantic_mongo_db import store_student_semantic_result
|
| 26 |
-
from ..database.chat_mongo_db import store_chat_history, get_chat_history
|
| 27 |
-
|
| 28 |
-
# from ..database.semantic_export import export_user_interactions
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
###############################
|
| 32 |
-
|
| 33 |
-
# En semantic_interface.py
|
| 34 |
-
def display_semantic_interface(text, lang_code, nlp_models, t, semantic_t):
|
| 35 |
-
try:
|
| 36 |
-
# 1. Inicializar el estado de la sesión
|
| 37 |
-
if 'semantic_state' not in st.session_state:
|
| 38 |
-
st.session_state.semantic_state = {
|
| 39 |
-
'analysis_count': 0,
|
| 40 |
-
'last_analysis': None,
|
| 41 |
-
'current_file': None,
|
| 42 |
-
'pending_analysis': False # Nuevo flag para controlar el análisis pendiente
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
# 2. Área de carga de archivo con mensaje informativo
|
| 46 |
-
st.info(semantic_t.get('initial_instruction',
|
| 47 |
-
'Para comenzar un nuevo análisis semántico, cargue un archivo de texto (.txt)'))
|
| 48 |
-
|
| 49 |
-
uploaded_file = st.file_uploader(
|
| 50 |
-
semantic_t.get('semantic_file_uploader', 'Upload a text file for semantic analysis'),
|
| 51 |
-
type=['txt'],
|
| 52 |
-
key=f"semantic_file_uploader_{st.session_state.semantic_state['analysis_count']}"
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
# 2.1 Verificar si hay un archivo cargado y un análisis pendiente
|
| 56 |
-
if uploaded_file is not None and st.session_state.semantic_state.get('pending_analysis', False):
|
| 57 |
-
try:
|
| 58 |
-
with st.spinner(semantic_t.get('processing', 'Processing...')):
|
| 59 |
-
# Realizar análisis
|
| 60 |
-
text = uploaded_file.getvalue().decode('utf-8')
|
| 61 |
-
|
| 62 |
-
analysis_result = process_semantic_input(
|
| 63 |
-
text,
|
| 64 |
-
lang_code,
|
| 65 |
-
nlp_models,
|
| 66 |
-
t,
|
| 67 |
-
semantic_t
|
| 68 |
-
)
|
| 69 |
-
|
| 70 |
-
if analysis_result['success']:
|
| 71 |
-
# Guardar resultado
|
| 72 |
-
st.session_state.semantic_result = analysis_result
|
| 73 |
-
st.session_state.semantic_state['analysis_count'] += 1
|
| 74 |
-
st.session_state.semantic_state['current_file'] = uploaded_file.name
|
| 75 |
-
|
| 76 |
-
# Guardar en base de datos
|
| 77 |
-
storage_success = store_student_semantic_result(
|
| 78 |
-
st.session_state.username,
|
| 79 |
-
text_content,
|
| 80 |
-
analysis_result['analysis']
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
if storage_success:
|
| 84 |
-
st.success(
|
| 85 |
-
semantic_t.get('analysis_complete',
|
| 86 |
-
'Análisis completado y guardado. Para realizar un nuevo análisis, cargue otro archivo.')
|
| 87 |
-
)
|
| 88 |
-
else:
|
| 89 |
-
st.error(semantic_t.get('error_message', 'Error saving analysis'))
|
| 90 |
-
else:
|
| 91 |
-
st.error(analysis_result['message'])
|
| 92 |
-
|
| 93 |
-
# Restablecer el flag de análisis pendiente
|
| 94 |
-
st.session_state.semantic_state['pending_analysis'] = False
|
| 95 |
-
|
| 96 |
-
except Exception as e:
|
| 97 |
-
logger.error(f"Error en análisis semántico: {str(e)}")
|
| 98 |
-
st.error(semantic_t.get('error_processing', f'Error processing text: {str(e)}'))
|
| 99 |
-
# Restablecer el flag de análisis pendiente en caso de error
|
| 100 |
-
st.session_state.semantic_state['pending_analysis'] = False
|
| 101 |
-
|
| 102 |
-
# 3. Columnas para los botones y mensajes
|
| 103 |
-
col1, col2 = st.columns([1,4])
|
| 104 |
-
|
| 105 |
-
# 4. Botón de análisis
|
| 106 |
-
with col1:
|
| 107 |
-
analyze_button = st.button(
|
| 108 |
-
semantic_t.get('semantic_analyze_button', 'Analyze'),
|
| 109 |
-
key=f"semantic_analyze_button_{st.session_state.semantic_state['analysis_count']}",
|
| 110 |
-
type="primary",
|
| 111 |
-
icon="🔍",
|
| 112 |
-
disabled=uploaded_file is None,
|
| 113 |
-
use_container_width=True
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
# 5. Procesar análisis
|
| 117 |
-
if analyze_button and uploaded_file is not None:
|
| 118 |
-
# En lugar de realizar el análisis inmediatamente, establecer el flag
|
| 119 |
-
st.session_state.semantic_state['pending_analysis'] = True
|
| 120 |
-
# Forzar la recarga de la aplicación
|
| 121 |
-
st.rerun()
|
| 122 |
-
|
| 123 |
-
# 6. Mostrar resultados previos o mensaje inicial
|
| 124 |
-
elif 'semantic_result' in st.session_state and st.session_state.semantic_result is not None:
|
| 125 |
-
# Mostrar mensaje sobre el análisis actual
|
| 126 |
-
st.info(
|
| 127 |
-
semantic_t.get('current_analysis_message',
|
| 128 |
-
'Mostrando análisis del archivo: {}. Para realizar un nuevo análisis, cargue otro archivo.'
|
| 129 |
-
).format(st.session_state.semantic_state["current_file"])
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
display_semantic_results(
|
| 133 |
-
st.session_state.semantic_result,
|
| 134 |
-
lang_code,
|
| 135 |
-
semantic_t
|
| 136 |
-
)
|
| 137 |
-
else:
|
| 138 |
-
st.info(semantic_t.get('upload_prompt', 'Cargue un archivo para comenzar el análisis'))
|
| 139 |
-
|
| 140 |
-
except Exception as e:
|
| 141 |
-
logger.error(f"Error general en interfaz semántica: {str(e)}")
|
| 142 |
-
st.error(semantic_t.get('general_error', "Se produjo un error. Por favor, intente de nuevo."))
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
#######################################
|
| 146 |
-
def display_semantic_results(semantic_result, lang_code, semantic_t):
|
| 147 |
-
"""
|
| 148 |
-
Muestra los resultados del análisis semántico de conceptos clave.
|
| 149 |
-
"""
|
| 150 |
-
if semantic_result is None or not semantic_result['success']:
|
| 151 |
-
st.warning(semantic_t.get('no_results', 'No results available'))
|
| 152 |
-
return
|
| 153 |
-
|
| 154 |
-
analysis = semantic_result['analysis']
|
| 155 |
-
|
| 156 |
-
# Mostrar conceptos clave en formato horizontal
|
| 157 |
-
st.subheader(semantic_t.get('key_concepts', 'Key Concepts'))
|
| 158 |
-
|
| 159 |
-
if 'key_concepts' in analysis and analysis['key_concepts']:
|
| 160 |
-
# Crear tabla de conceptos
|
| 161 |
-
df = pd.DataFrame(
|
| 162 |
-
analysis['key_concepts'],
|
| 163 |
-
columns=[
|
| 164 |
-
semantic_t.get('concept', 'Concept'),
|
| 165 |
-
semantic_t.get('frequency', 'Frequency')
|
| 166 |
-
]
|
| 167 |
-
)
|
| 168 |
-
|
| 169 |
-
# Convertir DataFrame a formato horizontal
|
| 170 |
-
st.write(
|
| 171 |
-
"""
|
| 172 |
-
<style>
|
| 173 |
-
.concept-table {
|
| 174 |
-
display: flex;
|
| 175 |
-
flex-wrap: wrap;
|
| 176 |
-
gap: 10px;
|
| 177 |
-
margin-bottom: 20px;
|
| 178 |
-
}
|
| 179 |
-
.concept-item {
|
| 180 |
-
background-color: #f0f2f6;
|
| 181 |
-
border-radius: 5px;
|
| 182 |
-
padding: 8px 12px;
|
| 183 |
-
display: flex;
|
| 184 |
-
align-items: center;
|
| 185 |
-
gap: 8px;
|
| 186 |
-
}
|
| 187 |
-
.concept-name {
|
| 188 |
-
font-weight: bold;
|
| 189 |
-
}
|
| 190 |
-
.concept-freq {
|
| 191 |
-
color: #666;
|
| 192 |
-
font-size: 0.9em;
|
| 193 |
-
}
|
| 194 |
-
</style>
|
| 195 |
-
<div class="concept-table">
|
| 196 |
-
""" +
|
| 197 |
-
''.join([
|
| 198 |
-
f'<div class="concept-item"><span class="concept-name">{concept}</span>'
|
| 199 |
-
f'<span class="concept-freq">({freq:.2f})</span></div>'
|
| 200 |
-
for concept, freq in df.values
|
| 201 |
-
]) +
|
| 202 |
-
"</div>",
|
| 203 |
-
unsafe_allow_html=True
|
| 204 |
-
)
|
| 205 |
-
else:
|
| 206 |
-
st.info(semantic_t.get('no_concepts', 'No key concepts found'))
|
| 207 |
-
|
| 208 |
-
# Gráfico de conceptos
|
| 209 |
-
|
| 210 |
-
# st.subheader(semantic_t.get('concept_graph', 'Concepts Graph'))
|
| 211 |
-
#Colocar aquí el bloque de código
|
| 212 |
-
|
| 213 |
-
if 'concept_graph' in analysis and analysis['concept_graph'] is not None:
|
| 214 |
-
try:
|
| 215 |
-
# Aplicar estilos directamente al contenedor de Streamlit
|
| 216 |
-
st.markdown(
|
| 217 |
-
"""
|
| 218 |
-
<style>
|
| 219 |
-
.stContainer {
|
| 220 |
-
background-color: white;
|
| 221 |
-
border-radius: 10px;
|
| 222 |
-
padding: 20px;
|
| 223 |
-
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
| 224 |
-
margin: 10px 0;
|
| 225 |
-
}
|
| 226 |
-
.button-container {
|
| 227 |
-
display: flex;
|
| 228 |
-
gap: 10px;
|
| 229 |
-
margin: 10px 0;
|
| 230 |
-
}
|
| 231 |
-
</style>
|
| 232 |
-
""",
|
| 233 |
-
unsafe_allow_html=True
|
| 234 |
-
)
|
| 235 |
-
|
| 236 |
-
# Mostrar el gráfico directamente sin el div adicional
|
| 237 |
-
graph_bytes = analysis['concept_graph']
|
| 238 |
-
graph_base64 = base64.b64encode(graph_bytes).decode()
|
| 239 |
-
st.markdown(
|
| 240 |
-
f'<img src="data:image/png;base64,{graph_base64}" alt="Concept Graph" style="width:100%;"/>',
|
| 241 |
-
unsafe_allow_html=True
|
| 242 |
-
)
|
| 243 |
-
|
| 244 |
-
# Expandible con la interpretación
|
| 245 |
-
with st.expander("📊 " + semantic_t.get('semantic_graph_interpretation', "Interpretación del gráfico semántico")):
|
| 246 |
-
st.markdown(f"""
|
| 247 |
-
- 🔀 {semantic_t.get('semantic_arrow_meaning', 'Las flechas indican la dirección de la relación entre conceptos')}
|
| 248 |
-
- 🎨 {semantic_t.get('semantic_color_meaning', 'Los colores más intensos indican conceptos más centrales en el texto')}
|
| 249 |
-
- ⭕ {semantic_t.get('semantic_size_meaning', 'El tamaño de los nodos representa la frecuencia del concepto')}
|
| 250 |
-
- ↔️ {semantic_t.get('semantic_thickness_meaning', 'El grosor de las líneas indica la fuerza de la conexión')}
|
| 251 |
-
""")
|
| 252 |
-
|
| 253 |
-
# Contenedor para botones
|
| 254 |
-
col1, col2 = st.columns([1,4])
|
| 255 |
-
with col1:
|
| 256 |
-
st.download_button(
|
| 257 |
-
label="📥 " + semantic_t.get('download_semantic_network_graph', "Descargar gráfico de red semántica"),
|
| 258 |
-
data=graph_bytes,
|
| 259 |
-
file_name="semantic_graph.png",
|
| 260 |
-
mime="image/png",
|
| 261 |
-
use_container_width=True
|
| 262 |
-
)
|
| 263 |
-
|
| 264 |
-
except Exception as e:
|
| 265 |
-
logger.error(f"Error displaying graph: {str(e)}")
|
| 266 |
-
st.error(semantic_t.get('graph_error', 'Error displaying the graph'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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