Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 22 additions & 17 deletions examples/graphml_visualize.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import networkx as nx
import json
import os
import webbrowser
import http.server
import socketserver
import threading

# 读取GraphML文件并转换为JSON
# load GraphML file and transfer to JSON
def graphml_to_json(graphml_file):
G = nx.read_graphml(graphml_file)
data = nx.node_link_data(G)
return json.dumps(data)


# 创建HTML文件
# create HTML file
def create_html(html_path):
html_content = '''
<!DOCTYPE html>
Expand Down Expand Up @@ -242,36 +243,40 @@ def create_json(json_data, json_path):
f.write(json_data)


# 启动简单的HTTP服务器
def start_server():
# start simple HTTP server
def start_server(port):
handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", 8000), handler) as httpd:
print("Server started at http://localhost:8000")
with socketserver.TCPServer(("", port), handler) as httpd:
print(f"Server started at http://localhost:{port}")
httpd.serve_forever()

# 主函数
def visualize_graphml(graphml_file, html_path):
# main function
def visualize_graphml(graphml_file, html_path, port=8000):
json_data = graphml_to_json(graphml_file)
create_json(json_data, 'graph_json.js')
html_dir = os.path.dirname(html_path)
if not os.path.exists(html_dir):
os.makedirs(html_dir)
json_path = os.path.join(html_dir, 'graph_json.js')
create_json(json_data, json_path)
create_html(html_path)
# 在后台启动服务器
server_thread = threading.Thread(target=start_server)
# start server in background
server_thread = threading.Thread(target=start_server(port))
server_thread.daemon = True
server_thread.start()

# 打开默认浏览器
webbrowser.open('http://localhost:8000/graph_visualization.html')
# open default browser
webbrowser.open(f'http://localhost:{port}/{html_path}')

print("Visualization is ready. Press Ctrl+C to exit.")
try:
# 保持主线程运行
# keep main thread running
while True:
pass
except KeyboardInterrupt:
print("Shutting down...")

# 使用示例
# usage
if __name__ == "__main__":
graphml_file = r"nano_graphrag_cache_azure_openai_TEST\graph_chunk_entity_relation.graphml" # 替换为您的GraphML文件路径
graphml_file = r"nano_graphrag_cache_azure_openai_TEST\graph_chunk_entity_relation.graphml" # replace with your GraphML file path
html_path = "graph_visualization.html"
visualize_graphml(graphml_file, html_path)
visualize_graphml(graphml_file, html_path, 11236)