AIdeaText commited on
Commit
ac689f1
·
verified ·
1 Parent(s): 64bc16b

Update modules/semantic/semantic_interface.py

Browse files
Files changed (1) hide show
  1. modules/semantic/semantic_interface.py +121 -94
modules/semantic/semantic_interface.py CHANGED
@@ -31,119 +31,146 @@ from ..database.semantic_export import export_user_interactions
31
 
32
  def display_semantic_interface(lang_code, nlp_models, semantic_t):
33
  """
34
- Interfaz para el análisis semántico
35
- Args:
36
- lang_code: Código del idioma actual
37
- nlp_models: Modelos de spaCy cargados
38
- semantic_t: Diccionario de traducciones semánticas
39
  """
40
  try:
41
  # Inicializar estados
42
  if 'semantic_analysis_counter' not in st.session_state:
43
  st.session_state.semantic_analysis_counter = 0
44
- if 'semantic_current_file' not in st.session_state:
45
- st.session_state.semantic_current_file = None
46
- if 'semantic_page' not in st.session_state:
47
- st.session_state.semantic_page = 'semantic'
48
 
49
- # Contenedor fijo para todos los controles
50
  with st.container():
51
- st.markdown("### Controls")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # File uploader
54
- uploaded_file = st.file_uploader(
55
- semantic_t.get('file_uploader', 'Upload a text file for analysis'),
56
- type=['txt'],
57
- key=f"semantic_file_uploader_{st.session_state.semantic_analysis_counter}",
58
- on_change=lambda: setattr(st.session_state, 'semantic_current_file', uploaded_file)
59
- )
60
-
61
- # Contenedor para botones alineados a la izquierda
62
- left_col, mid_col, right_col = st.columns([1,4,1])
63
- with left_col:
64
- # Botón de análisis
65
  analyze_button = st.button(
66
- semantic_t.get('analyze_button', 'Analyze text'),
67
- key=f"semantic_analyze_button_{st.session_state.semantic_analysis_counter}",
68
- disabled=not uploaded_file,
69
- use_container_width=True
70
  )
71
 
72
- # Botón de exportación (si hay resultados)
73
- if 'semantic_result' in st.session_state and st.session_state.semantic_result is not None:
74
- st.markdown("") # Espaciador
75
- export_button = st.button(
76
- semantic_t.get('export_button', 'Export Analysis'),
77
- key=f"semantic_export_{st.session_state.semantic_analysis_counter}",
78
- use_container_width=True
79
- )
80
- if export_button:
81
- st.download_button(
82
- label=semantic_t.get('download_pdf', 'Download PDF'),
83
- data=export_user_interactions(st.session_state.username, 'semantic'),
84
- file_name="semantic_analysis.pdf",
85
- mime="application/pdf",
86
- key=f"semantic_download_{st.session_state.semantic_analysis_counter}",
87
- use_container_width=True
88
- )
89
 
90
- st.markdown("---") # Separador
91
-
92
- # Procesar el análisis cuando se presiona el botón
93
- if analyze_button and uploaded_file is not None:
94
- try:
95
- with st.spinner(semantic_t.get('processing', 'Processing...')):
96
- text_content = uploaded_file.getvalue().decode('utf-8')
97
-
98
- analysis_result = process_semantic_input(
99
- text_content,
100
- lang_code,
101
- nlp_models,
102
- semantic_t
103
- )
104
-
105
- if analysis_result['success']:
106
- st.session_state.semantic_result = analysis_result
107
- st.session_state.semantic_analysis_counter += 1
108
 
109
- # Guardar en la base de datos
110
- if store_student_semantic_result(
111
- st.session_state.username,
112
- text_content,
113
- analysis_result['analysis']
114
- ):
115
- st.success(semantic_t.get('success_message', 'Analysis saved successfully'))
116
- # Asegurar que nos mantenemos en la página semántica
117
- st.session_state.page = 'semantic'
118
- # Mostrar resultados
119
- display_semantic_results(
120
- analysis_result,
121
- lang_code,
122
- semantic_t
123
- )
 
 
 
 
 
124
  else:
