AIdeaText commited on
Commit
793b83e
1 Parent(s): 3e5a060

Create semantic_analysis.py

Browse files
modules/text_analysis/semantic_analysis.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import spacy
3
+ import networkx as nx
4
+ import matplotlib.pyplot as plt
5
+ from collections import Counter
6
+ from sklearn.feature_extraction.text import TfidfVectorizer
7
+ from sklearn.metrics.pairwise import cosine_similarity
8
+
9
+ # ... (mantén las definiciones de POS_COLORS, POS_TRANSLATIONS, y ENTITY_LABELS como están)
10
+
11
+ def identify_key_concepts(doc):
12
+ word_freq = Counter([token.lemma_.lower() for token in doc if token.pos_ in ['NOUN', 'VERB'] and not token.is_stop])
13
+ return word_freq.most_common(10) # Top 10 conceptos clave
14
+
15
+ def create_concept_graph(text, concepts):
16
+ vectorizer = TfidfVectorizer()
17
+ tfidf_matrix = vectorizer.fit_transform([text])
18
+ concept_vectors = vectorizer.transform([c[0] for c in concepts])
19
+ similarity_matrix = cosine_similarity(concept_vectors, concept_vectors)
20
+
21
+ G = nx.Graph()
22
+ for i, (concept, weight) in enumerate(concepts):
23
+ G.add_node(concept, weight=weight)
24
+ for j in range(i+1, len(concepts)):
25
+ if similarity_matrix[i][j] > 0.1:
26
+ G.add_edge(concept, concepts[j][0], weight=similarity_matrix[i][j])
27
+
28
+ return G
29
+
30
+ def visualize_concept_graph(G, lang):
31
+ fig, ax = plt.subplots(figsize=(15, 10))
32
+ pos = nx.spring_layout(G, k=0.5, iterations=50)
33
+
34
+ node_sizes = [G.nodes[node]['weight'] * 100 for node in G.nodes()]
35
+ nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='lightblue', alpha=0.8, ax=ax)
36
+ nx.draw_networkx_labels(G, pos, font_size=10, font_weight="bold", ax=ax)
37
+ nx.draw_networkx_edges(G, pos, width=1, alpha=0.5, ax=ax)
38
+
39
+ edge_labels = nx.get_edge_attributes(G, 'weight')
40
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=8, ax=ax)
41
+
42
+ title = {
43
+ 'es': "Relaciones entre Conceptos Clave",
44
+ 'en': "Key Concept Relations",
45
+ 'fr': "Relations entre Concepts Clés"
46
+ }
47
+ ax.set_title(title[lang], fontsize=16)
48
+ ax.axis('off')
49
+
50
+ plt.tight_layout()
51
+ return fig
52
+
53
+ def perform_semantic_analysis(text, nlp, lang):
54
+ doc = nlp(text)
55
+
56
+ # Identificar conceptos clave
57
+ key_concepts = identify_key_concepts(doc)
58
+
59
+ # Crear y visualizar grafo de conceptos
60
+ concept_graph = create_concept_graph(text, key_concepts)
61
+ relations_graph = visualize_concept_graph(concept_graph, lang)
62
+
63
+ return {
64
+ 'key_concepts': key_concepts,
65
+ 'relations_graph': relations_graph
66
+ }
67
+
68
+ __all__ = ['perform_semantic_analysis', 'ENTITY_LABELS', 'POS_TRANSLATIONS']