Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import networkx as nx
|
| 3 |
+
from pyvis.network import Network
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Streamlit app layout
|
| 8 |
+
st.title("Interactive Graph Visualization")
|
| 9 |
+
st.write("Upload a JSON file containing nodes and edges to display the graph.")
|
| 10 |
+
|
| 11 |
+
# File upload
|
| 12 |
+
uploaded_file = st.file_uploader("Upload JSON file", type=["json"])
|
| 13 |
+
|
| 14 |
+
if uploaded_file is not None:
|
| 15 |
+
try:
|
| 16 |
+
# Load JSON data
|
| 17 |
+
graph_data = json.load(uploaded_file)
|
| 18 |
+
|
| 19 |
+
# Function to create a NetworkX graph from data
|
| 20 |
+
def create_graph(data):
|
| 21 |
+
G = nx.DiGraph()
|
| 22 |
+
for node in data.get("nodes", []):
|
| 23 |
+
G.add_node(node["id"], label=node.get("label", node["id"]))
|
| 24 |
+
for edge in data.get("edges", []):
|
| 25 |
+
G.add_edge(edge["source"], edge["target"], label=edge.get("label", ""))
|
| 26 |
+
return G
|
| 27 |
+
|
| 28 |
+
# Generate the graph
|
| 29 |
+
graph = create_graph(graph_data)
|
| 30 |
+
|
| 31 |
+
# Function to create a pyvis network from NetworkX graph
|
| 32 |
+
def create_pyvis_graph(G):
|
| 33 |
+
net = Network(height="600px", width="100%", directed=True)
|
| 34 |
+
for node, data in G.nodes(data=True):
|
| 35 |
+
net.add_node(node, label=data.get("label", node))
|
| 36 |
+
for source, target, data in G.edges(data=True):
|
| 37 |
+
net.add_edge(source, target, title=data.get("label", ""))
|
| 38 |
+
return net
|
| 39 |
+
|
| 40 |
+
# Create the Pyvis graph
|
| 41 |
+
pyvis_graph = create_pyvis_graph(graph)
|
| 42 |
+
|
| 43 |
+
# Save and display the graph
|
| 44 |
+
output_file = "graph.html"
|
| 45 |
+
pyvis_graph.show(output_file)
|
| 46 |
+
|
| 47 |
+
# Display the graph in Streamlit
|
| 48 |
+
st.components.v1.html(open(output_file, "r").read(), height=600, width=800)
|
| 49 |
+
|
| 50 |
+
# Clean up the temporary file
|
| 51 |
+
if os.path.exists(output_file):
|
| 52 |
+
os.remove(output_file)
|
| 53 |
+
except Exception as e:
|
| 54 |
+
st.error(f"Error processing the file: {e}")
|
| 55 |
+
else:
|
| 56 |
+
st.info("Please upload a JSON file to display the graph.")
|