You might need these
!pip install rdflib pyld yamlmagic
%reload_ext yamlmagic
from pyld import jsonld
from rdflib import (
ConjunctiveGraph,
URIRef as uri,
)
from yaml import SafeLoader
set up some custom tags.
def tag_ld(loader, node):
doc = loader.construct_mapping(node, deep=True)
# this looks odd... but pyld is way better at parsing the rdflib-jsonld
return ConjunctiveGraph().parse(
data=jsonld.normalize(doc, {'format': 'application/nquads'}),
format="n3"
)
def tag_ipyvar(loader, node):
varname = loader.construct_scalar(node)
return get_ipython().user_global_ns[varname]
Add them to SafeLoader.... could do this with a subclass, but whatever.
SafeLoader.add_constructor("!ipyvar", tag_ipyvar)
SafeLoader.add_constructor("!ld", tag_ld)
Let's say we want a context which we can reuse...
%%yaml context
rdfs: http://www.w3.org/2000/01/rdf-schema#
rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
# pretties, because `@` is reserved
the:
"@id": "@id"
"@type": "@id"
a:
"@id": "@type"
gist: https://gist.github.com/
jupyter: https://jupyter.org/
%%yaml graph1
!ld
"@context": !ipyvar context
"@graph":
- the: gist:ea2f710aaf8d3f4a8e81#file-bokeh_yaml-ipynb
a: jupyter:Notebook
rdfs:label: Bokeh YAML
- the: gist:8388c7a9425e237ff48d#file-bokeh-yaml-ipynb
a: jupyter:Notebook
rdfs:label: YAML Loader
The whole graph
list(graph1)
[(rdflib.term.URIRef('https://gist.github.com/ea2f710aaf8d3f4a8e81#file-bokeh_yaml-ipynb'), rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.URIRef('https://jupyter.org/Notebook')), (rdflib.term.URIRef('https://gist.github.com/ea2f710aaf8d3f4a8e81#file-bokeh_yaml-ipynb'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('Bokeh YAML')), (rdflib.term.URIRef('https://gist.github.com/8388c7a9425e237ff48d#file-bokeh-yaml-ipynb'), rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.URIRef('https://jupyter.org/Notebook')), (rdflib.term.URIRef('https://gist.github.com/8388c7a9425e237ff48d#file-bokeh-yaml-ipynb'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('YAML Loader'))]
All of the types
list(graph1[:uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"):])
[(rdflib.term.URIRef('https://gist.github.com/ea2f710aaf8d3f4a8e81#file-bokeh_yaml-ipynb'), rdflib.term.URIRef('https://jupyter.org/Notebook')), (rdflib.term.URIRef('https://gist.github.com/8388c7a9425e237ff48d#file-bokeh-yaml-ipynb'), rdflib.term.URIRef('https://jupyter.org/Notebook'))]