jaibadachiya commited on
Commit
bdfed26
Β·
verified Β·
1 Parent(s): a5dfac5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -109
app.py CHANGED
@@ -1,17 +1,12 @@
 
1
  import streamlit as st
2
  import spacy
3
  import subprocess
4
  from neo4j import GraphDatabase
5
  import matplotlib.pyplot as plt
6
  import networkx as nx
7
- import logging
8
- from sklearn.feature_extraction.text import TfidfVectorizer
9
- import re
10
 
11
- # Set up logging configuration
12
- logging.basicConfig(level=logging.INFO)
13
-
14
- # Ensure spaCy model is installed
15
  def install_spacy_model():
16
  try:
17
  spacy.load("en_core_web_sm")
@@ -28,107 +23,48 @@ username = "neo4j"
28
  password = "BfZM7YRKpFz1b_V7acAmOtaSQHPU9xK03rJlfPep88g"
29
 
30
  # Connect to Neo4j
31
- driver = None
32
- try:
33
- driver = GraphDatabase.driver(uri, auth=(username, password))
34
- logging.info("βœ… Connected to Neo4j!")
35
-
36
- def close_driver():
37
- if driver:
38
- driver.close()
39
- logging.info("πŸ”’ Neo4j driver closed.")
40
-
41
- def create_entity(tx, name: str):
42
- tx.run("MERGE (e:Entity {name: $name})", name=name)
43
-
44
- def create_relationship(tx, subj: str, pred: str, obj: str):
45
- tx.run("""
46
- MERGE (a:Entity {name: $subj})
47
- MERGE (b:Entity {name: $obj})
48
- MERGE (a)-[:RELATION {name: $pred}]->(b)
49
- """, subj=subj, pred=pred, obj=obj)
50
-
51
- # Text Processing
52
- def load_and_clean_text(file_path: str) -> str:
53
- with open(file_path, 'r', encoding='utf-8') as file:
54
- text = file.read()
55
- text = re.sub(r'\n+', ' ', text)
56
- return re.sub(r'\s+', ' ', text).strip().lower()
57
-
58
- # TF-IDF Filtering
59
- def compute_tfidf_keywords(text: str, top_n=60):
60
- vectorizer = TfidfVectorizer(stop_words='english')
61
- X = vectorizer.fit_transform([text])
62
- scores = zip(vectorizer.get_feature_names_out(), X.toarray()[0])
63
- sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True)
64
- return {word for word, _ in sorted_scores[:top_n]}
65
-
66
- # Triple Extraction
67
- def get_full_phrase(token) -> str:
68
- return ' '.join(tok.text for tok in token.subtree if tok.dep_ != 'punct').strip()
69
-
70
- def extract_rich_triples(doc, tfidf_keywords) -> list:
71
- triples = []
72
- for sent in doc.sents:
73
- subjects = [tok for tok in sent if "subj" in tok.dep_]
74
- objects = [tok for tok in sent if "obj" in tok.dep_]
75
- verbs = [tok for tok in sent if tok.pos_ == "VERB"]
76
- for subj in subjects:
77
- for obj in objects:
78
- for verb in verbs:
79
- s = get_full_phrase(subj)
80
- o = get_full_phrase(obj)
81
- if s.lower() in tfidf_keywords or o.lower() in tfidf_keywords:
82
- triples.append((s, verb.lemma_, o))
83
- return triples
84
-
85
- # Graph Visualization
86
- def visualize_knowledge_graph(triples: list, title: str = "Knowledge Graph"):
87
- G = nx.DiGraph()
88
- for subj, pred, obj in triples:
89
- G.add_node(subj, label='Subject')
90
- G.add_node(obj, label='Object')
91
- G.add_edge(subj, obj, label=pred)
92
-
93
- pos = nx.spring_layout(G, k=1.2, seed=42)
94
- node_colors = ['skyblue' if G.nodes[n]['label'] == 'Subject' else 'lightgreen' for n in G.nodes]
95
-
96
- plt.figure(figsize=(16, 16))
97
- nx.draw(G, pos, with_labels=True, node_size=1200, node_color=node_colors,
98
- font_size=10, font_weight='bold', edge_color='gray', alpha=0.8)
99
- nx.draw_networkx_edge_labels(G, pos, edge_labels={(u, v): d['label'] for u, v, d in G.edges(data=True)},
100
- font_size=8, font_color='red')
101
- plt.title(title, fontsize=20)
102
- plt.show()
103
-
104
- # === Main Execution ===
105
- file_path = r'C:\Users\jaiba\Desktop\KNOWLEDGE GRAPH\data2.txt'
106
- text = load_and_clean_text(file_path)
107
- tfidf_keywords = compute_tfidf_keywords(text)
108
 
 
 
