Update modules/text_analysis/semantic_analysis.py
Browse files
modules/text_analysis/semantic_analysis.py
CHANGED
@@ -1,251 +1,263 @@
|
|
1 |
-
#semantic_analysis.py
|
2 |
-
|
3 |
-
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
-
import
|
8 |
-
|
9 |
-
|
10 |
-
from
|
11 |
-
import
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
'
|
21 |
-
'
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
'
|
29 |
-
'
|
30 |
-
'
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
'
|
36 |
-
'
|
37 |
-
'
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
'
|
43 |
-
'
|
44 |
-
'
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
"
|
53 |
-
"
|
54 |
-
"
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
"
|
60 |
-
"
|
61 |
-
"
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
"
|
67 |
-
"
|
68 |
-
"
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
ax.
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
G =
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
def
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
'
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
'
|
249 |
-
'
|
250 |
-
'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
251 |
]
|
|
|
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 |
+
##############################################################################################################
|
75 |
+
def perform_semantic_analysis(text, nlp, lang_code):
|
76 |
+
"""
|
77 |
+
Realiza el an谩lisis sem谩ntico completo del texto.
|
78 |
+
Args:
|
79 |
+
text: Texto a analizar
|
80 |
+
nlp: Modelo de spaCy
|
81 |
+
lang_code: C贸digo del idioma
|
82 |
+
Returns:
|
83 |
+
dict: Resultados del an谩lisis
|
84 |
+
"""
|
85 |
+
|
86 |
+
logger.info(f"Starting semantic analysis for language: {lang_code}")
|
87 |
+
try:
|
88 |
+
doc = nlp(text)
|
89 |
+
key_concepts = identify_key_concepts(doc)
|
90 |
+
concept_graph = create_concept_graph(doc, key_concepts)
|
91 |
+
concept_graph_fig = visualize_concept_graph(concept_graph, lang_code)
|
92 |
+
entities = extract_entities(doc, lang_code)
|
93 |
+
entity_graph = create_entity_graph(entities)
|
94 |
+
entity_graph_fig = visualize_entity_graph(entity_graph, lang_code)
|
95 |
+
|
96 |
+
# Convertir figuras a bytes
|
97 |
+
concept_graph_bytes = fig_to_bytes(concept_graph_fig)
|
98 |
+
entity_graph_bytes = fig_to_bytes(entity_graph_fig)
|
99 |
+
|
100 |
+
logger.info("Semantic analysis completed successfully")
|
101 |
+
return {
|
102 |
+
'key_concepts': key_concepts,
|
103 |
+
'concept_graph': concept_graph_bytes,
|
104 |
+
'entities': entities,
|
105 |
+
'entity_graph': entity_graph_bytes
|
106 |
+
}
|
107 |
+
except Exception as e:
|
108 |
+
logger.error(f"Error in perform_semantic_analysis: {str(e)}")
|
109 |
+
raise
|
110 |
+
|
111 |
+
|
112 |
+
def fig_to_bytes(fig):
|
113 |
+
buf = io.BytesIO()
|
114 |
+
fig.savefig(buf, format='png')
|
115 |
+
buf.seek(0)
|
116 |
+
return buf.getvalue()
|
117 |
+
|
118 |
+
|
119 |
+
def fig_to_html(fig):
|
120 |
+
buf = io.BytesIO()
|
121 |
+
fig.savefig(buf, format='png')
|
122 |
+
buf.seek(0)
|
123 |
+
img_str = base64.b64encode(buf.getvalue()).decode()
|
124 |
+
return f'<img src="data:image/png;base64,{img_str}" />'
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
def identify_key_concepts(doc):
|
129 |
+
logger.info("Identifying key concepts")
|
130 |
+
word_freq = Counter([token.lemma_.lower() for token in doc if token.pos_ in ['NOUN', 'VERB'] and not token.is_stop])
|
131 |
+
key_concepts = word_freq.most_common(10)
|
132 |
+
return [(concept, float(freq)) for concept, freq in key_concepts]
|
133 |
+
|
134 |
+
|
135 |
+
def create_concept_graph(doc, key_concepts):
|
136 |
+
G = nx.Graph()
|
137 |
+
for concept, freq in key_concepts:
|
138 |
+
G.add_node(concept, weight=freq)
|
139 |
+
for sent in doc.sents:
|
140 |
+
sent_concepts = [token.lemma_.lower() for token in sent if token.lemma_.lower() in dict(key_concepts)]
|
141 |
+
for i, concept1 in enumerate(sent_concepts):
|
142 |
+
for concept2 in sent_concepts[i+1:]:
|
143 |
+
if G.has_edge(concept1, concept2):
|
144 |
+
G[concept1][concept2]['weight'] += 1
|
145 |
+
else:
|
146 |
+
G.add_edge(concept1, concept2, weight=1)
|
147 |
+
return G
|
148 |
+
|
149 |
+
def visualize_concept_graph(G, lang_code):
|
150 |
+
fig, ax = plt.subplots(figsize=(12, 8))
|
151 |
+
pos = nx.spring_layout(G, k=0.5, iterations=50)
|
152 |
+
node_sizes = [G.nodes[node]['weight'] * 100 for node in G.nodes()]
|
153 |
+
nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='lightblue', alpha=0.8, ax=ax)
|
154 |
+
nx.draw_networkx_labels(G, pos, font_size=10, font_weight="bold", ax=ax)
|
155 |
+
edge_weights = [G[u][v]['weight'] for u, v in G.edges()]
|
156 |
+
nx.draw_networkx_edges(G, pos, width=edge_weights, alpha=0.5, ax=ax)
|
157 |
+
title = {
|
158 |
+
'es': "Relaciones entre Conceptos Clave",
|
159 |
+
'en': "Key Concept Relations",
|
160 |
+
'fr': "Relations entre Concepts Cl茅s"
|
161 |
+
}
|
162 |
+
ax.set_title(title[lang_code], fontsize=16)
|
163 |
+
ax.axis('off')
|
164 |
+
plt.tight_layout()
|
165 |
+
return fig
|
166 |
+
|
167 |
+
def create_entity_graph(entities):
|
168 |
+
G = nx.Graph()
|
169 |
+
for entity_type, entity_list in entities.items():
|
170 |
+
for entity in entity_list:
|
171 |
+
G.add_node(entity, type=entity_type)
|
172 |
+
for i, entity1 in enumerate(entity_list):
|
173 |
+
for entity2 in entity_list[i+1:]:
|
174 |
+
G.add_edge(entity1, entity2)
|
175 |
+
return G
|
176 |
+
|
177 |
+
def visualize_entity_graph(G, lang_code):
|
178 |
+
fig, ax = plt.subplots(figsize=(12, 8))
|
179 |
+
pos = nx.spring_layout(G)
|
180 |
+
for entity_type, color in ENTITY_LABELS[lang_code].items():
|
181 |
+
node_list = [node for node, data in G.nodes(data=True) if data['type'] == entity_type]
|
182 |
+
nx.draw_networkx_nodes(G, pos, nodelist=node_list, node_color=color, node_size=500, alpha=0.8, ax=ax)
|
183 |
+
nx.draw_networkx_edges(G, pos, width=1, alpha=0.5, ax=ax)
|
184 |
+
nx.draw_networkx_labels(G, pos, font_size=8, font_weight="bold", ax=ax)
|
185 |
+
ax.set_title(f"Relaciones entre Entidades ({lang_code})", fontsize=16)
|
186 |
+
ax.axis('off')
|
187 |
+
plt.tight_layout()
|
188 |
+
return fig
|
189 |
+
|
190 |
+
|
191 |
+
#################################################################################
|
192 |
+
def create_topic_graph(topics, doc):
|
193 |
+
G = nx.Graph()
|
194 |
+
for topic in topics:
|
195 |
+
G.add_node(topic, weight=doc.text.count(topic))
|
196 |
+
for i, topic1 in enumerate(topics):
|
197 |
+
for topic2 in topics[i+1:]:
|
198 |
+
weight = sum(1 for sent in doc.sents if topic1 in sent.text and topic2 in sent.text)
|
199 |
+
if weight > 0:
|
200 |
+
G.add_edge(topic1, topic2, weight=weight)
|
201 |
+
return G
|
202 |
+
|
203 |
+
def visualize_topic_graph(G, lang_code):
|
204 |
+
fig, ax = plt.subplots(figsize=(12, 8))
|
205 |
+
pos = nx.spring_layout(G)
|
206 |
+
node_sizes = [G.nodes[node]['weight'] * 100 for node in G.nodes()]
|
207 |
+
nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='lightgreen', alpha=0.8, ax=ax)
|
208 |
+
nx.draw_networkx_labels(G, pos, font_size=10, font_weight="bold", ax=ax)
|
209 |
+
edge_weights = [G[u][v]['weight'] for u, v in G.edges()]
|
210 |
+
nx.draw_networkx_edges(G, pos, width=edge_weights, alpha=0.5, ax=ax)
|
211 |
+
ax.set_title(f"Relaciones entre Temas ({lang_code})", fontsize=16)
|
212 |
+
ax.axis('off')
|
213 |
+
plt.tight_layout()
|
214 |
+
return fig
|
215 |
+
|
216 |
+
###########################################################################################
|
217 |
+
def generate_summary(doc, lang_code):
|
218 |
+
sentences = list(doc.sents)
|
219 |
+
summary = sentences[:3] # Toma las primeras 3 oraciones como resumen
|
220 |
+
return " ".join([sent.text for sent in summary])
|
221 |
+
|
222 |
+
def extract_entities(doc, lang_code):
|
223 |
+
entities = defaultdict(list)
|
224 |
+
for ent in doc.ents:
|
225 |
+
if ent.label_ in ENTITY_LABELS[lang_code]:
|
226 |
+
entities[ent.label_].append(ent.text)
|
227 |
+
return dict(entities)
|
228 |
+
|
229 |
+
def analyze_sentiment(doc, lang_code):
|
230 |
+
positive_words = sum(1 for token in doc if token.sentiment > 0)
|
231 |
+
negative_words = sum(1 for token in doc if token.sentiment < 0)
|
232 |
+
total_words = len(doc)
|
233 |
+
if positive_words > negative_words:
|
234 |
+
return "Positivo"
|
235 |
+
elif negative_words > positive_words:
|
236 |
+
return "Negativo"
|
237 |
+
else:
|
238 |
+
return "Neutral"
|
239 |
+
|
240 |
+
def extract_topics(doc, lang_code):
|
241 |
+
vectorizer = TfidfVectorizer(stop_words='english', max_features=5)
|
242 |
+
tfidf_matrix = vectorizer.fit_transform([doc.text])
|
243 |
+
feature_names = vectorizer.get_feature_names_out()
|
244 |
+
return list(feature_names)
|
245 |
+
|
246 |
+
# Aseg煤rate de que todas las funciones necesarias est茅n exportadas
|
247 |
+
__all__ = [
|
248 |
+
'perform_semantic_analysis',
|
249 |
+
'identify_key_concepts',
|
250 |
+
'create_concept_graph',
|
251 |
+
'visualize_concept_graph',
|
252 |
+
'create_entity_graph',
|
253 |
+
'visualize_entity_graph',
|
254 |
+
'generate_summary',
|
255 |
+
'extract_entities',
|
256 |
+
'analyze_sentiment',
|
257 |
+
'create_topic_graph',
|
258 |
+
'visualize_topic_graph',
|
259 |
+
'extract_topics',
|
260 |
+
'ENTITY_LABELS',
|
261 |
+
'POS_COLORS',
|
262 |
+
'POS_TRANSLATIONS'
|
263 |
]
|