Spaces:
Sleeping
Sleeping
Update modules/text_analysis/discourse_analysis.py
Browse files
modules/text_analysis/discourse_analysis.py
CHANGED
|
@@ -1,4 +1,7 @@
|
|
| 1 |
# modules/text_analysis/discourse_analysis.py
|
|
|
|
|
|
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
import spacy
|
| 4 |
import networkx as nx
|
|
@@ -92,31 +95,126 @@ def compare_semantic_analysis(text1, text2, nlp, lang):
|
|
| 92 |
tuple: (fig1, fig2, key_concepts1, key_concepts2)
|
| 93 |
"""
|
| 94 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
# Procesar los textos
|
| 96 |
doc1 = nlp(text1)
|
| 97 |
doc2 = nlp(text2)
|
| 98 |
-
|
| 99 |
# Identificar conceptos clave con parámetros específicos
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
# Crear y visualizar grafos
|
|
|
|
| 104 |
G1 = create_concept_graph(doc1, key_concepts1)
|
| 105 |
G2 = create_concept_graph(doc2, key_concepts2)
|
| 106 |
|
|
|
|
|
|
|
| 107 |
fig1 = visualize_concept_graph(G1, lang)
|
|
|
|
| 108 |
fig2 = visualize_concept_graph(G2, lang)
|
| 109 |
|
| 110 |
-
# Limpiar títulos
|
| 111 |
-
fig1.suptitle("")
|
| 112 |
-
fig2.suptitle("")
|
|
|
|
|
|
|
|
|
|
| 113 |
|
|
|
|
| 114 |
return fig1, fig2, key_concepts1, key_concepts2
|
| 115 |
|
| 116 |
except Exception as e:
|
| 117 |
logger.error(f"Error en compare_semantic_analysis: {str(e)}")
|
|
|
|
| 118 |
raise
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
def create_concept_table(key_concepts):
|
| 121 |
"""
|
| 122 |
Crea una tabla de conceptos clave con sus frecuencias
|
|
@@ -133,6 +231,9 @@ def create_concept_table(key_concepts):
|
|
| 133 |
logger.error(f"Error en create_concept_table: {str(e)}")
|
| 134 |
raise
|
| 135 |
|
|
|
|
|
|
|
|
|
|
| 136 |
def perform_discourse_analysis(text1, text2, nlp, lang):
|
| 137 |
"""
|
| 138 |
Realiza el análisis completo del discurso
|
|
|
|
| 1 |
# modules/text_analysis/discourse_analysis.py
|
| 2 |
+
# Configuración de matplotlib
|
| 3 |
+
plt.switch_backend('agg') # Backend no interactivo
|
| 4 |
+
plt.style.use('default') # Estilo consistente
|
| 5 |
import streamlit as st
|
| 6 |
import spacy
|
| 7 |
import networkx as nx
|
|
|
|
| 95 |
tuple: (fig1, fig2, key_concepts1, key_concepts2)
|
| 96 |
"""
|
| 97 |
try:
|
| 98 |
+
logger.info(f"Iniciando análisis comparativo para idioma: {lang}")
|
| 99 |
+
|
| 100 |
+
# Obtener stopwords
|
| 101 |
+
stopwords = get_custom_stopwords(lang)
|
| 102 |
+
logger.info(f"Obtenidas {len(stopwords)} stopwords para el idioma {lang}")
|
| 103 |
+
|
| 104 |
# Procesar los textos
|
| 105 |
doc1 = nlp(text1)
|
| 106 |
doc2 = nlp(text2)
|
| 107 |
+
|
| 108 |
# Identificar conceptos clave con parámetros específicos
|
| 109 |
+
logger.info("Identificando conceptos clave del primer texto...")
|
| 110 |
+
key_concepts1 = identify_key_concepts(doc1, stopwords=stopwords, min_freq=2, min_length=3)
|
| 111 |
+
|
| 112 |
+
logger.info("Identificando conceptos clave del segundo texto...")
|
| 113 |
+
key_concepts2 = identify_key_concepts(doc2, stopwords=stopwords, min_freq=2, min_length=3)
|
| 114 |
+
|
| 115 |
+
if not key_concepts1 or not key_concepts2:
|
| 116 |
+
raise ValueError("No se pudieron identificar conceptos clave en uno o ambos textos")
|
| 117 |
|
| 118 |
# Crear y visualizar grafos
|
| 119 |
+
logger.info("Creando grafos de conceptos...")
|
| 120 |
G1 = create_concept_graph(doc1, key_concepts1)
|
| 121 |
G2 = create_concept_graph(doc2, key_concepts2)
|
| 122 |
|
| 123 |
+
logger.info("Visualizando grafos...")
|
| 124 |
+
plt.clf() # Limpiar figura actual
|
| 125 |
fig1 = visualize_concept_graph(G1, lang)
|
| 126 |
+
plt.clf() # Limpiar figura antes del segundo grafo
|
| 127 |
fig2 = visualize_concept_graph(G2, lang)
|
| 128 |
|
| 129 |
+
# Limpiar títulos y ajustar
|
| 130 |
+
fig1.suptitle("", pad=20)
|
| 131 |
+
fig2.suptitle("", pad=20)
|
| 132 |
+
|
| 133 |
+
# Ajustar diseño
|
| 134 |
+
plt.tight_layout()
|
| 135 |
|
| 136 |
+
logger.info("Análisis comparativo completado exitosamente")
|
| 137 |
return fig1, fig2, key_concepts1, key_concepts2
|
| 138 |
|
| 139 |
except Exception as e:
|
| 140 |
logger.error(f"Error en compare_semantic_analysis: {str(e)}")
|
| 141 |
+
plt.close('all') # Limpiar recursos en caso de error
|
| 142 |
raise
|
| 143 |
|
| 144 |
+
def create_concept_table(key_concepts):
|
| 145 |
+
"""
|
| 146 |
+
Crea una tabla de conceptos clave con sus frecuencias
|
| 147 |
+
Args:
|
| 148 |
+
key_concepts: Lista de tuplas (concepto, frecuencia)
|
| 149 |
+
Returns:
|
| 150 |
+
pandas.DataFrame: Tabla formateada de conceptos
|
| 151 |
+
"""
|
| 152 |
+
try:
|
| 153 |
+
if not key_concepts:
|
| 154 |
+
logger.warning("Lista de conceptos vacía")
|
| 155 |
+
return pd.DataFrame(columns=['Concepto', 'Frecuencia'])
|
| 156 |
+
|
| 157 |
+
df = pd.DataFrame(key_concepts, columns=['Concepto', 'Frecuencia'])
|
| 158 |
+
df['Frecuencia'] = df['Frecuencia'].round(2)
|
| 159 |
+
return df
|
| 160 |
+
except Exception as e:
|
| 161 |
+
logger.error(f"Error en create_concept_table: {str(e)}")
|
| 162 |
+
return pd.DataFrame(columns=['Concepto', 'Frecuencia'])
|
| 163 |
+
|
| 164 |
+
def perform_discourse_analysis(text1, text2, nlp, lang):
|
| 165 |
+
"""
|
| 166 |
+
Realiza el análisis completo del discurso
|
| 167 |
+
Args:
|
| 168 |
+
text1: Primer texto a analizar
|
| 169 |
+
text2: Segundo texto a analizar
|
| 170 |
+
nlp: Modelo de spaCy cargado
|
| 171 |
+
lang: Código de idioma
|
| 172 |
+
Returns:
|
| 173 |
+
dict: Resultados del análisis
|
| 174 |
+
"""
|
| 175 |
+
try:
|
| 176 |
+
logger.info("Iniciando análisis del discurso...")
|
| 177 |
+
|
| 178 |
+
# Verificar inputs
|
| 179 |
+
if not text1 or not text2:
|
| 180 |
+
raise ValueError("Los textos de entrada no pueden estar vacíos")
|
| 181 |
+
|
| 182 |
+
if not nlp:
|
| 183 |
+
raise ValueError("Modelo de lenguaje no inicializado")
|
| 184 |
+
|
| 185 |
+
# Realizar análisis comparativo
|
| 186 |
+
fig1, fig2, key_concepts1, key_concepts2 = compare_semantic_analysis(
|
| 187 |
+
text1, text2, nlp, lang
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
# Crear tablas de resultados
|
| 191 |
+
table1 = create_concept_table(key_concepts1)
|
| 192 |
+
table2 = create_concept_table(key_concepts2)
|
| 193 |
+
|
| 194 |
+
result = {
|
| 195 |
+
'graph1': fig1,
|
| 196 |
+
'graph2': fig2,
|
| 197 |
+
'key_concepts1': key_concepts1,
|
| 198 |
+
'key_concepts2': key_concepts2,
|
| 199 |
+
'table1': table1,
|
| 200 |
+
'table2': table2,
|
| 201 |
+
'success': True
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
logger.info("Análisis del discurso completado exitosamente")
|
| 205 |
+
return result
|
| 206 |
+
|
| 207 |
+
except Exception as e:
|
| 208 |
+
logger.error(f"Error en perform_discourse_analysis: {str(e)}")
|
| 209 |
+
plt.close('all') # Asegurar limpieza de recursos
|
| 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):
|
| 219 |
"""
|
| 220 |
Crea una tabla de conceptos clave con sus frecuencias
|
|
|
|
| 231 |
logger.error(f"Error en create_concept_table: {str(e)}")
|
| 232 |
raise
|
| 233 |
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
#################
|
| 237 |
def perform_discourse_analysis(text1, text2, nlp, lang):
|
| 238 |
"""
|
| 239 |
Realiza el análisis completo del discurso
|