[docs]classRdfGraph:"""RDFlib wrapper for graph operations. Modes: * local: Local file - can be queried and changed * online: Online file - can only be queried, changes can be stored locally * store: Triple store - can be queried and changed if update_endpoint available Together with a source file, the serialization should be specified. *Security note*: Make sure that the database connection uses credentials that are narrowly-scoped to only include necessary permissions. Failure to do so may result in data corruption or loss, since the calling code may attempt commands that would result in deletion, mutation of data if appropriately prompted or reading sensitive data if such data is present in the database. The best way to guard against such negative outcomes is to (as appropriate) limit the permissions granted to the credentials used with this tool. See https://python.langchain.com/docs/security for more information. """
[docs]def__init__(self,source_file:Optional[str]=None,serialization:Optional[str]="ttl",query_endpoint:Optional[str]=None,update_endpoint:Optional[str]=None,standard:Optional[str]="rdf",local_copy:Optional[str]=None,graph_kwargs:Optional[Dict]=None,store_kwargs:Optional[Dict]=None,)->None:""" Set up the RDFlib graph :param source_file: either a path for a local file or a URL :param serialization: serialization of the input :param query_endpoint: SPARQL endpoint for queries, read access :param update_endpoint: SPARQL endpoint for UPDATE queries, write access :param standard: RDF, RDFS, or OWL :param local_copy: new local copy for storing changes :param graph_kwargs: Additional rdflib.Graph specific kwargs that will be used to initialize it, if query_endpoint is provided. :param store_kwargs: Additional sparqlstore.SPARQLStore specific kwargs that will be used to initialize it, if query_endpoint is provided. """self.source_file=source_fileself.serialization=serializationself.query_endpoint=query_endpointself.update_endpoint=update_endpointself.standard=standardself.local_copy=local_copytry:importrdflibfromrdflib.plugins.storesimportsparqlstoreexceptImportError:raiseImportError("Could not import rdflib python package. ""Please install it with `pip install rdflib`.")ifself.standardnotin(supported_standards:=("rdf","rdfs","owl")):raiseValueError(f"Invalid standard. Supported standards are: {supported_standards}.")if(notsource_fileandnotquery_endpointorsource_fileand(query_endpointorupdate_endpoint)):raiseValueError("Could not unambiguously initialize the graph wrapper. ""Specify either a file (local or online) via the source_file ""or a triple store via the endpoints.")ifsource_file:ifsource_file.startswith("http"):self.mode="online"else:self.mode="local"ifself.local_copyisNone:self.local_copy=self.source_fileself.graph=rdflib.Graph()self.graph.parse(source_file,format=self.serialization)ifquery_endpoint:store_kwargs=store_kwargsor{}self.mode="store"ifnotupdate_endpoint:self._store=sparqlstore.SPARQLStore(**store_kwargs)self._store.open(query_endpoint)else:self._store=sparqlstore.SPARQLUpdateStore(**store_kwargs)self._store.open((query_endpoint,update_endpoint))graph_kwargs=graph_kwargsor{}self.graph=rdflib.Graph(self._store,**graph_kwargs)# Verify that the graph was loadedifnotlen(self.graph):raiseAssertionError("The graph is empty.")# Set schemaself.schema=""self.load_schema()
@propertydefget_schema(self)->str:""" Returns the schema of the graph database. """returnself.schema
[docs]defquery(self,query:str,)->List[rdflib.query.ResultRow]:""" Query the graph. """fromrdflib.exceptionsimportParserErrorfromrdflib.queryimportResultRowtry:res=self.graph.query(query)exceptParserErrorase:raiseValueError(f"Generated SPARQL statement is invalid\n{e}")return[rforrinresifisinstance(r,ResultRow)]
[docs]defupdate(self,query:str,)->None:""" Update the graph. """fromrdflib.exceptionsimportParserErrortry:self.graph.update(query)exceptParserErrorase:raiseValueError(f"Generated SPARQL statement is invalid\n{e}")ifself.local_copy:self.graph.serialize(destination=self.local_copy,format=self.local_copy.split(".")[-1])else:raiseValueError("No target file specified for saving the updated file.")
@staticmethoddef_get_local_name(iri:str)->str:if"#"iniri:local_name=iri.split("#")[-1]elif"/"iniri:local_name=iri.split("/")[-1]else:raiseValueError(f"Unexpected IRI '{iri}', contains neither '#' nor '/'.")returnlocal_namedef_res_to_str(self,res:rdflib.query.ResultRow,var:str)->str:return("<"+str(res[var])+"> ("+self._get_local_name(res[var])+", "+str(res["com"])+")")
[docs]defload_schema(self)->None:""" Load the graph schema information. """def_rdf_s_schema(classes:List[rdflib.query.ResultRow],relationships:List[rdflib.query.ResultRow],)->str:return(f"In the following, each IRI is followed by the local name and "f"optionally its description in parentheses. \n"f"The RDF graph supports the following node types:\n"f"{', '.join([self._res_to_str(r,'cls')forrinclasses])}\n"f"The RDF graph supports the following relationships:\n"f"{', '.join([self._res_to_str(r,'rel')forrinrelationships])}\n")ifself.standard=="rdf":clss=self.query(cls_query_rdf)rels=self.query(rel_query_rdf)self.schema=_rdf_s_schema(clss,rels)elifself.standard=="rdfs":clss=self.query(cls_query_rdfs)rels=self.query(rel_query_rdfs)self.schema=_rdf_s_schema(clss,rels)elifself.standard=="owl":clss=self.query(cls_query_owl)ops=self.query(op_query_owl)dps=self.query(dp_query_owl)self.schema=(f"In the following, each IRI is followed by the local name and "f"optionally its description in parentheses. \n"f"The OWL graph supports the following node types:\n"f"{', '.join([self._res_to_str(r,'cls')forrinclss])}\n"f"The OWL graph supports the following object properties, "f"i.e., relationships between objects:\n"f"{', '.join([self._res_to_str(r,'op')forrinops])}\n"f"The OWL graph supports the following data properties, "f"i.e., relationships between objects and literals:\n"f"{', '.join([self._res_to_str(r,'dp')forrindps])}\n")else:raiseValueError(f"Mode '{self.standard}' is currently not supported.")