import networkx as nx import json import os import webbrowser import http.server import socketserver import threading # 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) # create HTML file def create_html(html_path): html_content = ''' Graph Visualization
''' with open(html_path, 'w', encoding='utf-8') as f: f.write(html_content) def create_json(json_data, json_path): json_data = "var graphJson = " + json_data.replace('\\"', '').replace("'", "\\'").replace("\n", "") with open(json_path, 'w', encoding='utf-8') as f: f.write(json_data) # start simple HTTP server def start_server(port): handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", port), handler) as httpd: print(f"Server started at http://localhost:{port}") httpd.serve_forever() # main function def visualize_graphml(graphml_file, html_path, port=8000): json_data = graphml_to_json(graphml_file) 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) # start server in background server_thread = threading.Thread(target=start_server(port)) server_thread.daemon = True server_thread.start() # 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" # replace with your GraphML file path html_path = "graph_visualization.html" visualize_graphml(graphml_file, html_path, 11236)