import owlready2 def load_owl(filename): return owlready2.get_ontology("file://" + filename).load() def map_properties_classes(ontology): """ Return a map of all things """ cls_prop_map = {cls: {} for cls in ontology.classes()} for prop in ontology.properties(): for domain in prop.domain: cls = cls_prop_map.get(domain) if cls is None: continue cls[prop] = prop.range return cls_prop_map def to_name(thing): if thing is str: return 'string' return '.'.join(str(thing).split('.')[1:]) def range_to_type_name(thing): # a very lazy/naive implementation for the mean time. if len(thing) == 1: if thing[0] is str: return "string" else: return to_name(thing[0]) # laziest possible conversion. return str([to_name(item) for item in thing]) def build_schema(cls_prop_map): results = {} for cls, cls_prop in cls_prop_map.items(): key, value = build_schema_cls(cls, cls_prop) results[key] = value return results def build_schema_cls(cls, cls_prop): schema_properties = {} schema = { "$id": "", "$schema": "http://schema.blackfynn.io/model/draft-01/schema", "name": to_name(cls), "description": "", "category": "", "properties": schema_properties, "required": [], } for prop, range_ in cls_prop.items(): schema_properties[to_name(prop)] = { "description": "", "type": range_to_type_name(range_), } return to_name(cls), schema if __name__ == '__main__': import sys import json from os.path import basename if len(sys.argv) < 2: sys.stderr.write('usage: %s \n' % basename(sys.argv[0])) sys.exit(1) ontology = load_owl(sys.argv[1]) cls_prop_map = map_properties_classes(ontology) schemas = build_schema(cls_prop_map) print(json.dumps(schemas, indent=4))