rockerritesh commited on
Commit
195a488
·
verified ·
1 Parent(s): b2aa1a3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -0
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import networkx as nx
3
+ import matplotlib.pyplot as plt
4
+ from neo4j import GraphDatabase
5
+ import io
6
+ import base64
7
+
8
+ class Neo4jGraphVisualizer:
9
+ def __init__(self, uri, username, password):
10
+ """
11
+ Initialize the Neo4j graph database connection
12
+
13
+ Args:
14
+ uri (str): Neo4j database URI
15
+ username (str): Neo4j username
16
+ password (str): Neo4j password
17
+ """
18
+ self.driver = GraphDatabase.driver(uri, auth=(username, password))
19
+
20
+ def fetch_graph_data(self):
21
+ """
22
+ Fetch graph data from Neo4j database
23
+
24
+ Returns:
25
+ dict: A dictionary containing nodes and relationships
26
+ """
27
+ with self.driver.session() as session:
28
+ # Fetch all nodes
29
+ nodes_result = session.run("""
30
+ MATCH (n)
31
+ RETURN ID(n) as id,
32
+ labels(n) as labels,
33
+ properties(n) as properties
34
+ """)
35
+
36
+ # Fetch all relationships
37
+ relationships_result = session.run("""
38
+ MATCH (a)-[r]->(b)
39
+ RETURN
40
+ ID(a) as source_id,
41
+ ID(b) as target_id,
42
+ type(r) as relationship_type
43
+ """)
44
+
45
+ # Process nodes
46
+ nodes = [
47
+ {
48
+ 'id': record['id'],
49
+ 'label': record['labels'][0] if record['labels'] else 'Unknown',
50
+ 'properties': dict(record['properties'])
51
+ }
52
+ for record in nodes_result
53
+ ]
54
+
55
+ # Process relationships
56
+ relationships = [
57
+ {
58
+ 'source': record['source_id'],
59
+ 'target': record['target_id'],
60
+ 'type': record['relationship_type']
61
+ }
62
+ for record in relationships_result
63
+ ]
64
+
65
+ return {'nodes': nodes, 'relationships': relationships}
66
+
67
+ def visualize_graph(self):
68
+ """
69
+ Visualize the graph using NetworkX and Matplotlib
70
+
71
+ Returns:
72
+ str: Base64 encoded image of the graph
73
+ """
74
+ # Fetch graph data
75
+ graph_data = self.fetch_graph_data()
76
+
77
+ # Create NetworkX graph
78
+ G = nx.DiGraph()
79
+
80
+ # Add nodes
81
+ for node in graph_data['nodes']:
82
+ G.add_node(node['id'],
83
+ label=node['label'],
84
+ properties=node['properties'])
85
+
86
+ # Add edges
87
+ for rel in graph_data['relationships']:
88
+ G.add_edge(rel['source'], rel['target'], type=rel['type'])
89
+
90
+ # Visualization
91
+ plt.figure(figsize=(12, 8))
92
+ pos = nx.spring_layout(G, k=0.5) # positions for all nodes
93
+
94
+ # Draw nodes
95
+ nx.draw_networkx_nodes(G, pos,
96
+ node_color='lightblue',
97
+ node_size=300,
98
+ alpha=0.8)
99
+
100
+ # Draw edges
101
+ nx.draw_networkx_edges(G, pos,
102
+ edge_color='gray',
103
+ arrows=True)
104
+
105
+ # Draw labels
106
+ nx.draw_networkx_labels(G, pos,
107
+ labels={node: f"{node}" for node in G.nodes()})
108
+
109
+ plt.title("Neo4j Graph Visualization")
110
+ plt.axis('off')
111
+
112
+ # Save to buffer
113
+ buffer = io.BytesIO()
114
+ plt.savefig(buffer, format='png')
115
+ buffer.seek(0)
116
+ image_png = buffer.getvalue()
117
+ buffer.close()
118
+
119
+ # Encode
120
+ graphic = base64.b64encode(image_png).decode('utf-8')
121
+ return f"data:image/png;base64,{graphic}"
122
+
123
+ def close(self):
124
+ """Close the Neo4j driver connection"""
125
+ self.driver.close()
126
+
127
+ def create_gradio_interface(uri, username, password):
128
+ """
129
+ Create a Gradio interface for Neo4j graph visualization
130
+
131
+ Args:
132
+ uri (str): Neo4j database URI
133
+ username (str): Neo4j username
134
+ password (str): Neo4j password
135
+ """
136
+ visualizer = Neo4jGraphVisualizer(uri, username, password)
137
+
138
+ def visualize_graph():
139
+ try:
140
+ graph_image = visualizer.visualize_graph()
141
+ return graph_image
142
+ except Exception as e:
143
+ return f"Error: {str(e)}"
144
+
145
+ # Create Gradio interface
146
+ iface = gr.Interface(
147
+ fn=visualize_graph,
148
+ inputs=[],
149
+ outputs=gr.Image(type="filepath"),
150
+ title="Neo4j Graph Visualization",
151
+ description="Visualize graph data from Neo4j database"
152
+ )
153
+
154
+ return iface, visualizer
155
+
156
+ # Configuration (replace with your actual Neo4j credentials)
157
+ NEO4J_URI="neo4j+s://b96332bd.databases.neo4j.io"
158
+ NEO4J_USERNAME="neo4j"
159
+ NEO4J_PASSWORD="qviTdN6cw66AjIv6lu7kXcsN4keYPdXc2gAWuIoB8T4"
160
+ AURA_INSTANCEID="b96332bd"
161
+ AURA_INSTANCENAME="Instance01"
162
+
163
+ def main():
164
+ # Create Gradio interface
165
+ interface, visualizer = create_gradio_interface(
166
+ NEO4J_URI,
167
+ NEO4J_USERNAME,
168
+ NEO4J_PASSWORD
169
+ )
170
+
171
+ try:
172
+ # Launch the interface
173
+ interface.launch(share=True)
174
+ except Exception as e:
175
+ print(f"Error launching interface: {e}")
176
+ finally:
177
+ # Ensure driver is closed
178
+ visualizer.close()
179
+
180
+ if __name__ == "__main__":
181
+ main()