home » zplus/dokk.org.git
ID: e3d4d71ac4c0d28ecd101e5309a90af70ea9df1b
66 lines — 2K — View raw


#!/usr/bin/env python3

"""
This script creates the data.js file containing the list of nodes end edges for
the vis.js graph.
"""

import json
import networkx
import matplotlib.pyplot as plt
from pathlib import Path


G = networkx.nx.Graph()


data = '../dokk/data'
edge_properties = [ 'comics_cartoon', 'comics_author', 'ttrpg_character' ]

nodes = []
edges = []

for path in Path(data).glob('**/*.json',):
    with open(path, 'r') as f:
        n = json.loads(f.read())
        
        G.add_node(n['node_id'])
        
        nodes.append({
            'title': n['node_name'] + ('\n' + n['node_description'] if 'node_description' in n else ''),
            #'color': { 'background': '', 'border': ''},
            'label': n['node_name'],
            'id': n['node_id']
        })
        
        for p in edge_properties:
            if p not in n.keys():
                continue
            
            if not type(n[p]) == list:
                n[p] = [ n[p] ]
            
            for target in n[p]:
                G.add_edge(n['node_id'], target)
                
                edges.append({
                    'title': p,
                    'from': n['node_id'],
                    #'label': p,
                    'to': target,
                })

"""
pos = networkx.nx.spring_layout(G, k=1, iterations=200, scale=1000)

for n in nodes:
    n['x'] = pos[n['id']][0]
    n['y'] = pos[n['id']][1]

networkx.nx.set_node_attributes(G, pos, 'pos')
networkx.nx.draw(G, pos=pos)
plt.show()
"""

with open('data.js', 'w') as f:
    f.write('var nodes={};\nvar edges={}'.format(json.dumps(nodes), json.dumps(edges)))