from typing import List, Optional from owlready2 import get_ontology, Ontology class MyOntology: def __init__(self) -> None: self._onto: Ontology = get_ontology("file://./ontology.owl").load() def _find(self, string: str, string_list: List[str]) -> int: try: string_list.index(string) return 1 except ValueError: return 0 def _get_property_value(self, values: [], instance): if len(values) != 1: raise ValueError(f'Wrong values in {instance.name}') return values[0] def _get_event_instance(self, instances: []): max_instance: Optional = None max_priority: int = 0 for instance in instances: event = self._get_property_value(instance.hasEvent, instance) priority = self._get_property_value(event.hasPriority, event) if priority > max_priority: max_instance = event max_priority = priority return max_instance def _find_instances_by_terms(self, nouns: List[str]) -> []: instances = [] for instance in self._onto.Concept.instances(): terms = instance.hasTerm match: int = 0 for term in terms: match = match + self._find(term.name, nouns) if match >= len(terms) * 0.5: instances.append(instance) return instances def get_event_description(self, nouns: List[str]) -> str: instances: [] = self._find_instances_by_terms(nouns) event = self._get_event_instance(instances) if event is None: return '' return self._get_property_value(event.hasDescription, event)