#!/usr/bin/env python # coding: utf-8 # # Less-painful live-authoring authoring of RDF with IPython, YAML(-LD) # > You might need these # In[ ]: get_ipython().system('pip install rdflib pyld yamlmagic') # In[1]: get_ipython().run_line_magic('reload_ext', 'yamlmagic') from pyld import jsonld from rdflib import ( ConjunctiveGraph, URIRef as uri, ) from yaml import SafeLoader # set up some custom tags. # In[2]: 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" ) # In[3]: 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. # In[4]: SafeLoader.add_constructor("!ipyvar", tag_ipyvar) SafeLoader.add_constructor("!ld", tag_ld) # Let's say we want a context which we can reuse... # In[5]: get_ipython().run_cell_magic('yaml', 'context', 'rdfs: http://www.w3.org/2000/01/rdf-schema#\nrdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#\n# pretties, because `@` is reserved\nthe:\n "@id": "@id"\n "@type": "@id"\na:\n "@id": "@type"\ngist: https://gist.github.com/\njupyter: https://jupyter.org/\n') # In[6]: get_ipython().run_cell_magic('yaml', 'graph1', '!ld\n"@context": !ipyvar context\n"@graph":\n- the: gist:ea2f710aaf8d3f4a8e81#file-bokeh_yaml-ipynb\n a: jupyter:Notebook\n rdfs:label: Bokeh YAML\n- the: gist:8388c7a9425e237ff48d#file-bokeh-yaml-ipynb\n a: jupyter:Notebook\n rdfs:label: YAML Loader\n') # The whole graph # In[7]: list(graph1) # All of the types # In[8]: list(graph1[:uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"):])