AIdeaText commited on
Commit
9cdec60
·
verified ·
1 Parent(s): d4a5717

Update modules/semantic/semantic_interface.py

Browse files
modules/semantic/semantic_interface.py CHANGED
@@ -25,32 +25,15 @@ from ..utils.widget_utils import generate_unique_key
25
  from ..database.semantic_mongo_db import store_student_semantic_result
26
  from ..database.semantic_export import export_user_interactions
27
 
28
- def handle_file_upload(uploaded_file):
29
- """
30
- Maneja la carga de archivos y mantiene el estado
31
- Args:
32
- uploaded_file: Archivo subido a través del file_uploader
33
- """
34
- try:
35
- if uploaded_file is not None:
36
- content = uploaded_file.getvalue().decode('utf-8')
37
- st.session_state.semantic_file_content = content
38
- st.session_state.page = 'semantic' # Mantener en la página semántica
39
- logger.info(f"Archivo cargado exitosamente: {uploaded_file.name}")
40
- else:
41
- st.session_state.semantic_file_content = None
42
- logger.info("No se ha cargado ningún archivo")
43
- except Exception as e:
44
- logger.error(f"Error al cargar archivo: {str(e)}")
45
- st.error("Error al cargar el archivo. Asegúrese de que es un archivo de texto válido.")
46
- st.session_state.semantic_file_content = None
47
-
48
  def display_semantic_interface(lang_code, nlp_models, semantic_t):
49
  """
50
  Interfaz para el análisis semántico con controles alineados horizontalmente
51
  """
 
 
 
52
  try:
53
- # Inicializar estados
54
  if 'semantic_analysis_counter' not in st.session_state:
55
  st.session_state.semantic_analysis_counter = 0
56
  if 'semantic_file_content' not in st.session_state:
@@ -58,52 +41,72 @@ def display_semantic_interface(lang_code, nlp_models, semantic_t):
58
  if 'semantic_analysis_done' not in st.session_state:
59
  st.session_state.semantic_analysis_done = False
60
 
61
- # Contenedor principal para la fila de controles
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  with st.container():
63
- # Crear una fila con cuatro columnas de igual ancho
64
- col1, col2, col3, col4 = st.columns([3, 1, 1, 1])
65
 
66
  # Columna 1: Carga de archivo
67
- with col1:
68
  uploaded_file = st.file_uploader(
69
  semantic_t.get('file_uploader', 'Upload TXT file'),
70
  type=['txt'],
71
- key=f"semantic_file_uploader_{st.session_state.semantic_analysis_counter}",
72
- on_change=lambda: handle_file_upload(uploaded_file)
73
  )
 
 
 
 
 
 
74
 
75
  # Columna 2: Botón de análisis
76
- with col2:
77
  analyze_button = st.button(
78
  semantic_t.get('analyze_button', 'Analyze Text'),
79
- disabled=not st.session_state.semantic_file_content,
80
- use_container_width=True,
81
- key="analyze_semantic"
82
  )
83
 
84
  # Columna 3: Botón de exportación
85
- with col3:
86
  export_button = st.button(
87
- semantic_t.get('export_button', 'Export Analysis'),
88
  disabled=not st.session_state.semantic_analysis_done,
89
- use_container_width=True,
90
- key="export_semantic"
91
  )
92
 
93
  # Columna 4: Botón de nuevo análisis
94
- with col4:
95
  new_analysis_button = st.button(
96
- semantic_t.get('new_analysis_button', 'New Analysis'),
97
  disabled=not st.session_state.semantic_analysis_done,
98
- use_container_width=True,
99
- key="new_semantic"
100
  )
101
 
102
- # Separador sutil
103
- st.markdown("<hr style='margin: 1em 0; padding: 0; opacity: 0.3'>", unsafe_allow_html=True)
104
 
105
  # Procesar análisis
106
- if analyze_button and st.session_state.semantic_file_content:
107
  try:
108
  with st.spinner(semantic_t.get('processing', 'Processing...')):
