pandora_cms/ontology/update.py

69 lines
1.8 KiB
Python
Raw Normal View History

2018-05-31 14:59:17 +00:00
#!/usr/bin/python3
import json
import os
from collections import defaultdict
2018-05-31 19:32:56 +00:00
base = os.path.abspath(os.path.dirname(__file__))
keywords = json.load(open(os.path.join(base, 'keywords.json')))
ontology = json.load(open(os.path.join(base, 'ontology.json')))
2018-05-31 14:59:17 +00:00
def find_path(parent, root=None, path=None):
if root is None:
root = ontology
2018-05-31 19:32:56 +00:00
if path is None:
2018-05-31 14:59:17 +00:00
path = []
for key in root:
if key == parent:
return path + [key]
elif root[key]:
r = find_path(parent, root[key], path + [key])
if r:
return r
2018-05-31 19:32:56 +00:00
def get_node(name, children, parent=None):
2018-05-31 14:59:17 +00:00
node = {
"size": len(children) + 100,
"name": name,
2018-05-31 19:32:56 +00:00
"children": [get_node(child, children[child], name) for child in children]
2018-05-31 14:59:17 +00:00
}
if not node['children']:
del node['children']
2018-05-31 19:32:56 +00:00
key = '%s: %s' % (parent, name)
if key in keywords:
node['size'] = keywords[key]
2018-05-31 14:59:17 +00:00
return node
if __name__ == '__main__':
os.chdir(base)
tree = defaultdict(dict)
for keyword in keywords:
2018-05-31 19:32:56 +00:00
parent, child = keyword.split(': ')
2018-05-31 14:59:17 +00:00
path = find_path(parent)
if path:
p = tree
for part in path:
if part not in p:
p[part] = {}
p = p[part]
p[child] = {}
else:
print('missing root - %s: %s' % (parent, child))
#print(json.dumps(tree, indent=4, sort_keys=True))
sized_ontology = {
"size": len(tree),
"name": "CineMuseSpace",
"children": []
}
for name in tree:
children = tree[name]
2018-05-31 19:32:56 +00:00
child = get_node(name, tree[name], name)
2018-05-31 14:59:17 +00:00
sized_ontology['children'].append(child)
with open('../static/ontology/sized_ontology.json', 'w') as fd:
json.dump(sized_ontology, fd, indent=4, sort_keys=True)