def __attrs_post_init__(self): if self.location is not None: self._is_remote = self.location.startswith( "http://") or self.location.startswith("https://") if self._is_remote is True: self.connector = SPARQLConnector(self.location, cache=self.cache) elif self.location is not None: for subj, pred, obj in rdflib.Graph().parse(self.location, format=self.fmt): subj = Vertex(str(subj)) obj = Vertex(str(obj)) self.add_walk( subj, Vertex(str(pred), predicate=True, vprev=subj, vnext=obj), obj, )
def _res2hops(self, vertex: Vertex, res) -> List[Hop]: """Converts a JSON response from a SPARQL endpoint server to hops. Args: vertex: The vertex to get the hops. res: The JSON response of the SPARQL endpoint server. Returns: The hops. """ hops = [] for value in res: obj = Vertex(value["o"]["value"]) pred = Vertex( value["p"]["value"], predicate=True, vprev=vertex, vnext=obj, ) if self.add_walk(vertex, pred, obj): hops.append((pred, obj)) return hops
def _fill_hops(self, entities: Entities) -> None: """Fills the entity hops in cache. Args: vertices: The vertices to get the hops. """ queries = [self.connector.get_query(entity) for entity in entities] for entity, res in zip( entities, asyncio.run(self.connector.afetch(queries)), ): hops = self._res2hops(Vertex(entity), res) self._entity_hops.update({entity: hops})
def get_pliterals(self, entity: str, preds: List[str]) -> List[str]: """Gets the literals for an entity and a local KG based on a chain of predicates. Args: entity: The entity. preds: The chain of predicates. Returns: The literals for the given entity. """ frontier = {entity} for p in preds: new_frontier = set() for node in frontier: for pred, obj in self.get_hops(Vertex(node)): if pred.name == p: new_frontier.add(obj.name) frontier = new_frontier return list(frontier)
def is_exist(self, entities: Entities) -> bool: """Checks that all provided entities exists in the Knowledge Graph. Args: entities: The entities to check the existence Returns: True if all the entities exists, False otherwise. """ if self._is_remote: queries = [ f"ASK WHERE {{ <{entity}> ?p ?o . }}" for entity in entities ] if self.mul_req: responses = [ res["boolean"] # type: ignore for res in asyncio.run(self.connector.afetch(queries)) ] else: responses = [self.connector.fetch(query) for query in queries] responses = [res["boolean"] for res in responses] return False not in responses return all([Vertex(entity) in self._vertices for entity in entities])