AIdeaText commited on
Commit
5971e1f
verified
1 Parent(s): 86d6da4

Create semantic_analysis.py

Browse files
modules/text_analysis/semantic_analysis.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modules/text_analysis/semantic_analysis.py
2
+ # [Mantener todas las importaciones y constantes existentes...]
3
+
4
+ import streamlit as st
5
+ import spacy
6
+ import networkx as nx
7
+ import matplotlib.pyplot as plt
8
+ import io
9
+ import base64
10
+ from collections import Counter, defaultdict
11
+ from sklearn.feature_extraction.text import TfidfVectorizer
12
+ from sklearn.metrics.pairwise import cosine_similarity
13
+ import logging
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ # Define colors for grammatical categories
19
+ POS_COLORS = {
20
+ 'ADJ': '#FFA07A', 'ADP': '#98FB98', 'ADV': '#87CEFA', 'AUX': '#DDA0DD',
21
+ 'CCONJ': '#F0E68C', 'DET': '#FFB6C1', 'INTJ': '#FF6347', 'NOUN': '#90EE90',
22
+ 'NUM': '#FAFAD2', 'PART': '#D3D3D3', 'PRON': '#FFA500', 'PROPN': '#20B2AA',
23
+ 'SCONJ': '#DEB887', 'SYM': '#7B68EE', 'VERB': '#FF69B4', 'X': '#A9A9A9',
24
+ }
25
+
26
+ POS_TRANSLATIONS = {
27
+ 'es': {
28
+ 'ADJ': 'Adjetivo', 'ADP': 'Preposici贸n', 'ADV': 'Adverbio', 'AUX': 'Auxiliar',
29
+ 'CCONJ': 'Conjunci贸n Coordinante', 'DET': 'Determinante', 'INTJ': 'Interjecci贸n',
30
+ 'NOUN': 'Sustantivo', 'NUM': 'N煤mero', 'PART': 'Part铆cula', 'PRON': 'Pronombre',
31
+ 'PROPN': 'Nombre Propio', 'SCONJ': 'Conjunci贸n Subordinante', 'SYM': 'S铆mbolo',
32
+ 'VERB': 'Verbo', 'X': 'Otro',
33
+ },
34
+ 'en': {
35
+ 'ADJ': 'Adjective', 'ADP': 'Preposition', 'ADV': 'Adverb', 'AUX': 'Auxiliary',
36
+ 'CCONJ': 'Coordinating Conjunction', 'DET': 'Determiner', 'INTJ': 'Interjection',
37
+ 'NOUN': 'Noun', 'NUM': 'Number', 'PART': 'Particle', 'PRON': 'Pronoun',
38
+ 'PROPN': 'Proper Noun', 'SCONJ': 'Subordinating Conjunction', 'SYM': 'Symbol',
39
+ 'VERB': 'Verb', 'X': 'Other',
40
+ },
41
+ 'fr': {
42
+ 'ADJ': 'Adjectif', 'ADP': 'Pr茅position', 'ADV': 'Adverbe', 'AUX': 'Auxiliaire',
43
+ 'CCONJ': 'Conjonction de Coordination', 'DET': 'D茅terminant', 'INTJ': 'Interjection',
44
+ 'NOUN': 'Nom', 'NUM': 'Nombre', 'PART': 'Particule', 'PRON': 'Pronom',
45
+ 'PROPN': 'Nom Propre', 'SCONJ': 'Conjonction de Subordination', 'SYM': 'Symbole',
46
+ 'VERB': 'Verbe', 'X': 'Autre',
47
+ }
48
+ }
49
+
50
+ ENTITY_LABELS = {
51
+ 'es': {
52
+ "Personas": "lightblue",
53
+ "Lugares": "lightcoral",
54
+ "Inventos": "lightgreen",
55
+ "Fechas": "lightyellow",
56
+ "Conceptos": "lightpink"
57
+ },
58
+ 'en': {
59
+ "People": "lightblue",
60
+ "Places": "lightcoral",
61
+ "Inventions": "lightgreen",
62
+ "Dates": "lightyellow",
63
+ "Concepts": "lightpink"
64
+ },
65
+ 'fr': {
66
+ "Personnes": "lightblue",
67
+ "Lieux": "lightcoral",
68
+ "Inventions": "lightgreen",
69
+ "Dates": "lightyellow",
70
+ "Concepts": "lightpink"
71
+ }
72
+ }
73
+
74
+ CUSTOM_STOPWORDS = {
75
+ 'es': {
76
+ # Art铆culos
77
+ 'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas',
78
+ # Preposiciones comunes
79
+ 'a', 'ante', 'bajo', 'con', 'contra', 'de', 'desde', 'en',
80
+ 'entre', 'hacia', 'hasta', 'para', 'por', 'seg煤n', 'sin',
81
+ 'sobre', 'tras', 'durante', 'mediante',
82
+ # Conjunciones
83
+ 'y', 'e', 'ni', 'o', 'u', 'pero', 'sino', 'porque',
84
+ # Pronombres
85
+ 'yo', 't煤', '茅l', 'ella', 'nosotros', 'vosotros', 'ellos',
86
+ 'ellas', 'este', 'esta', 'ese', 'esa', 'aquel', 'aquella',
87
+ # Verbos auxiliares comunes
88
+ 'ser', 'estar', 'haber', 'tener',
89
+ # Palabras comunes en textos acad茅micos
90
+ 'adem谩s', 'tambi茅n', 'asimismo', 'sin embargo', 'no obstante',
91
+ 'por lo tanto', 'entonces', 'as铆', 'luego', 'pues',
92
+ # N煤meros escritos
93
+ 'uno', 'dos', 'tres', 'primer', 'primera', 'segundo', 'segunda',
94
+ # Otras palabras comunes
95
+ 'cada', 'todo', 'toda', 'todos', 'todas', 'otro', 'otra',
96
+ 'donde', 'cuando', 'como', 'que', 'cual', 'quien',
97
+ 'cuyo', 'cuya', 'hay', 'solo', 'ver', 'si', 'no',
98
+ # S铆mbolos y caracteres especiales
99
+ '#', '@', '/', '*', '+', '-', '=', '$', '%'
100
+ },
101
+ 'en': {
102
+ # Articles
103
+ 'the', 'a', 'an',
104
+ # Common prepositions
105
+ 'in', 'on', 'at', 'by', 'for', 'with', 'about', 'against',
106
+ 'between', 'into', 'through', 'during', 'before', 'after',
107
+ 'above', 'below', 'to', 'from', 'up', 'down', 'of',
108
+ # Conjunctions
109
+ 'and', 'or', 'but', 'nor', 'so', 'for', 'yet',
110
+ # Pronouns
111
+ 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'this',
112
+ 'that', 'these', 'those', 'my', 'your', 'his', 'her',
113
+ # Auxiliary verbs
114
+ 'be', 'am', 'is', 'are', 'was', 'were', 'been', 'have',
115
+ 'has', 'had', 'do', 'does', 'did',
116
+ # Common academic words
117
+ 'therefore', 'however', 'thus', 'hence', 'moreover',
118
+ 'furthermore', 'nevertheless',
119
+ # Numbers written
120
+ 'one', 'two', 'three', 'first', 'second', 'third',
121
+ # Other common words
122
+ 'where', 'when', 'how', 'what', 'which', 'who',
123
+ 'whom', 'whose', 'there', 'here', 'just', 'only',
124
+ # Symbols and special characters
125
+ '#', '@', '/', '*', '+', '-', '=', '$', '%'
126
+ },
127
+ 'fr': {
128
+ # Articles
129
+ 'le', 'la', 'les', 'un', 'une', 'des',
130
+ # Prepositions
131
+ '脿', 'de', 'dans', 'sur', 'en', 'par', 'pour', 'avec',
132
+ 'sans', 'sous', 'entre', 'derri猫re', 'chez', 'avant',
133
+ # Conjunctions
134
+ 'et', 'ou', 'mais', 'donc', 'car', 'ni', 'or',
135
+ # Pronouns
136
+ 'je', 'tu', 'il', 'elle', 'nous', 'vous', 'ils',
137
+ 'elles', 'ce', 'cette', 'ces', 'celui', 'celle',
138
+ # Auxiliary verbs
139
+ '锚tre', 'avoir', 'faire',
140
+ # Academic words
141
+ 'donc', 'cependant', 'n茅anmoins', 'ainsi', 'toutefois',
142
+ 'pourtant', 'alors',
143
+ # Numbers
144
+ 'un', 'deux', 'trois', 'premier', 'premi猫re', 'second',
145
+ # Other common words
146
+ 'o霉', 'quand', 'comment', 'que', 'qui', 'quoi',
147
+ 'quel', 'quelle', 'plus', 'moins',
148
+ # Symbols
149
+ '#', '@', '/', '*', '+', '-', '=', '$', '%'
150
+ }
151
+ }
152
+
153
+ ##############################################################################################################
154
+ def get_stopwords(lang_code):
155
+ """
156
+ Obtiene el conjunto de stopwords para un idioma espec铆fico.
157
+ Combina las stopwords de spaCy con las personalizadas.
158
+ """
159
+ try:
160
+ nlp = spacy.load(f'{lang_code}_core_news_sm')
161
+ spacy_stopwords = nlp.Defaults.stop_words
162
+ custom_stopwords = CUSTOM_STOPWORDS.get(lang_code, set())
163
+ return spacy_stopwords.union(custom_stopwords)
164
+ except:
165
+ return CUSTOM_STOPWORDS.get(lang_code, set())
166
+
167
+
168
+ def perform_semantic_analysis(text, nlp, lang_code):
169
+ """
170
+ Realiza el an谩lisis sem谩ntico completo del texto.
171
+ Args:
172
+ text: Texto a analizar
173
+ nlp: Modelo de spaCy
174
+ lang_code: C贸digo del idioma
175
+ Returns:
176
+ dict: Resultados del an谩lisis
177
+ """
178
+
179
+ logger.info(f"Starting semantic analysis for language: {lang_code}")
180
+ try:
181
+ doc = nlp(text)
182
+ key_concepts = identify_key_concepts(doc)
183
+ concept_graph = create_concept_graph(doc, key_concepts)
184
+ concept_graph_fig = visualize_concept_graph(concept_graph, lang_code)
185
+ entities = extract_entities(doc, lang_code)
186
+ entity_graph = create_entity_graph(entities)
187
+ entity_graph_fig = visualize_entity_graph(entity_graph, lang_code)
188
+
189
+ # Convertir figuras a bytes
190
+ concept_graph_bytes = fig_to_bytes(concept_graph_fig)
191
+ entity_graph_bytes = fig_to_bytes(entity_graph_fig)
192
+
193
+ logger.info("Semantic analysis completed successfully")
194
+ return {
195
+ 'key_concepts': key_concepts,
196
+ 'concept_graph': concept_graph_bytes,
197
+ 'entities': entities,
198
+ 'entity_graph': entity_graph_bytes
199
+ }
200
+ except Exception as e:
201
+ logger.error(f"Error in perform_semantic_analysis: {str(e)}")
202
+ raise
203
+
204
+
205
+ def fig_to_bytes(fig):
206
+ buf = io.BytesIO()
207
+ fig.savefig(buf, format='png')
208
+ buf.seek(0)
209
+ return buf.getvalue()
210
+
211
+
212
+ def fig_to_html(fig):
213
+ buf = io.BytesIO()
214
+ fig.savefig(buf, format='png')
215
+ buf.seek(0)
216
+ img_str = base64.b64encode(buf.getvalue()).decode()
217
+ return f'<img src="data:image/png;base64,{img_str}" />'
218
+
219
+
220
+
221
+ def identify_key_concepts(doc, min_freq=2, min_length=3):
222
+ """
223
+ Identifica conceptos clave en el texto.
224
+ Args:
225
+ doc: Documento procesado por spaCy
226
+ min_freq: Frecuencia m铆nima para considerar un concepto
227
+ min_length: Longitud m铆nima de palabra para considerar
228
+ Returns:
229
+ list: Lista de tuplas (concepto, frecuencia)
230
+ """
231
+ try:
232
+ # Obtener stopwords para el idioma
233
+ stopwords = get_stopwords(doc.lang_)
234
+
235
+ # Contar frecuencias de palabras
236
+ word_freq = Counter()
237
+
238
+ for token in doc:
239
+ if (token.lemma_.lower() not in stopwords and
240
+ len(token.lemma_) >= min_length and
241
+ token.is_alpha and
242
+ not token.is_punct and
243
+ not token.like_num):
244
+
245
+ word_freq[token.lemma_.lower()] += 1
246
+
247
+ # Filtrar por frecuencia m铆nima
248
+ concepts = [(word, freq) for word, freq in word_freq.items()
249
+ if freq >= min_freq]
250
+
251
+ # Ordenar por frecuencia
252
+ concepts.sort(key=lambda x: x[1], reverse=True)
253
+
254
+ return concepts[:10] # Retornar los 10 conceptos m谩s frecuentes
255
+
256
+ except Exception as e:
257
+ logger.error(f"Error en identify_key_concepts: {str(e)}")
258
+ return [] # Retornar lista vac铆a en caso de error
259
+
260
+
261
+ def create_concept_graph(doc, key_concepts):
262
+ """
263
+ Crea un grafo de relaciones entre conceptos.
264
+ Args:
265
+ doc: Documento procesado por spaCy
266
+ key_concepts: Lista de tuplas (concepto, frecuencia)
267
+ Returns:
268
+ nx.Graph: Grafo de conceptos
269
+ """
270
+ try:
271
+ G = nx.Graph()
272
+
273
+ # Crear un conjunto de conceptos clave para b煤squeda r谩pida
274
+ concept_words = {concept[0].lower() for concept in key_concepts}
275
+
276
+ # A帽adir nodos al grafo
277
+ for concept, freq in key_concepts:
278
+ G.add_node(concept.lower(), weight=freq)
279
+
280
+ # Analizar cada oraci贸n
281
+ for sent in doc.sents:
282
+ # Obtener conceptos en la oraci贸n actual
283
+ current_concepts = []
284
+ for token in sent:
285
+ if token.lemma_.lower() in concept_words:
286
+ current_concepts.append(token.lemma_.lower())
287
+
288
+ # Crear conexiones entre conceptos en la misma oraci贸n
289
+ for i, concept1 in enumerate(current_concepts):
290
+ for concept2 in current_concepts[i+1:]:
291
+ if concept1 != concept2:
292
+ # Si ya existe la arista, incrementar el peso
293
+ if G.has_edge(concept1, concept2):
294
+ G[concept1][concept2]['weight'] += 1
295
+ # Si no existe, crear nueva arista con peso 1
296
+ else:
297
+ G.add_edge(concept1, concept2, weight=1)
298
+
299
+ return G
300
+
301
+ except Exception as e:
302
+ logger.error(f"Error en create_concept_graph: {str(e)}")
303
+ # Retornar un grafo vac铆o en caso de error
304
+ return nx.Graph()
305
+
306
+ def visualize_concept_graph(G, lang_code):
307
+ """
308
+ Visualiza el grafo de conceptos.
309
+ Args:
310
+ G: Grafo de networkx
311
+ lang_code: C贸digo del idioma
312
+ Returns:
313
+ matplotlib.figure.Figure: Figura con el grafo visualizado
314
+ """
315
+ try:
316
+ plt.figure(figsize=(12, 8))
317
+
318
+ # Calcular el layout del grafo
319
+ pos = nx.spring_layout(G)
320
+
321
+ # Obtener pesos de nodos y aristas
322
+ node_weights = [G.nodes[node].get('weight', 1) * 500 for node in G.nodes()]
323
+ edge_weights = [G[u][v].get('weight', 1) for u, v in G.edges()]
324
+
325
+ # Dibujar el grafo
326
+ nx.draw_networkx_nodes(G, pos,
327
+ node_size=node_weights,
328
+ node_color='lightblue',
329
+ alpha=0.6)
330
+
331
+ nx.draw_networkx_edges(G, pos,
332
+ width=edge_weights,
333
+ alpha=0.5,
334
+ edge_color='gray')
335
+
336
+ nx.draw_networkx_labels(G, pos,
337
+ font_size=10,
338
+ font_weight='bold')
339
+
340
+ plt.title("Red de conceptos relacionados")
341
+ plt.axis('off')
342
+
343
+ return plt.gcf()
344
+
345
+ except Exception as e:
346
+ logger.error(f"Error en visualize_concept_graph: {str(e)}")
347
+ # Retornar una figura vac铆a en caso de error
348
+ return plt.figure()
349
+
350
+ def create_entity_graph(entities):
351
+ G = nx.Graph()
352
+ for entity_type, entity_list in entities.items():
353
+ for entity in entity_list:
354
+ G.add_node(entity, type=entity_type)
355
+ for i, entity1 in enumerate(entity_list):
356
+ for entity2 in entity_list[i+1:]:
357
+ G.add_edge(entity1, entity2)
358
+ return G
359
+
360
+ def visualize_entity_graph(G, lang_code):
361
+ fig, ax = plt.subplots(figsize=(12, 8))
362
+ pos = nx.spring_layout(G)
363
+ for entity_type, color in ENTITY_LABELS[lang_code].items():
364
+ node_list = [node for node, data in G.nodes(data=True) if data['type'] == entity_type]
365
+ nx.draw_networkx_nodes(G, pos, nodelist=node_list, node_color=color, node_size=500, alpha=0.8, ax=ax)
366
+ nx.draw_networkx_edges(G, pos, width=1, alpha=0.5, ax=ax)
367
+ nx.draw_networkx_labels(G, pos, font_size=8, font_weight="bold", ax=ax)
368
+ ax.set_title(f"Relaciones entre Entidades ({lang_code})", fontsize=16)
369
+ ax.axis('off')
370
+ plt.tight_layout()
371
+ return fig
372
+
373
+
374
+ #################################################################################
375
+ def create_topic_graph(topics, doc):
376
+ G = nx.Graph()
377
+ for topic in topics:
378
+ G.add_node(topic, weight=doc.text.count(topic))
379
+ for i, topic1 in enumerate(topics):
380
+ for topic2 in topics[i+1:]:
381
+ weight = sum(1 for sent in doc.sents if topic1 in sent.text and topic2 in sent.text)
382
+ if weight > 0:
383
+ G.add_edge(topic1, topic2, weight=weight)
384
+ return G
385
+
386
+ def visualize_topic_graph(G, lang_code):
387
+ fig, ax = plt.subplots(figsize=(12, 8))
388
+ pos = nx.spring_layout(G)
389
+ node_sizes = [G.nodes[node]['weight'] * 100 for node in G.nodes()]
390
+ nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='lightgreen', alpha=0.8, ax=ax)
391
+ nx.draw_networkx_labels(G, pos, font_size=10, font_weight="bold", ax=ax)
392
+ edge_weights = [G[u][v]['weight'] for u, v in G.edges()]
393
+ nx.draw_networkx_edges(G, pos, width=edge_weights, alpha=0.5, ax=ax)
394
+ ax.set_title(f"Relaciones entre Temas ({lang_code})", fontsize=16)
395
+ ax.axis('off')
396
+ plt.tight_layout()
397
+ return fig
398
+
399
+ ###########################################################################################
400
+ def generate_summary(doc, lang_code):
401
+ sentences = list(doc.sents)
402
+ summary = sentences[:3] # Toma las primeras 3 oraciones como resumen
403
+ return " ".join([sent.text for sent in summary])
404
+
405
+ def extract_entities(doc, lang_code):
406
+ entities = defaultdict(list)
407
+ for ent in doc.ents:
408
+ if ent.label_ in ENTITY_LABELS[lang_code]:
409
+ entities[ent.label_].append(ent.text)
410
+ return dict(entities)
411
+
412
+ def analyze_sentiment(doc, lang_code):
413
+ positive_words = sum(1 for token in doc if token.sentiment > 0)
414
+ negative_words = sum(1 for token in doc if token.sentiment < 0)
415
+ total_words = len(doc)
416
+ if positive_words > negative_words:
417
+ return "Positivo"
418
+ elif negative_words > positive_words:
419
+ return "Negativo"
420
+ else:
421
+ return "Neutral"
422
+
423
+ def extract_topics(doc, lang_code):
424
+ vectorizer = TfidfVectorizer(stop_words='english', max_features=5)
425
+ tfidf_matrix = vectorizer.fit_transform([doc.text])
426
+ feature_names = vectorizer.get_feature_names_out()
427
+ return list(feature_names)
428
+
429
+ # Aseg煤rate de que todas las funciones necesarias est茅n exportadas
430
+ __all__ = [
431
+ 'perform_semantic_analysis',
432
+ 'identify_key_concepts',
433
+ 'create_concept_graph',
434
+ 'visualize_concept_graph',
435
+ 'create_entity_graph',
436
+ 'visualize_entity_graph',
437
+ 'generate_summary',
438
+ 'extract_entities',
439
+ 'analyze_sentiment',
440
+ 'create_topic_graph',
441
+ 'visualize_topic_graph',
442
+ 'extract_topics',
443
+ 'ENTITY_LABELS',
444
+ 'POS_COLORS',
445
+ 'POS_TRANSLATIONS'
446
+ ]