Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import spacy
|
| 4 |
+
from neo4j import GraphDatabase
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import networkx as nx
|
| 7 |
+
|
| 8 |
+
# Neo4j credentials
|
| 9 |
+
uri = "neo4j+s://ff701b1c.databases.neo4j.io"
|
| 10 |
+
username = "neo4j"
|
| 11 |
+
password = "your_neo4j_password_here"
|
| 12 |
+
|
| 13 |
+
# Connect to Neo4j
|
| 14 |
+
driver = GraphDatabase.driver(uri, auth=(username, password))
|
| 15 |
+
|
| 16 |
+
def extract_triples(text):
|
| 17 |
+
nlp = spacy.load("en_core_web_sm")
|
| 18 |
+
doc = nlp(text)
|
| 19 |
+
triples = []
|
| 20 |
+
for sent in doc.sents:
|
| 21 |
+
subjects = [tok for tok in sent if "subj" in tok.dep_]
|
| 22 |
+
verbs = [tok for tok in sent if tok.pos_ == "VERB"]
|
| 23 |
+
objects = [tok for tok in sent if "obj" in tok.dep_]
|
| 24 |
+
for subj in subjects:
|
| 25 |
+
for verb in verbs:
|
| 26 |
+
for obj in objects:
|
| 27 |
+
triples.append((subj.text, verb.lemma_, obj.text))
|
| 28 |
+
return triples
|
| 29 |
+
|
| 30 |
+
def show_graph(triples):
|
| 31 |
+
G = nx.DiGraph()
|
| 32 |
+
for s, p, o in triples:
|
| 33 |
+
G.add_node(s)
|
| 34 |
+
G.add_node(o)
|
| 35 |
+
G.add_edge(s, o, label=p)
|
| 36 |
+
pos = nx.spring_layout(G)
|
| 37 |
+
plt.figure(figsize=(10, 8))
|
| 38 |
+
nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=2000, font_size=10)
|
| 39 |
+
nx.draw_networkx_edge_labels(G, pos, edge_labels={(u,v):d['label'] for u,v,d in G.edges(data=True)})
|
| 40 |
+
st.pyplot(plt)
|
| 41 |
+
|
| 42 |
+
# === Streamlit UI ===
|
| 43 |
+
st.title("🧠 Knowledge Graph Generator")
|
| 44 |
+
|
| 45 |
+
text_input = st.text_area("Paste your text here", height=200)
|
| 46 |
+
|
| 47 |
+
if st.button("Generate Graph"):
|
| 48 |
+
if text_input:
|
| 49 |
+
triples = extract_triples(text_input)
|
| 50 |
+
st.write("### Extracted Triples")
|
| 51 |
+
for t in triples:
|
| 52 |
+
st.write("🔗", t)
|
| 53 |
+
show_graph(triples)
|
| 54 |
+
else:
|
| 55 |
+
st.warning("Please enter some text.")
|