imranjamal commited on
Commit
3f051c6
·
verified ·
1 Parent(s): af24f5d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -0
app.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import networkx as nx
3
+ import matplotlib.pyplot as plt
4
+ from io import BytesIO
5
+
6
+ # Function to build and visualize a knowledge graph
7
+ def visualize_knowledge_graph(entities, relationships):
8
+ G = nx.DiGraph()
9
+
10
+ # Add entities as nodes
11
+ for entity in entities.split(","):
12
+ G.add_node(entity.strip())
13
+
14
+ # Add relationships as edges
15
+ for relationship in relationships.split(";"):
16
+ try:
17
+ source, target, label = map(str.strip, relationship.split(","))
18
+ G.add_edge(source, target, label=label)
19
+ except ValueError:
20
+ return "Invalid relationship format. Use 'entity1,entity2,label' format for each relationship."
21
+
22
+ # Plot the graph
23
+ plt.figure(figsize=(10, 6))
24
+ pos = nx.spring_layout(G)
25
+ nx.draw(G, pos, with_labels=True, node_size=3000, node_color="lightblue", font_size=10, font_weight="bold")
26
+ edge_labels = nx.get_edge_attributes(G, 'label')
27
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color="red")
28
+ buf = BytesIO()
29
+ plt.savefig(buf, format="png")
30
+ plt.close()
31
+ buf.seek(0)
32
+ return buf
33
+
34
+ # Define the Gradio interface
35
+ with gr.Blocks() as demo:
36
+ gr.Markdown("## Knowledge Graph Builder")
37
+ gr.Markdown("Enter entities (comma-separated) and relationships (in the format `entity1,entity2,label` separated by semicolons).")
38
+
39
+ entities_input = gr.Textbox(label="Entities (Comma-separated)", placeholder="e.g., SCIEKore, AI, Education")
40
+ relationships_input = gr.Textbox(label="Relationships (Semicolon-separated)", placeholder="e.g., SCIEKore,AI,uses; SCIEKore,Education,offers")
41
+
42
+ output_image = gr.Image(label="Knowledge Graph")
43
+
44
+ submit_button = gr.Button("Build Graph")
45
+ submit_button.click(
46
+ visualize_knowledge_graph,
47
+ inputs=[entities_input, relationships_input],
48
+ outputs=output_image
49
+ )
50
+
51
+ # Launch the Gradio app
52
+ if __name__ == "__main__":
53
+ demo.launch()