109
  doc = nlp(text)
110
-
111
- triples = extract_rich_triples(doc, tfidf_keywords)
112
- logging.info(f"🧠 Extracted {len(triples)} filtered triples.")
113
- for t in triples[:10]: # Print only the top 10 triplets
114
- print("πŸ”—", t)
115
-
116
- # === Push to Neo4j ===
117
- with driver.session() as session:
118
- for subj, pred, obj in triples:
119
- session.execute_write(create_entity, subj)
120
- session.execute_write(create_entity, obj)
121
- session.execute_write(create_relationship, subj, pred, obj)
122
-
123
- logging.info("πŸ“‘ Triples successfully stored in Neo4j.")
124
- print("πŸ“‘ Triples successfully stored in Neo4j.")
125
-
126
- # === Final Visualization ===
127
- visualize_knowledge_graph(triples, title="Filtered Knowledge Graph (TF-IDF)")
128
-
129
- except Exception as e:
130
- logging.error(f"❌ An error occurred: {e}", exc_info=True)
131
-
132
- finally:
133
- if driver:
134
- close_driver()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
  import streamlit as st
3
  import spacy
4
  import subprocess
5
  from neo4j import GraphDatabase
6
  import matplotlib.pyplot as plt
7
  import networkx as nx
 
 
 
8
 
9
+ # === Ensure spaCy model is installed ===
 
 
 
10
  def install_spacy_model():
11
  try:
12
  spacy.load("en_core_web_sm")
 
23
  password = "BfZM7YRKpFz1b_V7acAmOtaSQHPU9xK03rJlfPep88g"
24
 
25
  # Connect to Neo4j
26
+ driver = GraphDatabase.driver(uri, auth=(username, password))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ # Triple extraction function
29
+ def extract_triples(text):
30
  doc = nlp(text)
31
+ triples = []
32
+ for sent in doc.sents:
33
+ subjects = [tok for tok in sent if "subj" in tok.dep_]
34
+ verbs = [tok for tok in sent if tok.pos_ == "VERB"]
35
+ objects = [tok for tok in sent if "obj" in tok.dep_]
36
+ for subj in subjects:
37
+ for verb in verbs:
38
+ for obj in objects:
39
+ triples.append((subj.text, verb.lemma_, obj.text))
40
+ if len(triples) == 10:
41
+ return triples
42
+ return triples
43
+
44
+ # Visualization function
45
+ def show_graph(triples):
46
+ G = nx.DiGraph()
47
+ for s, p, o in triples:
48
+ G.add_node(s)
49
+ G.add_node(o)
50
+ G.add_edge(s, o, label=p)
51
+ pos = nx.spring_layout(G)
52
+ plt.figure(figsize=(10, 8))
53
+ nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=2000, font_size=10)
54
+ nx.draw_networkx_edge_labels(G, pos, edge_labels={(u,v):d['label'] for u,v,d in G.edges(data=True)})
55
+ st.pyplot(plt)
56
+
57
+ # === Streamlit UI ===
58
+ st.title("🧠 Knowledge Graph Generator")
59
+
60
+ text_input = st.text_area("Paste your text here", height=200)
61
+
62
+ if st.button("Generate Graph"):
63
+ if text_input:
64
+ triples = extract_triples(text_input)
65
+ st.write("### Extracted Triples")
66
+ for t in triples:
67
+ st.write("πŸ”—", t)
68
+ show_graph(triples)
69
+ else:
70
+ st.warning("Please enter some text.")