rockerritesh commited on
Commit
d2b6669
·
verified ·
1 Parent(s): c902f1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -55
app.py CHANGED
@@ -25,21 +25,22 @@ class Neo4jGraphVisualizer:
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
@@ -57,7 +58,8 @@ class Neo4jGraphVisualizer:
57
  {
58
  'source': record['source_id'],
59
  'target': record['target_id'],
60
- 'type': record['relationship_type']
 
61
  }
62
  for record in relationships_result
63
  ]
@@ -71,54 +73,69 @@ class Neo4jGraphVisualizer:
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"""
@@ -170,7 +187,7 @@ def main():
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:
 
25
  dict: A dictionary containing nodes and relationships
26
  """
27
  with self.driver.session() as session:
28
+ # Fetch all nodes with elementId instead of deprecated ID()
29
  nodes_result = session.run("""
30
  MATCH (n)
31
+ RETURN elementId(n) as id,
32
  labels(n) as labels,
33
  properties(n) as properties
34
  """)
35
 
36
+ # Fetch all relationships using elementId
37
  relationships_result = session.run("""
38
  MATCH (a)-[r]->(b)
39
  RETURN
40
+ elementId(a) as source_id,
41
+ elementId(b) as target_id,
42
+ type(r) as relationship_type,
43
+ properties(r) as relationship_properties
44
  """)
45
 
46
  # Process nodes
 
58
  {
59
  'source': record['source_id'],
60
  'target': record['target_id'],
61
+ 'type': record['relationship_type'],
62
+ 'properties': dict(record.get('relationship_properties', {}))
63
  }
64
  for record in relationships_result
65
  ]
 
73
  Returns:
74
  str: Base64 encoded image of the graph
75
  """
76
+ try:
77
+ # Fetch graph data
78
+ graph_data = self.fetch_graph_data()
79
+
80
+ # Create NetworkX graph
81
+ G = nx.DiGraph()
82
+
83
+ # Add nodes
84
+ for node in graph_data['nodes']:
85
+ # Use node's label or properties for display
86
+ label = node.get('properties', {}).get('name', str(node['id']))
87
+ G.add_node(node['id'],
88
+ label=label,
89
+ properties=node['properties'])
90
+
91
+ # Add edges
92
+ for rel in graph_data['relationships']:
93
+ G.add_edge(rel['source'], rel['target'],
94
+ type=rel['type'],
95
+ properties=rel['properties'])
96
+
97
+ # Visualization
98
+ plt.figure(figsize=(16, 12))
99
+ pos = nx.spring_layout(G, k=0.9, iterations=50) # Improved layout
100
+
101
+ # Draw nodes with color and size based on properties
102
+ node_sizes = [300 + len(str(G.nodes[node]['properties'])) * 10 for node in G.nodes()]
103
+ node_colors = ['lightblue' if idx % 2 == 0 else 'lightgreen' for idx in range(len(G.nodes()))]
104
+
105
+ nx.draw_networkx_nodes(G, pos,
106
+ node_color=node_colors,
107
+ node_size=node_sizes,
108
+ alpha=0.8)
109
+
110
+ # Draw edges
111
+ nx.draw_networkx_edges(G, pos,
112
+ edge_color='gray',
113
+ arrows=True,
114
+ width=1.5)
115
+
116
+ # Draw labels
117
+ nx.draw_networkx_labels(G, pos,
118
+ labels={node: G.nodes[node]['label'] for node in G.nodes()},
119
+ font_size=8)
120
+
121
+ plt.title("Neo4j Graph Visualization")
122
+ plt.axis('off')
123
+
124
+ # Save to buffer
125
+ buffer = io.BytesIO()
126
+ plt.savefig(buffer, format='png', dpi=300, bbox_inches='tight')
127
+ buffer.seek(0)
128
+ image_png = buffer.getvalue()
129
+ buffer.close()
130
+ plt.close() # Close the plot to free memory
131
+
132
+ # Encode
133
+ graphic = base64.b64encode(image_png).decode('utf-8')
134
+ return f"data:image/png;base64,{graphic}"
135
 
136
+ except Exception as e:
137
+ print(f"Error in graph visualization: {e}")
138
+ return f"Error visualizing graph: {e}"
139
 
140
  def close(self):
141
  """Close the Neo4j driver connection"""
 
187
 
188
  try:
189
  # Launch the interface
190
+ interface.launch(server_name='0.0.0.0', server_port=7860)
191
  except Exception as e:
192
  print(f"Error launching interface: {e}")
193
  finally: