Create semantic_analysis,py
Browse files
modules/text_analysis/semantic_analysis,py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#semantic_analysis.py
|
2 |
+
import streamlit as st
|
3 |
+
import spacy
|
4 |
+
import networkx as nx
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from collections import Counter, defaultdict
|
7 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
8 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
9 |
+
|
10 |
+
# Define colors for grammatical categories
|
11 |
+
POS_COLORS = {
|
12 |
+
'ADJ': '#FFA07A', 'ADP': '#98FB98', 'ADV': '#87CEFA', 'AUX': '#DDA0DD',
|
13 |
+
'CCONJ': '#F0E68C', 'DET': '#FFB6C1', 'INTJ': '#FF6347', 'NOUN': '#90EE90',
|
14 |
+
'NUM': '#FAFAD2', 'PART': '#D3D3D3', 'PRON': '#FFA500', 'PROPN': '#20B2AA',
|
15 |
+
'SCONJ': '#DEB887', 'SYM': '#7B68EE', 'VERB': '#FF69B4', 'X': '#A9A9A9',
|
16 |
+
}
|
17 |
+
|
18 |
+
POS_TRANSLATIONS = {
|
19 |
+
'es': {
|
20 |
+
'ADJ': 'Adjetivo', 'ADP': 'Preposici贸n', 'ADV': 'Adverbio', 'AUX': 'Auxiliar',
|
21 |
+
'CCONJ': 'Conjunci贸n Coordinante', 'DET': 'Determinante', 'INTJ': 'Interjecci贸n',
|
22 |
+
'NOUN': 'Sustantivo', 'NUM': 'N煤mero', 'PART': 'Part铆cula', 'PRON': 'Pronombre',
|
23 |
+
'PROPN': 'Nombre Propio', 'SCONJ': 'Conjunci贸n Subordinante', 'SYM': 'S铆mbolo',
|
24 |
+
'VERB': 'Verbo', 'X': 'Otro',
|
25 |
+
},
|
26 |
+
'en': {
|
27 |
+
'ADJ': 'Adjective', 'ADP': 'Preposition', 'ADV': 'Adverb', 'AUX': 'Auxiliary',
|
28 |
+
'CCONJ': 'Coordinating Conjunction', 'DET': 'Determiner', 'INTJ': 'Interjection',
|
29 |
+
'NOUN': 'Noun', 'NUM': 'Number', 'PART': 'Particle', 'PRON': 'Pronoun',
|
30 |
+
'PROPN': 'Proper Noun', 'SCONJ': 'Subordinating Conjunction', 'SYM': 'Symbol',
|
31 |
+
'VERB': 'Verb', 'X': 'Other',
|
32 |
+
},
|
33 |
+
'fr': {
|
34 |
+
'ADJ': 'Adjectif', 'ADP': 'Pr茅position', 'ADV': 'Adverbe', 'AUX': 'Auxiliaire',
|
35 |
+
'CCONJ': 'Conjonction de Coordination', 'DET': 'D茅terminant', 'INTJ': 'Interjection',
|
36 |
+
'NOUN': 'Nom', 'NUM': 'Nombre', 'PART': 'Particule', 'PRON': 'Pronom',
|
37 |
+
'PROPN': 'Nom Propre', 'SCONJ': 'Conjonction de Subordination', 'SYM': 'Symbole',
|
38 |
+
'VERB': 'Verbe', 'X': 'Autre',
|
39 |
+
}
|
40 |
+
}
|
41 |
+
|
42 |
+
ENTITY_LABELS = {
|
43 |
+
'es': {
|
44 |
+
"Personas": "lightblue",
|
45 |
+
"Lugares": "lightcoral",
|
46 |
+
"Inventos": "lightgreen",
|
47 |
+
"Fechas": "lightyellow",
|
48 |
+
"Conceptos": "lightpink"
|
49 |
+
},
|
50 |
+
'en': {
|
51 |
+
"People": "lightblue",
|
52 |
+
"Places": "lightcoral",
|
53 |
+
"Inventions": "lightgreen",
|
54 |
+
"Dates": "lightyellow",
|
55 |
+
"Concepts": "lightpink"
|
56 |
+
},
|
57 |
+
'fr': {
|
58 |
+
"Personnes": "lightblue",
|
59 |
+
"Lieux": "lightcoral",
|
60 |
+
"Inventions": "lightgreen",
|
61 |
+
"Dates": "lightyellow",
|
62 |
+
"Concepts": "lightpink"
|
63 |
+
}
|
64 |
+
}
|
65 |
+
|
66 |
+
def identify_and_contextualize_entities(doc, lang):
|
67 |
+
entities = []
|
68 |
+
for ent in doc.ents:
|
69 |
+
# Obtener el contexto (3 palabras antes y despu茅s de la entidad)
|
70 |
+
start = max(0, ent.start - 3)
|
71 |
+
end = min(len(doc), ent.end + 3)
|
72 |
+
context = doc[start:end].text
|
73 |
+
|
74 |
+
# Mapear las etiquetas de spaCy a nuestras categor铆as
|
75 |
+
if ent.label_ in ['PERSON', 'ORG']:
|
76 |
+
category = "Personas" if lang == 'es' else "People" if lang == 'en' else "Personnes"
|
77 |
+
elif ent.label_ in ['LOC', 'GPE']:
|
78 |
+
category = "Lugares" if lang == 'es' else "Places" if lang == 'en' else "Lieux"
|
79 |
+
elif ent.label_ in ['PRODUCT']:
|
80 |
+
category = "Inventos" if lang == 'es' else "Inventions" if lang == 'en' else "Inventions"
|
81 |
+
elif ent.label_ in ['DATE', 'TIME']:
|
82 |
+
category = "Fechas" if lang == 'es' else "Dates" if lang == 'en' else "Dates"
|
83 |
+
else:
|
84 |
+
category = "Conceptos" if lang == 'es' else "Concepts" if lang == 'en' else "Concepts"
|
85 |
+
|
86 |
+
entities.append({
|
87 |
+
'text': ent.text,
|
88 |
+
'label': category,
|
89 |
+
'start': ent.start,
|
90 |
+
'end': ent.end,
|
91 |
+
'context': context
|
92 |
+
})
|
93 |
+
|
94 |
+
# Identificar conceptos clave (usando sustantivos y verbos m谩s frecuentes)
|
95 |
+
word_freq = Counter([token.lemma_.lower() for token in doc if token.pos_ in ['NOUN', 'VERB'] and not token.is_stop])
|
96 |
+
key_concepts = word_freq.most_common(10) # Top 10 conceptos clave
|
97 |
+
|
98 |
+
return entities, key_concepts
|
99 |
+
|
100 |
+
def create_concept_graph(text, concepts):
|
101 |
+
vectorizer = TfidfVectorizer()
|
102 |
+
tfidf_matrix = vectorizer.fit_transform([text])
|
103 |
+
concept_vectors = vectorizer.transform(concepts)
|
104 |
+
similarity_matrix = cosine_similarity(concept_vectors, concept_vectors)
|
105 |
+
|
106 |
+
G = nx.Graph()
|
107 |
+
for i, concept in enumerate(concepts):
|
108 |
+
G.add_node(concept)
|
109 |
+
for j in range(i+1, len(concepts)):
|
110 |
+
if similarity_matrix[i][j] > 0.1:
|
111 |
+
G.add_edge(concept, concepts[j], weight=similarity_matrix[i][j])
|
112 |
+
|
113 |
+
return G
|
114 |
+
|
115 |
+
def visualize_concept_graph(G, lang):
|
116 |
+
fig, ax = plt.subplots(figsize=(12, 8))
|
117 |
+
pos = nx.spring_layout(G)
|
118 |
+
|
119 |
+
nx.draw_networkx_nodes(G, pos, node_size=3000, node_color='lightblue', ax=ax)
|
120 |
+
nx.draw_networkx_labels(G, pos, font_size=10, font_weight="bold", ax=ax)
|
121 |
+
nx.draw_networkx_edges(G, pos, width=1, ax=ax)
|
122 |
+
|
123 |
+
edge_labels = nx.get_edge_attributes(G, 'weight')
|
124 |
+
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=8, ax=ax)
|
125 |
+
|
126 |
+
title = {
|
127 |
+
'es': "Relaciones Conceptuales",
|
128 |
+
'en': "Conceptual Relations",
|
129 |
+
'fr': "Relations Conceptuelles"
|
130 |
+
}
|
131 |
+
ax.set_title(title[lang], fontsize=16)
|
132 |
+
ax.axis('off')
|
133 |
+
|
134 |
+
return fig
|
135 |
+
|
136 |
+
def perform_semantic_analysis(text, nlp, lang):
|
137 |
+
doc = nlp(text)
|
138 |
+
|
139 |
+
# Identificar entidades y conceptos clave
|
140 |
+
entities, key_concepts = identify_and_contextualize_entities(doc, lang)
|
141 |
+
|
142 |
+
# Crear y visualizar grafo de conceptos
|
143 |
+
concepts = [concept for concept, _ in key_concepts]
|
144 |
+
concept_graph = create_concept_graph(text, concepts)
|
145 |
+
relations_graph = visualize_concept_graph(concept_graph, lang)
|
146 |
+
|
147 |
+
return {
|
148 |
+
'entities': entities,
|
149 |
+
'key_concepts': key_concepts,
|
150 |
+
'relations_graph': relations_graph
|
151 |
+
}
|
152 |
+
|
153 |
+
__all__ = ['perform_semantic_analysis', 'ENTITY_LABELS', 'POS_TRANSLATIONS']
|