from typing import List, Set from owlready2 import get_ontology, Ontology class MyOntology: def __init__(self) -> None: self.__onto: Ontology = get_ontology("file://./new-ontology.owx").load() self.__concept = self.__onto.Concept def __get_concept_level(self, concept) -> int: level = 1 parent = concept.is_a[0] while parent != self.__concept: level += 1 parent = parent.is_a[0] return level @staticmethod def __get_instances(root, term: str) -> Set: instances: Set = set() for instance in root.instances(): if instance.name == term: instances.add(instance) return instances def __get_concepts(self, instances: Set) -> Set: concepts: Set = set() for instance in instances: for concept in instance.is_instance_of: concepts.add((self.__get_concept_level(concept), concept)) return concepts def make(self, root_class: [], terms: List[str], is_empty=True) -> Set: if not isinstance(terms, list) or not isinstance(root_class, list): return set() if len(terms) == 0 or len(root_class) == 0: return set() concepts: Set = set() for concept in root_class: term: str = terms[-1] my_terms: List[str] = list(filter(lambda item: item != term, terms)) instances: Set = self.__get_instances(concept, term) result = self.__get_concepts(instances) concepts.update(result) new_root: [] = [] is_empty = is_empty and len(concepts) == 0 if len(result) == 0 and is_empty: new_root.append(self.__concept) else: new_root.extend(list(map(lambda item: item[1], result))) concepts.update(self.make(new_root, my_terms, is_empty)) return concepts def get_events(self, terms: List[str]) -> str: concepts: Set = set() for term in terms: concepts.update(self.make([self.__concept], term.split(' '))) events = sorted(list( map(lambda concept: (concept[0], ' '.join(concept[1].hasDescription)), concepts)), reverse=True) return '\n'.join(list(map(lambda event: event[1], events)))