109
  analysis_result = process_semantic_input(
@@ -116,7 +119,6 @@ def display_semantic_interface(lang_code, nlp_models, semantic_t):
116
  if analysis_result['success']:
117
  st.session_state.semantic_result = analysis_result
118
  st.session_state.semantic_analysis_done = True
119
- st.session_state.semantic_analysis_counter += 1
120
 
121
  # Guardar en la base de datos
122
  if store_student_semantic_result(
@@ -135,7 +137,7 @@ def display_semantic_interface(lang_code, nlp_models, semantic_t):
135
  st.error(semantic_t.get('error_message', 'Error saving analysis'))
136
  else:
137
  st.error(analysis_result['message'])
138
-
139
  except Exception as e:
140
  logger.error(f"Error en análisis semántico: {str(e)}")
141
  st.error(semantic_t.get('error_processing', f'Error processing text: {str(e)}'))
@@ -160,16 +162,16 @@ def display_semantic_interface(lang_code, nlp_models, semantic_t):
160
  st.session_state.semantic_analysis_done = False
161
  st.session_state.semantic_result = None
162
  st.session_state.semantic_analysis_counter += 1
163
- st.rerun()
164
 
165
- # Mostrar resultados previos o mensaje inicial
166
- elif st.session_state.semantic_analysis_done and 'semantic_result' in st.session_state:
167
  display_semantic_results(
168
  st.session_state.semantic_result,
169
  lang_code,
170
  semantic_t
171
  )
172
- elif not st.session_state.semantic_file_content:
173
  st.info(semantic_t.get('initial_message', 'Upload a TXT file to begin analysis'))
174
 
175
  except Exception as e:
 
25
  from ..database.semantic_mongo_db import store_student_semantic_result
26
  from ..database.semantic_export import export_user_interactions
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def display_semantic_interface(lang_code, nlp_models, semantic_t):
29
  """
30
  Interfaz para el análisis semántico con controles alineados horizontalmente
31
  """
32
+ # Mantener la página en semántico
33
+ st.session_state.page = 'semantic'
34
+
35
  try:
36
+ # Inicializar estados si no existen
37
  if 'semantic_analysis_counter' not in st.session_state:
38
  st.session_state.semantic_analysis_counter = 0
39
  if 'semantic_file_content' not in st.session_state:
 
41
  if 'semantic_analysis_done' not in st.session_state:
42
  st.session_state.semantic_analysis_done = False
43
 
44
+ # Estilos CSS para alinear los botones
45
+ st.markdown("""
46
+ <style>
47
+ .stButton > button {
48
+ width: 100%;
49
+ margin: 0;
50
+ height: 38px;
51
+ display: inline-flex;
52
+ align-items: center;
53
+ justify-content: center;
54
+ }
55
+ .upload-container {
56
+ margin-bottom: 0 !important;
57
+ padding-bottom: 0 !important;
58
+ }
59
+ </style>
60
+ """, unsafe_allow_html=True)
61
+
62
+ # Contenedor principal con layout fijo
63
  with st.container():
64
+ # Una sola fila para todos los controles
65
+ cols = st.columns([4, 2, 2, 2])
66
 
67
  # Columna 1: Carga de archivo
68
+ with cols[0]:
69
  uploaded_file = st.file_uploader(
70
  semantic_t.get('file_uploader', 'Upload TXT file'),
71
  type=['txt'],
72
+ key=f"semantic_file_uploader_{st.session_state.semantic_analysis_counter}"
 
73
  )
74
+
75
+ # Actualizar el estado cuando se sube un archivo
76
+ if uploaded_file is not None:
77
+ content = uploaded_file.getvalue().decode('utf-8')
78
+ st.session_state.semantic_file_content = content
79
+ st.session_state.page = 'semantic'
80
 
81
  # Columna 2: Botón de análisis
82
+ with cols[1]:
83
  analyze_button = st.button(
84
  semantic_t.get('analyze_button', 'Analyze Text'),
85
+ disabled=(uploaded_file is None),
86
+ key=f"analyze_semantic_{st.session_state.semantic_analysis_counter}"
 
87
  )
88
 
89
  # Columna 3: Botón de exportación
90
+ with cols[2]:
91
  export_button = st.button(
92
+ semantic_t.get('export_button', 'Export'),
93
  disabled=not st.session_state.semantic_analysis_done,
94
+ key=f"export_semantic_{st.session_state.semantic_analysis_counter}"
 
95
  )
96
 
97
  # Columna 4: Botón de nuevo análisis
98
+ with cols[3]:
99
  new_analysis_button = st.button(
100
+ semantic_t.get('new_analysis', 'New'),
101
  disabled=not st.session_state.semantic_analysis_done,
102
+ key=f"new_semantic_{st.session_state.semantic_analysis_counter}"
 
103
  )
104
 
105
+ # Separador
106
+ st.markdown("<hr style='margin: 1em 0; opacity: 0.3'>", unsafe_allow_html=True)
107
 
108
  # Procesar análisis
109
+ if analyze_button and uploaded_file is not None:
110
  try:
111
  with st.spinner(semantic_t.get('processing', 'Processing...')):
112
  analysis_result = process_semantic_input(
 
119
  if analysis_result['success']:
120
  st.session_state.semantic_result = analysis_result
121
  st.session_state.semantic_analysis_done = True
 
122
 
123
  # Guardar en la base de datos
124
  if store_student_semantic_result(
 
137
  st.error(semantic_t.get('error_message', 'Error saving analysis'))
138
  else:
139
  st.error(analysis_result['message'])
140
+
141
  except Exception as e:
142
  logger.error(f"Error en análisis semántico: {str(e)}")
143
  st.error(semantic_t.get('error_processing', f'Error processing text: {str(e)}'))
 
162
  st.session_state.semantic_analysis_done = False
163
  st.session_state.semantic_result = None
164
  st.session_state.semantic_analysis_counter += 1
165
+ st.experimental_rerun()
166
 
167
+ # Mostrar resultados o mensaje inicial
168
+ if st.session_state.semantic_analysis_done and 'semantic_result' in st.session_state:
169
  display_semantic_results(
170
  st.session_state.semantic_result,
171
  lang_code,
172
  semantic_t
173
  )
174
+ elif not uploaded_file:
175
  st.info(semantic_t.get('initial_message', 'Upload a TXT file to begin analysis'))
176
 
177
  except Exception as e: