AIdeaText commited on
Commit
3970f3d
·
verified ·
1 Parent(s): 1a00e4a

Update modules/text_analysis/discourse_analysis.py

Browse files
modules/text_analysis/discourse_analysis.py CHANGED
@@ -8,6 +8,10 @@ import matplotlib.pyplot as plt
8
  import pandas as pd
9
  import numpy as np
10
  import logging
 
 
 
 
11
 
12
  logger = logging.getLogger(__name__)
13
 
@@ -23,6 +27,7 @@ from .stopwords import (
23
  get_stopwords_for_spacy
24
  )
25
 
 
26
  #####################
27
  # Define colors for grammatical categories
28
  POS_COLORS = {
@@ -80,6 +85,27 @@ ENTITY_LABELS = {
80
  }
81
  }
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  #################
85
  def compare_semantic_analysis(text1, text2, nlp, lang):
@@ -161,9 +187,17 @@ def create_concept_table(key_concepts):
161
 
162
 
163
  ##########################################################
 
164
  def perform_discourse_analysis(text1, text2, nlp, lang):
165
  """
166
  Realiza el análisis completo del discurso
 
 
 
 
 
 
 
167
  """
168
  try:
169
  logger.info("Iniciando análisis del discurso...")
@@ -174,27 +208,33 @@ def perform_discourse_analysis(text1, text2, nlp, lang):
174
 
175
  if not nlp:
176
  raise ValueError("Modelo de lenguaje no inicializado")
177
-
178
  # Realizar análisis comparativo
179
- try:
180
- fig1, fig2, key_concepts1, key_concepts2 = compare_semantic_analysis(
181
- text1, text2, nlp, lang
182
- )
183
- except Exception as e:
184
- logger.error(f"Error en el análisis comparativo: {str(e)}")
185
- raise
 
 
 
 
 
186
 
187
  # Crear tablas de resultados
188
- try:
189
- table1 = create_concept_table(key_concepts1)
190
- table2 = create_concept_table(key_concepts2)
191
- except Exception as e:
192
- logger.error(f"Error creando tablas de conceptos: {str(e)}")
193
- raise
194
 
195
  result = {
196
- 'graph1': fig1,
197
- 'graph2': fig2,
 
198
  'key_concepts1': key_concepts1,
199
  'key_concepts2': key_concepts2,
200
  'table1': table1,
@@ -202,17 +242,21 @@ def perform_discourse_analysis(text1, text2, nlp, lang):
202
  'success': True
203
  }
204
 
205
- logger.info("Análisis del discurso completado exitosamente")
206
  return result
207
 
208
  except Exception as e:
209
  logger.error(f"Error en perform_discourse_analysis: {str(e)}")
 
 
210
  return {
211
  'success': False,
212
  'error': str(e)
213
  }
214
  finally:
215
- plt.close('all') # Asegurar limpieza en todos los casos
 
 
216
 
217
  #################################################################
218
  def create_concept_table(key_concepts):
 
8
  import pandas as pd
9
  import numpy as np
10
  import logging
11
+ import io
12
+ import base64
13
+ from collections import Counter, defaultdict
14
+
15
 
16
  logger = logging.getLogger(__name__)
17
 
 
27
  get_stopwords_for_spacy
28
  )
29
 
30
+
31
  #####################
32
  # Define colors for grammatical categories
33
  POS_COLORS = {
 
85
  }
86
  }
87
 
88
+ #################
89
+ def fig_to_bytes(fig):
90
+ """
91
+ Convierte una figura de matplotlib a bytes en formato PNG.
92
+
93
+ Args:
94
+ fig: Figura de matplotlib
95
+
96
+ Returns:
97
+ bytes: Representación en bytes de la figura en formato PNG
98
+ """
99
+ try:
100
+ import io
101
+ buf = io.BytesIO()
102
+ fig.savefig(buf, format='png', dpi=100, bbox_inches='tight')
103
+ buf.seek(0)
104
+ return buf.getvalue()
105
+ except Exception as e:
106
+ logger.error(f"Error al convertir figura a bytes: {str(e)}")
107
+ return None
108
+
109
 
110
  #################
111
  def compare_semantic_analysis(text1, text2, nlp, lang):
 
187
 
188
 
189
  ##########################################################
190
+
191
  def perform_discourse_analysis(text1, text2, nlp, lang):
192
  """
193
  Realiza el análisis completo del discurso
194
+ Args:
195
+ text1: Primer texto a analizar
196
+ text2: Segundo texto a analizar
197
+ nlp: Modelo de spaCy cargado
198
+ lang: Código de idioma
199
+ Returns:
200
+ dict: Resultados del análisis con gráficos convertidos a bytes
201
  """
202
  try:
203
  logger.info("Iniciando análisis del discurso...")
 
208
 
209
  if not nlp:
210
  raise ValueError("Modelo de lenguaje no inicializado")
211
+
212
  # Realizar análisis comparativo
213
+ fig1, fig2, key_concepts1, key_concepts2 = compare_semantic_analysis(
214
+ text1, text2, nlp, lang
215
+ )
216
+
217
+ logger.info("Análisis comparativo completado, convirtiendo figuras a bytes...")
218
+
219
+ # Convertir figuras a bytes para almacenamiento
220
+ graph1_bytes = fig_to_bytes(fig1)
221
+ graph2_bytes = fig_to_bytes(fig2)
222
+
223
+ logger.info(f"Figura 1 convertida a {len(graph1_bytes) if graph1_bytes else 0} bytes")
224
+ logger.info(f"Figura 2 convertida a {len(graph2_bytes) if graph2_bytes else 0} bytes")
225
 
226
  # Crear tablas de resultados
227
+ table1 = create_concept_table(key_concepts1)
228
+ table2 = create_concept_table(key_concepts2)
229
+
230
+ # Cerrar figuras para liberar memoria
231
+ plt.close(fig1)
232
+ plt.close(fig2)
233
 
234
  result = {
235
+ 'graph1': graph1_bytes, # Bytes en lugar de figura
236
+ 'graph2': graph2_bytes, # Bytes en lugar de figura
237
+ 'combined_graph': None, # No hay gráfico combinado por ahora
238
  'key_concepts1': key_concepts1,
239
  'key_concepts2': key_concepts2,
240
  'table1': table1,
 
242
  'success': True
243
  }
244
 
245
+ logger.info("Análisis del discurso completado y listo para almacenamiento")
246
  return result
247
 
248
  except Exception as e:
249
  logger.error(f"Error en perform_discourse_analysis: {str(e)}")
250
+ # Asegurar limpieza de recursos
251
+ plt.close('all')
252
  return {
253
  'success': False,
254
  'error': str(e)
255
  }
256
  finally:
257
+ # Asegurar limpieza en todos los casos
258
+ plt.close('all')
259
+
260
 
261
  #################################################################
262
  def create_concept_table(key_concepts):