|
import streamlit as st |
|
import spacy |
|
import networkx as nx |
|
import matplotlib.pyplot as plt |
|
from collections import Counter |
|
from sklearn.feature_extraction.text import TfidfVectorizer |
|
from sklearn.metrics.pairwise import cosine_similarity |
|
|
|
|
|
|
|
def identify_key_concepts(doc): |
|
word_freq = Counter([token.lemma_.lower() for token in doc if token.pos_ in ['NOUN', 'VERB'] and not token.is_stop]) |
|
return word_freq.most_common(10) |
|
|
|
def create_concept_graph(text, concepts): |
|
vectorizer = TfidfVectorizer() |
|
tfidf_matrix = vectorizer.fit_transform([text]) |
|
concept_vectors = vectorizer.transform([c[0] for c in concepts]) |
|
similarity_matrix = cosine_similarity(concept_vectors, concept_vectors) |
|
|
|
G = nx.Graph() |
|
for i, (concept, weight) in enumerate(concepts): |
|
G.add_node(concept, weight=weight) |
|
for j in range(i+1, len(concepts)): |
|
if similarity_matrix[i][j] > 0.1: |
|
G.add_edge(concept, concepts[j][0], weight=similarity_matrix[i][j]) |
|
|
|
return G |
|
|
|
def visualize_concept_graph(G, lang): |
|
fig, ax = plt.subplots(figsize=(15, 10)) |
|
pos = nx.spring_layout(G, k=0.5, iterations=50) |
|
|
|
node_sizes = [G.nodes[node]['weight'] * 100 for node in G.nodes()] |
|
nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='lightblue', alpha=0.8, ax=ax) |
|
nx.draw_networkx_labels(G, pos, font_size=10, font_weight="bold", ax=ax) |
|
nx.draw_networkx_edges(G, pos, width=1, alpha=0.5, ax=ax) |
|
|
|
edge_labels = nx.get_edge_attributes(G, 'weight') |
|
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=8, ax=ax) |
|
|
|
title = { |
|
'es': "Relaciones entre Conceptos Clave", |
|
'en': "Key Concept Relations", |
|
'fr': "Relations entre Concepts Clés" |
|
} |
|
ax.set_title(title[lang], fontsize=16) |
|
ax.axis('off') |
|
|
|
plt.tight_layout() |
|
return fig |
|
|
|
def perform_semantic_analysis(text, nlp, lang): |
|
doc = nlp(text) |
|
|
|
|
|
key_concepts = identify_key_concepts(doc) |
|
|
|
|
|
concept_graph = create_concept_graph(text, key_concepts) |
|
relations_graph = visualize_concept_graph(concept_graph, lang) |
|
|
|
return { |
|
'key_concepts': key_concepts, |
|
'relations_graph': relations_graph |
|
} |
|
|
|
__all__ = ['perform_semantic_analysis', 'ENTITY_LABELS', 'POS_TRANSLATIONS'] |