11import networkx as nx
22import json
3+ import os
34import webbrowser
45import http .server
56import socketserver
67import threading
78
8- # 读取GraphML文件并转换为JSON
9+ # load GraphML file and transfer to JSON
910def graphml_to_json (graphml_file ):
1011 G = nx .read_graphml (graphml_file )
1112 data = nx .node_link_data (G )
1213 return json .dumps (data )
1314
1415
15- # 创建HTML文件
16+ # create HTML file
1617def create_html (html_path ):
1718 html_content = '''
1819<!DOCTYPE html>
@@ -242,36 +243,40 @@ def create_json(json_data, json_path):
242243 f .write (json_data )
243244
244245
245- # 启动简单的HTTP服务器
246- def start_server ():
246+ # start simple HTTP server
247+ def start_server (port ):
247248 handler = http .server .SimpleHTTPRequestHandler
248- with socketserver .TCPServer (("" , 8000 ), handler ) as httpd :
249- print ("Server started at http://localhost:8000 " )
249+ with socketserver .TCPServer (("" , port ), handler ) as httpd :
250+ print (f "Server started at http://localhost:{ port } " )
250251 httpd .serve_forever ()
251252
252- # 主函数
253- def visualize_graphml (graphml_file , html_path ):
253+ # main function
254+ def visualize_graphml (graphml_file , html_path , port = 8000 ):
254255 json_data = graphml_to_json (graphml_file )
255- create_json (json_data , 'graph_json.js' )
256+ html_dir = os .path .dirname (html_path )
257+ if not os .path .exists (html_dir ):
258+ os .makedirs (html_dir )
259+ json_path = os .path .join (html_dir , 'graph_json.js' )
260+ create_json (json_data , json_path )
256261 create_html (html_path )
257- # 在后台启动服务器
258- server_thread = threading .Thread (target = start_server )
262+ # start server in background
263+ server_thread = threading .Thread (target = start_server ( port ) )
259264 server_thread .daemon = True
260265 server_thread .start ()
261266
262- # 打开默认浏览器
263- webbrowser .open ('http://localhost:8000/graph_visualization.html ' )
267+ # open default browser
268+ webbrowser .open (f 'http://localhost:{ port } / { html_path } ' )
264269
265270 print ("Visualization is ready. Press Ctrl+C to exit." )
266271 try :
267- # 保持主线程运行
272+ # keep main thread running
268273 while True :
269274 pass
270275 except KeyboardInterrupt :
271276 print ("Shutting down..." )
272277
273- # 使用示例
278+ # usage
274279if __name__ == "__main__" :
275- graphml_file = r"nano_graphrag_cache_azure_openai_TEST\graph_chunk_entity_relation.graphml" # 替换为您的GraphML文件路径
280+ graphml_file = r"nano_graphrag_cache_azure_openai_TEST\graph_chunk_entity_relation.graphml" # replace with your GraphML file path
276281 html_path = "graph_visualization.html"
277- visualize_graphml (graphml_file , html_path )
282+ visualize_graphml (graphml_file , html_path , 11236 )
0 commit comments