125
- st.error(semantic_t.get('error_message', 'Error saving analysis'))
126
- else:
127
- st.error(analysis_result['message'])
128
- except Exception as e:
129
- logger.error(f"Error en análisis semántico: {str(e)}")
130
- st.error(semantic_t.get('error_processing', f'Error processing text: {str(e)}'))
131
-
132
- # Mostrar resultados previos
133
- elif 'semantic_result' in st.session_state and st.session_state.semantic_result is not None:
134
- display_semantic_results(
135
- st.session_state.semantic_result,
136
- lang_code,
137
- semantic_t
138
- )
139
- else:
140
- st.info(semantic_t.get('initial_message', 'Upload a file to begin analysis'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  except Exception as e:
143
  logger.error(f"Error general en interfaz semántica: {str(e)}")
144
  st.error("Se produjo un error. Por favor, intente de nuevo.")
145
 
146
- # [Resto del código igual...]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  def display_semantic_results(result, lang_code, semantic_t):
149
  """
 
31
 
32
  def display_semantic_interface(lang_code, nlp_models, semantic_t):
33
  """
34
+ Interfaz para el análisis semántico con controles fijos y manejo de estado mejorado
 
 
 
 
35
  """
36
  try:
37
  # Inicializar estados
38
  if 'semantic_analysis_counter' not in st.session_state:
39
  st.session_state.semantic_analysis_counter = 0
40
+ if 'semantic_file_content' not in st.session_state:
41
+ st.session_state.semantic_file_content = None
42
+ if 'semantic_analysis_done' not in st.session_state:
43
+ st.session_state.semantic_analysis_done = False
44
 
45
+ # Contenedor principal con bordes
46
  with st.container():
47
+ st.markdown("### Semantic Analysis Controls")
48
+ st.markdown("---")
49
+
50
+ # Sección de carga de archivo
51
+ col_file, _ = st.columns([6, 4])
52
+ with col_file:
53
+ uploaded_file = st.file_uploader(
54
+ semantic_t.get('file_uploader', 'Upload a text file for analysis'),
55
+ type=['txt'],
56
+ key=f"semantic_file_uploader_{st.session_state.semantic_analysis_counter}",
57
+ on_change=lambda: handle_file_upload(uploaded_file)
58
+ )
59
+
60
+ # Contenedor fijo para botones
61
+ st.markdown("---")
62
+ col1, col2, col3, col4 = st.columns([2, 2, 2, 6])
63
 
64
+ with col1:
 
 
 
 
 
 
 
 
 
 
 
65
  analyze_button = st.button(
66
+ semantic_t.get('analyze_button', 'Analyze Text'),
67
+ disabled=not st.session_state.semantic_file_content,
68
+ use_container_width=True,
69
+ key="analyze_semantic"
70
  )
71
 
72
+ with col2:
73
+ export_button = st.button(
74
+ semantic_t.get('export_button', 'Export Analysis'),
75
+ disabled=not st.session_state.semantic_analysis_done,
76
+ use_container_width=True,
77
+ key="export_semantic"
78
+ )
79
+
80
+ with col3:
81
+ clear_button = st.button(
82
+ semantic_t.get('clear_button', 'Clear Analysis'),
83
+ disabled=not st.session_state.semantic_analysis_done,
84
+ use_container_width=True,
85
+ key="clear_semantic"
86
+ )
 
 
87
 
88
+ st.markdown("---")
89
+
90
+ # Procesar análisis
91
+ if analyze_button and st.session_state.semantic_file_content:
92
+ try:
93
+ with st.spinner(semantic_t.get('processing', 'Processing...')):
94
+ analysis_result = process_semantic_input(
95
+ st.session_state.semantic_file_content,
96
+ lang_code,
97
+ nlp_models,
98
+ semantic_t
99
+ )
 
 
 
 
 
 
100
 
101
+ if analysis_result['success']:
102
+ st.session_state.semantic_result = analysis_result
103
+ st.session_state.semantic_analysis_done = True
104
+ st.session_state.semantic_analysis_counter += 1
105
+
106
+ # Guardar en la base de datos
107
+ if store_student_semantic_result(
108
+ st.session_state.username,
109
+ st.session_state.semantic_file_content,
110
+ analysis_result['analysis']
111
+ ):
112
+ st.success(semantic_t.get('success_message', 'Analysis saved successfully'))
113
+ # Mostrar resultados
114
+ display_semantic_results(
115
+ analysis_result,
116
+ lang_code,
117
+ semantic_t
118
+ )
119
+ else:
120
+ st.error(semantic_t.get('error_message', 'Error saving analysis'))
121
  else:
122
+ st.error(analysis_result['message'])
123
+ except Exception as e:
124
+ logger.error(f"Error en análisis semántico: {str(e)}")
125
+ st.error(semantic_t.get('error_processing', f'Error processing text: {str(e)}'))
126
+
127
+ # Manejo de exportación
128
+ if export_button and st.session_state.semantic_analysis_done:
129
+ pdf_buffer = export_user_interactions(st.session_state.username, 'semantic')
130
+ st.download_button(
131
+ label=semantic_t.get('download_pdf', 'Download PDF'),
132
+ data=pdf_buffer,
133
+ file_name="semantic_analysis.pdf",
134
+ mime="application/pdf",
135
+ key=f"semantic_download_{st.session_state.semantic_analysis_counter}"
136
+ )
137
+
138
+ # Manejo de limpieza
139
+ if clear_button:
140
+ st.session_state.semantic_file_content = None
141
+ st.session_state.semantic_analysis_done = False
142
+ st.session_state.semantic_result = None
143
+ st.rerun()
144
+
145
+ # Mostrar resultados previos o mensaje inicial
146
+ if st.session_state.semantic_analysis_done and 'semantic_result' in st.session_state:
147
+ display_semantic_results(
148
+ st.session_state.semantic_result,
149
+ lang_code,
150
+ semantic_t
151
+ )
152
+ elif not st.session_state.semantic_file_content:
153
+ st.info(semantic_t.get('initial_message', 'Upload a file to begin analysis'))
154
 
155
  except Exception as e:
156
  logger.error(f"Error general en interfaz semántica: {str(e)}")
157
  st.error("Se produjo un error. Por favor, intente de nuevo.")
158
 
159
+ def handle_file_upload(uploaded_file):
160
+ """Maneja la carga de archivos y mantiene el estado"""
161
+ if uploaded_file is not None:
162
+ try:
163
+ content = uploaded_file.getvalue().decode('utf-8')
164
+ st.session_state.semantic_file_content = content
165
+ st.session_state.page = 'semantic' # Mantener en la página semántica
166
+ except Exception as e:
167
+ logger.error(f"Error al cargar archivo: {str(e)}")
168
+ st.error("Error al cargar el archivo. Asegúrese de que es un archivo de texto válido.")
169
+ st.session_state.semantic_file_content = None
170
+ else:
171
+ st.session_state.semantic_file_content = None
172
+
173
+ # [Resto del código igual...] ###############################################################################################################
174
 
175
  def display_semantic_results(result, lang_code, semantic_t):
176
  """