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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import tempfile
|
| 5 |
+
import networkx as nx
|
| 6 |
+
import seaborn as sns
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import random
|
| 9 |
+
import colorsys
|
| 10 |
+
from community import community_louvain
|
| 11 |
+
from pyvis.network import Network
|
| 12 |
+
import gradio as gr
|
| 13 |
+
|
| 14 |
+
def parse_graph_data(file):
|
| 15 |
+
try:
|
| 16 |
+
file_extension = os.path.splitext(file.name)[1].lower()
|
| 17 |
+
|
| 18 |
+
if file_extension == '.json':
|
| 19 |
+
with open(file.name, 'r', encoding='utf-8') as f:
|
| 20 |
+
data = json.load(f)
|
| 21 |
+
|
| 22 |
+
if isinstance(data, dict) and 'nodes' in data and 'edges' in data:
|
| 23 |
+
return data['nodes'], data['edges'], None
|
| 24 |
+
else:
|
| 25 |
+
return None, None, "Invalid JSON format. Expected {'nodes': [...], 'edges': [...]}"
|
| 26 |
+
|
| 27 |
+
elif file_extension == '.txt':
|
| 28 |
+
with open(file.name, 'r', encoding='utf-8') as f:
|
| 29 |
+
content = f.read()
|
| 30 |
+
|
| 31 |
+
# Try to extract JSON from the text content
|
| 32 |
+
try:
|
| 33 |
+
import re
|
| 34 |
+
json_match = re.search(r'```json\s*(.*?)\s*```', content, re.DOTALL)
|
| 35 |
+
if json_match:
|
| 36 |
+
content = json_match.group(1)
|
| 37 |
+
|
| 38 |
+
content = content.strip()
|
| 39 |
+
if not content.startswith('{'):
|
| 40 |
+
content = '{' + content
|
| 41 |
+
if not content.endswith('}'):
|
| 42 |
+
content = content + '}'
|
| 43 |
+
|
| 44 |
+
data = json.loads(content)
|
| 45 |
+
if 'nodes' in data and 'edges' in data:
|
| 46 |
+
return data['nodes'], data['edges'], None
|
| 47 |
+
else:
|
| 48 |
+
return None, None, "Text file does not contain valid graph data structure."
|
| 49 |
+
except json.JSONDecodeError as e:
|
| 50 |
+
return None, None, f"Failed to parse JSON from text file: {str(e)}"
|
| 51 |
+
else:
|
| 52 |
+
return None, None, "Unsupported file format. Please upload .json or .txt files."
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return None, None, f"Error processing file: {str(e)}"
|
| 55 |
+
|
| 56 |
+
def create_graph_and_detect_communities(nodes, edges):
|
| 57 |
+
"""
|
| 58 |
+
Builds a NetworkX graph from the given nodes/edges,
|
| 59 |
+
then computes a community partition. We store the
|
| 60 |
+
community in a separate attribute 'community' so
|
| 61 |
+
we don't overwrite the original 'group'.
|
| 62 |
+
"""
|
| 63 |
+
G = nx.Graph()
|
| 64 |
+
|
| 65 |
+
for node in nodes:
|
| 66 |
+
label = node.get('label', f"Node_{node['id']}")
|
| 67 |
+
group = node.get('group', 'Default')
|
| 68 |
+
G.add_node(node["id"], label=label, group=group)
|
| 69 |
+
|
| 70 |
+
for edge in edges:
|
| 71 |
+
if 'from' in edge and 'to' in edge:
|
| 72 |
+
G.add_edge(edge["from"], edge["to"], label=edge.get('label', ''))
|
| 73 |
+
|
| 74 |
+
# Detect communities (optional)
|
| 75 |
+
partition = community_louvain.best_partition(G)
|
| 76 |
+
for node_id, comm_id in partition.items():
|
| 77 |
+
# Store the community ID separately
|
| 78 |
+
G.nodes[node_id]['community'] = comm_id
|
| 79 |
+
|
| 80 |
+
return G
|
| 81 |
+
|
| 82 |
+
def get_distinct_colors(n, saturation=0.7, value=0.9):
|
| 83 |
+
"""Generate n visually distinct colors with variation in hue, saturation, and value."""
|
| 84 |
+
colors = []
|
| 85 |
+
for i in range(n):
|
| 86 |
+
hue = (i * 0.618033988749895) % 1
|
| 87 |
+
sat = saturation - 0.1 * (i % 3)
|
| 88 |
+
val = value - 0.05 * ((i + 1) % 4)
|
| 89 |
+
r, g, b = colorsys.hsv_to_rgb(hue, sat, val)
|
| 90 |
+
color = f"#{int(255*r):02x}{int(255*g):02x}{int(255*b):02x}"
|
| 91 |
+
colors.append(color)
|
| 92 |
+
return colors
|
| 93 |
+
|
| 94 |
+
def generate_edge_colors(edges):
|
| 95 |
+
unique_labels = list(set(edge.get('label', '') for edge in edges))
|
| 96 |
+
palette = get_distinct_colors(max(len(unique_labels), 1))
|
| 97 |
+
return {label: color for label, color in zip(unique_labels, palette)}
|
| 98 |
+
|
| 99 |
+
def generate_node_colors(nodes):
|
| 100 |
+
"""
|
| 101 |
+
Generate distinct colors for each unique 'group' in the original
|
| 102 |
+
node data. This ensures that, for example, 'Entity', 'Event', and
|
| 103 |
+
'Concept' each get their own color.
|
| 104 |
+
"""
|
| 105 |
+
unique_groups = list(set(node.get('group', 'Default') for node in nodes))
|
| 106 |
+
|
| 107 |
+
# If there's only 1 group, you can keep them all the same color or create multiple shades
|
| 108 |
+
if len(unique_groups) == 1:
|
| 109 |
+
palette = get_distinct_colors(min(len(nodes), 10))
|
| 110 |
+
else:
|
| 111 |
+
palette = get_distinct_colors(len(unique_groups))
|
| 112 |
+
|
| 113 |
+
return {group: color for group, color in zip(unique_groups, palette)}
|
| 114 |
+
|
| 115 |
+
def visualize_graph(G, edges, label_color_map, group_color_map, output_file, title="Knowledge Graph"):
|
| 116 |
+
net = Network(
|
| 117 |
+
notebook=True,
|
| 118 |
+
cdn_resources="in_line",
|
| 119 |
+
height="1350px",
|
| 120 |
+
width="100%",
|
| 121 |
+
select_menu=True,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
# PyVis config for a white background
|
| 125 |
+
net.set_options("""
|
| 126 |
+
{
|
| 127 |
+
"physics": {
|
| 128 |
+
"forceAtlas2Based": {
|
| 129 |
+
"gravitationalConstant": -600,
|
| 130 |
+
"centralGravity": 0.015,
|
| 131 |
+
"springLength": 300,
|
| 132 |
+
"springConstant": 0.08,
|
| 133 |
+
"damping": 0.9,
|
| 134 |
+
"avoidOverlap": 1.5
|
| 135 |
+
},
|
| 136 |
+
"solver": "forceAtlas2Based",
|
| 137 |
+
"stabilization": {
|
| 138 |
+
"enabled": true,
|
| 139 |
+
"iterations": 1000,
|
| 140 |
+
"updateInterval": 25
|
| 141 |
+
}
|
| 142 |
+
},
|
| 143 |
+
"nodes": {
|
| 144 |
+
"font": {
|
| 145 |
+
"size": 16,
|
| 146 |
+
"face": "Tahoma"
|
| 147 |
+
},
|
| 148 |
+
"shadow": {
|
| 149 |
+
"enabled": true
|
| 150 |
+
}
|
| 151 |
+
},
|
| 152 |
+
"edges": {
|
| 153 |
+
"smooth": {
|
| 154 |
+
"type": "continuous",
|
| 155 |
+
"forceDirection": "none"
|
| 156 |
+
},
|
| 157 |
+
"color": {
|
| 158 |
+
"inherit": false
|
| 159 |
+
},
|
| 160 |
+
"shadow": {
|
| 161 |
+
"enabled": true
|
| 162 |
+
},
|
| 163 |
+
"font": {
|
| 164 |
+
"size": 12,
|
| 165 |
+
"face": "Tahoma"
|
| 166 |
+
}
|
| 167 |
+
},
|
| 168 |
+
"interaction": {
|
| 169 |
+
"hover": true,
|
| 170 |
+
"navigationButtons": true,
|
| 171 |
+
"keyboard": {
|
| 172 |
+
"enabled": true
|
| 173 |
+
},
|
| 174 |
+
"tooltipDelay": 200
|
| 175 |
+
},
|
| 176 |
+
"background": {
|
| 177 |
+
"color": "#ffffff"
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
""")
|
| 181 |
+
|
| 182 |
+
# Add nodes
|
| 183 |
+
for node_id, node_data in G.nodes(data=True):
|
| 184 |
+
label = node_data.get('label', f"Node_{node_id}")
|
| 185 |
+
group = node_data.get('group', 'Default')
|
| 186 |
+
color = group_color_map.get(group, '#CCCCCC')
|
| 187 |
+
size = max(20, min(50, G.degree[node_id] * 2))
|
| 188 |
+
|
| 189 |
+
net.add_node(
|
| 190 |
+
node_id,
|
| 191 |
+
label=label,
|
| 192 |
+
title=label,
|
| 193 |
+
color=color,
|
| 194 |
+
size=size
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
# Add edges
|
| 198 |
+
for edge in edges:
|
| 199 |
+
if 'from' in edge and 'to' in edge:
|
| 200 |
+
edge_label = edge.get('label', '')
|
| 201 |
+
edge_color = label_color_map.get(edge_label, '#888888')
|
| 202 |
+
|
| 203 |
+
net.add_edge(
|
| 204 |
+
edge['from'],
|
| 205 |
+
edge['to'],
|
| 206 |
+
label=edge_label,
|
| 207 |
+
title=edge_label,
|
| 208 |
+
color=edge_color,
|
| 209 |
+
arrows="to"
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
net.show(output_file)
|
| 213 |
+
|
| 214 |
+
# Minimal CSS/JS injection for adaptive theme (no doc panel, no toggle)
|
| 215 |
+
theme_css = """
|
| 216 |
+
<style>
|
| 217 |
+
:root {
|
| 218 |
+
--bg-color: #FFFFFF;
|
| 219 |
+
--text-color: #000000;
|
| 220 |
+
--panel-bg: #F5F5F5;
|
| 221 |
+
--panel-border: #CCCCCC;
|
| 222 |
+
--node-border: #333333;
|
| 223 |
+
--edge-color: #666666;
|
| 224 |
+
--highlight-color: #3498db;
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
@media (prefers-color-scheme: dark) {
|
| 228 |
+
:root {
|
| 229 |
+
--bg-color: #1E1E1E;
|
| 230 |
+
--text-color: #FFFFFF;
|
| 231 |
+
--panel-bg: #2D2D2D;
|
| 232 |
+
--panel-border: #444444;
|
| 233 |
+
--node-border: #888888;
|
| 234 |
+
--edge-color: #AAAAAA;
|
| 235 |
+
--highlight-color: #3498db;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
body, #mynetwork {
|
| 239 |
+
background-color: #FFFFFF !important;
|
| 240 |
+
color: #000000 !important;
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
.vis-label {
|
| 244 |
+
color: var(--text-color) !important;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
.vis-tooltip, .vis-network-tooltip {
|
| 248 |
+
background-color: var(--panel-bg) !important;
|
| 249 |
+
color: var(--text-color) !important;
|
| 250 |
+
border-color: var(--panel-border) !important;
|
| 251 |
+
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
.vis-button {
|
| 255 |
+
background-color: var(--panel-bg) !important;
|
| 256 |
+
color: var(--text-color) !important;
|
| 257 |
+
border-color: var(--panel-border) !important;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
.vis-navigation {
|
| 261 |
+
background-color: var(--panel-bg) !important;
|
| 262 |
+
border-color: var(--panel-border) !important;
|
| 263 |
+
}
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
@media (prefers-color-scheme: light) {
|
| 267 |
+
body, #mynetwork {
|
| 268 |
+
background-color: var(--bg-color) !important;
|
| 269 |
+
color: var(--text-color) !important;
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
.vis-label {
|
| 273 |
+
color: var(--text-color) !important;
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
.vis-tooltip, .vis-network-tooltip {
|
| 277 |
+
background-color: var(--panel-bg) !important;
|
| 278 |
+
color: var(--text-color) !important;
|
| 279 |
+
border-color: var(--panel-border) !important;
|
| 280 |
+
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
|
| 281 |
+
}
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
body {
|
| 285 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
| 286 |
+
margin: 0;
|
| 287 |
+
padding: 0;
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
#mynetwork {
|
| 291 |
+
width: 100%;
|
| 292 |
+
height: 80vh;
|
| 293 |
+
border: 1px solid #cccccc;
|
| 294 |
+
border-radius: 8px;
|
| 295 |
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
#mynetwork:hover {
|
| 299 |
+
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
.vis-tooltip, .vis-network-tooltip {
|
| 303 |
+
border-radius: 4px;
|
| 304 |
+
padding: 8px 12px;
|
| 305 |
+
font-size: 14px;
|
| 306 |
+
max-width: 250px;
|
| 307 |
+
z-index: 1000;
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
.vis-button {
|
| 311 |
+
transition: background-color 0.2s ease;
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
.vis-button:hover {
|
| 315 |
+
background-color: var(--highlight-color) !important;
|
| 316 |
+
color: white !important;
|
| 317 |
+
}
|
| 318 |
+
</style>
|
| 319 |
+
|
| 320 |
+
<script>
|
| 321 |
+
// Minimal script to set default theme
|
| 322 |
+
document.addEventListener("DOMContentLoaded", function() {
|
| 323 |
+
document.documentElement.setAttribute(
|
| 324 |
+
'data-theme',
|
| 325 |
+
window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
| 326 |
+
);
|
| 327 |
+
});
|
| 328 |
+
</script>
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
with open(output_file, "r", encoding="utf-8") as f:
|
| 332 |
+
html_content = f.read()
|
| 333 |
+
|
| 334 |
+
# Inject the minimal CSS/JS (no doc panel or toggles)
|
| 335 |
+
if "<head>" in html_content:
|
| 336 |
+
html_content = html_content.replace("<head>", "<head>" + theme_css)
|
| 337 |
+
else:
|
| 338 |
+
html_content = theme_css + html_content
|
| 339 |
+
|
| 340 |
+
# Set the HTML title
|
| 341 |
+
if "<title>" in html_content:
|
| 342 |
+
html_content = html_content.replace("<title>", f"<title>{title} - Interactive Visualization")
|
| 343 |
+
|
| 344 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
| 345 |
+
f.write(html_content)
|
| 346 |
+
|
| 347 |
+
return output_file
|
| 348 |
+
|
| 349 |
+
def get_graph_html(nodes, edges, title="Knowledge Graph"):
|
| 350 |
+
"""Generate HTML visualization of the graph and return it as a string."""
|
| 351 |
+
if not nodes or not edges:
|
| 352 |
+
return "No valid graph data available."
|
| 353 |
+
|
| 354 |
+
fd, temp_path = tempfile.mkstemp(suffix='.html')
|
| 355 |
+
os.close(fd)
|
| 356 |
+
|
| 357 |
+
try:
|
| 358 |
+
# Build the graph
|
| 359 |
+
G = create_graph_and_detect_communities(nodes, edges)
|
| 360 |
+
|
| 361 |
+
# Generate color maps
|
| 362 |
+
label_color_map = generate_edge_colors(edges)
|
| 363 |
+
group_color_map = generate_node_colors(nodes)
|
| 364 |
+
|
| 365 |
+
# Visualize the graph
|
| 366 |
+
visualize_graph(G, edges, label_color_map, group_color_map, temp_path, title)
|
| 367 |
+
|
| 368 |
+
with open(temp_path, 'r', encoding='utf-8') as f:
|
| 369 |
+
html_content = f.read()
|
| 370 |
+
|
| 371 |
+
return html_content
|
| 372 |
+
finally:
|
| 373 |
+
try:
|
| 374 |
+
os.remove(temp_path)
|
| 375 |
+
except:
|
| 376 |
+
pass
|
| 377 |
+
|
| 378 |
+
def process_graph_file(file):
|
| 379 |
+
"""Process uploaded graph file and generate visualization."""
|
| 380 |
+
if not file:
|
| 381 |
+
return "No file uploaded. Please upload a JSON or text file.", None, None
|
| 382 |
+
|
| 383 |
+
# Parse the graph data
|
| 384 |
+
nodes, edges, error = parse_graph_data(file)
|
| 385 |
+
|
| 386 |
+
if error:
|
| 387 |
+
return error, None, None
|
| 388 |
+
|
| 389 |
+
if not nodes or not edges:
|
| 390 |
+
return "File does not contain valid graph data. Ensure it has 'nodes' and 'edges'.", None, None
|
| 391 |
+
|
| 392 |
+
num_nodes = len(nodes)
|
| 393 |
+
num_edges = len(edges)
|
| 394 |
+
|
| 395 |
+
# Generate graph visualization HTML content
|
| 396 |
+
html_content = get_graph_html(nodes, edges, title="Knowledge Graph Visualization")
|
| 397 |
+
|
| 398 |
+
graph_data = {"html": html_content, "nodes": nodes, "edges": edges}
|
| 399 |
+
summary = f"Graph loaded successfully with {num_nodes} nodes and {num_edges} edges."
|
| 400 |
+
return summary, html_content, graph_data
|
| 401 |
+
|
| 402 |
+
def download_graph_html(graph_data):
|
| 403 |
+
"""Write the stored HTML visualization to a file for download."""
|
| 404 |
+
if not graph_data or "html" not in graph_data:
|
| 405 |
+
return None
|
| 406 |
+
html_content = graph_data["html"]
|
| 407 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".html", mode="w", encoding="utf-8") as temp_file:
|
| 408 |
+
temp_file.write(html_content)
|
| 409 |
+
temp_file_path = temp_file.name
|
| 410 |
+
return temp_file_path
|
| 411 |
+
|
| 412 |
+
def display_example():
|
| 413 |
+
"""Display an example graph format."""
|
| 414 |
+
example = {
|
| 415 |
+
"nodes": [
|
| 416 |
+
{"id": "1", "label": "Concept_1", "group": "Concept"},
|
| 417 |
+
{"id": "2", "label": "Entity_1", "group": "Entity"},
|
| 418 |
+
{"id": "3", "label": "Event_1", "group": "Event"}
|
| 419 |
+
],
|
| 420 |
+
"edges": [
|
| 421 |
+
{"from": "1", "to": "2", "label": "relates_to"},
|
| 422 |
+
{"from": "2", "to": "3", "label": "participates_in"}
|
| 423 |
+
]
|
| 424 |
+
}
|
| 425 |
+
return "```json\n" + json.dumps(example, indent=2) + "\n```"
|
| 426 |
+
|
| 427 |
+
def create_app():
|
| 428 |
+
"""Create and configure the Gradio app."""
|
| 429 |
+
with gr.Blocks(title="Knowledge Graph Visualizer", theme=gr.themes.Soft()) as app:
|
| 430 |
+
gr.Markdown(
|
| 431 |
+
"""
|
| 432 |
+
<div style="text-align: center; margin-bottom: 20px;">
|
| 433 |
+
<h1 style="color: #3498db; margin-bottom: 5px;">Knowledge Graph Visualizer</h1>
|
| 434 |
+
<p style="font-size: 16px; opacity: 0.8;">Visualize and explore your graph data interactively</p>
|
| 435 |
+
</div>
|
| 436 |
+
"""
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
with gr.Row():
|
| 440 |
+
with gr.Column(scale=1):
|
| 441 |
+
with gr.Accordion("๐ How to Use", open=False):
|
| 442 |
+
gr.Markdown(
|
| 443 |
+
"""
|
| 444 |
+
### Quick Start Guide
|
| 445 |
+
|
| 446 |
+
1. **Prepare your data**: Create a JSON file with 'nodes' and 'edges'
|
| 447 |
+
2. **Upload your file**: Use the upload button to select your JSON or text file
|
| 448 |
+
3. **Visualize**: Click the "Visualize Graph" button
|
| 449 |
+
4. **Explore**:
|
| 450 |
+
- Drag to move around the graph
|
| 451 |
+
- Scroll to zoom in/out
|
| 452 |
+
- Click on nodes to highlight connections
|
| 453 |
+
- Hover over nodes for details
|
| 454 |
+
5. **Download**: Save the visualization as an HTML file
|
| 455 |
+
"""
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
gr.Markdown("### 1. Upload Your Graph Data")
|
| 459 |
+
file_input = gr.File(
|
| 460 |
+
label="Select a JSON or text file with nodes and edges",
|
| 461 |
+
file_count="single",
|
| 462 |
+
type="file"
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
process_btn = gr.Button("Visualize Graph", variant="primary", size="lg")
|
| 466 |
+
status_output = gr.Textbox(label="Status", interactive=False)
|
| 467 |
+
|
| 468 |
+
with gr.Accordion("๐ Example Data Format", open=False):
|
| 469 |
+
gr.Markdown(
|
| 470 |
+
"Your file should contain a JSON object with 'nodes' and 'edges' arrays:"
|
| 471 |
+
)
|
| 472 |
+
example_format = gr.Markdown(display_example())
|
| 473 |
+
|
| 474 |
+
with gr.Accordion("๐ Documentation", open=False):
|
| 475 |
+
gr.Markdown(
|
| 476 |
+
"""
|
| 477 |
+
### Comprehensive Documentation
|
| 478 |
+
|
| 479 |
+
For detailed information about all features and capabilities, please visit our documentation page:
|
| 480 |
+
|
| 481 |
+
[View Complete Documentation](https://github.com/YOUR_USERNAME/knowledge-graph-visualizer/wiki)
|
| 482 |
+
|
| 483 |
+
### Node Properties
|
| 484 |
+
- **id**: Unique identifier (required)
|
| 485 |
+
- **label**: Display name (optional)
|
| 486 |
+
- **group**: Category grouping for coloring (optional)
|
| 487 |
+
|
| 488 |
+
### Edge Properties
|
| 489 |
+
- **from**: Source node id (required)
|
| 490 |
+
- **to**: Target node id (required)
|
| 491 |
+
- **label**: Relationship type (optional)
|
| 492 |
+
|
| 493 |
+
### Customization
|
| 494 |
+
The visualization adapts to your system's theme (light/dark) and is fully responsive.
|
| 495 |
+
"""
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
gr.Markdown("### 3. Save Your Visualization")
|
| 499 |
+
download_btn = gr.Button("Download Graph HTML", variant="secondary")
|
| 500 |
+
download_file = gr.File(label="Download File")
|
| 501 |
+
|
| 502 |
+
with gr.Row():
|
| 503 |
+
with gr.Column(scale=2):
|
| 504 |
+
gr.Markdown("### 2. Interactive Graph Visualization")
|
| 505 |
+
graph_output = gr.HTML(
|
| 506 |
+
label="Graph Visualization",
|
| 507 |
+
elem_id="graph-vis"
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
graph_data_state = gr.State(None)
|
| 511 |
+
|
| 512 |
+
gr.HTML(
|
| 513 |
+
"""
|
| 514 |
+
<style>
|
| 515 |
+
/* Responsive container for graph visualization */
|
| 516 |
+
#graph-vis {
|
| 517 |
+
width: 100%;
|
| 518 |
+
height: calc(100vh - 300px);
|
| 519 |
+
min-height: 500px;
|
| 520 |
+
overflow: auto;
|
| 521 |
+
border-radius: 8px;
|
| 522 |
+
border: 1px solid #e0e0e0;
|
| 523 |
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
| 524 |
+
transition: all 0.3s ease;
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
#graph-vis:hover {
|
| 528 |
+
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
@media (prefers-color-scheme: dark) {
|
| 532 |
+
.gradio-container {
|
| 533 |
+
background-color: #1e1e2e !important;
|
| 534 |
+
color: #cdd6f4 !important;
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
.gr-button-primary {
|
| 538 |
+
background-color: #74c7ec !important;
|
| 539 |
+
color: #1e1e2e !important;
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
.gr-button-secondary {
|
| 543 |
+
background-color: #313244 !important;
|
| 544 |
+
color: #cdd6f4 !important;
|
| 545 |
+
border: 1px solid #45475a !important;
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
.gr-input, .gr-text-input {
|
| 549 |
+
background-color: #313244 !important;
|
| 550 |
+
color: #cdd6f4 !important;
|
| 551 |
+
border: 1px solid #45475a !important;
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
.gr-panel {
|
| 555 |
+
background-color: #313244 !important;
|
| 556 |
+
border: 1px solid #45475a !important;
|
| 557 |
+
}
|
| 558 |
+
.gr-button:hover {
|
| 559 |
+
opacity: 0.9;
|
| 560 |
+
}
|
| 561 |
+
}
|
| 562 |
+
</style>
|
| 563 |
+
"""
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# Button actions
|
| 567 |
+
process_btn.click(
|
| 568 |
+
process_graph_file,
|
| 569 |
+
inputs=file_input,
|
| 570 |
+
outputs=[status_output, graph_output, graph_data_state]
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
download_btn.click(
|
| 574 |
+
download_graph_html,
|
| 575 |
+
inputs=graph_data_state,
|
| 576 |
+
outputs=download_file
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
return app
|
| 580 |
+
|
| 581 |
+
if __name__ == "__main__":
|
| 582 |
+
app = create_app()
|
| 583 |
+
app.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas
|
| 2 |
+
seaborn
|
| 3 |
+
networkx
|
| 4 |
+
python-louvain
|
| 5 |
+
pyvis
|
| 6 |
+
gradio
|
| 7 |
+
community
|
| 8 |
+
colorsys
|