Source code

Download source archive ↓

src/rdflib/extras/describer.py

1"""
2A Describer is a stateful utility for creating RDF statements in a
3semi-declarative manner. It has methods for creating literal values, rel and
4rev resource relations (somewhat resembling RDFa).
5
6The `Describer.rel` and `Describer.rev` methods return a context manager which sets the current
7about to the referenced resource for the context scope (for use with the
8`with` statement).
9
10Full example in the `to_rdf` method below:
11
12```python
13>>> import datetime
14>>> from rdflib.graph import Graph
15>>> from rdflib.namespace import Namespace, RDFS, FOAF
16
17>>> ORG_URI = "http://example.org/"
18
19>>> CV = Namespace("http://purl.org/captsolo/resume-rdf/0.2/cv#")
20
21>>> class Person:
22...     def __init__(self):
23...         self.first_name = "Some"
24...         self.last_name = "Body"
25...         self.username = "some1"
26...         self.presentation = "Just a Python & RDF hacker."
27...         self.image = "/images/persons/" + self.username + ".jpg"
28...         self.site = "http://example.net/"
29...         self.start_date = datetime.date(2009, 9, 4)
30...     def get_full_name(self):
31...         return " ".join([self.first_name, self.last_name])
32...     def get_absolute_url(self):
33...         return "/persons/" + self.username
34...     def get_thumbnail_url(self):
35...         return self.image.replace('.jpg', '-thumb.jpg')
36...
37...     def to_rdf(self):
38...         graph = Graph()
39...         graph.bind('foaf', FOAF)
40...         graph.bind('cv', CV)
41...         lang = 'en'
42...         d = Describer(graph, base=ORG_URI)
43...         d.about(self.get_absolute_url()+'#person')
44...         d.rdftype(FOAF.Person)
45...         d.value(FOAF.name, self.get_full_name())
46...         d.value(FOAF.givenName, self.first_name)
47...         d.value(FOAF.familyName, self.last_name)
48...         d.rel(FOAF.homepage, self.site)
49...         d.value(RDFS.comment, self.presentation, lang=lang)
50...         with d.rel(FOAF.depiction, self.image):
51...             d.rdftype(FOAF.Image)
52...             d.rel(FOAF.thumbnail, self.get_thumbnail_url())
53...         with d.rev(CV.aboutPerson):
54...             d.rdftype(CV.CV)
55...             with d.rel(CV.hasWorkHistory):
56...                 d.value(CV.startDate, self.start_date)
57...                 d.rel(CV.employedIn, ORG_URI+"#company")
58...         return graph
59...
60>>> person_graph = Person().to_rdf()
61>>> expected = Graph().parse(data='''<?xml version="1.0" encoding="utf-8"?>
62... <rdf:RDF
63...   xmlns:foaf="http://xmlns.com/foaf/0.1/"
64...   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
65...   xmlns:cv="http://purl.org/captsolo/resume-rdf/0.2/cv#"
66...   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
67...   <foaf:Person rdf:about="http://example.org/persons/some1#person">
68...     <foaf:name>Some Body</foaf:name>
69...     <foaf:givenName>Some</foaf:givenName>
70...     <foaf:familyName>Body</foaf:familyName>
71...     <foaf:depiction>
72...       <foaf:Image
73...         rdf:about=
74...             "http://example.org/images/persons/some1.jpg">
75...         <foaf:thumbnail
76...         rdf:resource=
77...             "http://example.org/images/persons/some1-thumb.jpg"/>
78...       </foaf:Image>
79...     </foaf:depiction>
80...     <rdfs:comment xml:lang="en">
81...             Just a Python &amp; RDF hacker.
82...     </rdfs:comment>
83...     <foaf:homepage rdf:resource="http://example.net/"/>
84...   </foaf:Person>
85...   <cv:CV>
86...     <cv:aboutPerson
87...         rdf:resource="http://example.org/persons/some1#person">
88...     </cv:aboutPerson>
89...     <cv:hasWorkHistory>
90...       <rdf:Description>
91...         <cv:startDate
92...             rdf:datatype="http://www.w3.org/2001/XMLSchema#date"
93...             >2009-09-04</cv:startDate>
94...         <cv:employedIn rdf:resource="http://example.org/#company"/>
95...       </rdf:Description>
96...     </cv:hasWorkHistory>
97...   </cv:CV>
98... </rdf:RDF>
99... ''', format="xml")
100
101>>> from rdflib.compare import isomorphic
102>>> isomorphic(person_graph, expected)  #doctest: +SKIP
103True
104
105```
106"""
107
108from contextlib import contextmanager
109
110from rdflib.graph import Graph
111from rdflib.namespace import RDF
112from rdflib.term import BNode, Identifier, Literal, URIRef
113
114
115class Describer:
116    def __init__(self, graph=None, about=None, base=None):
117        if graph is None:
118            graph = Graph()
119        self.graph = graph
120        self.base = base
121        self._subjects = []
122        self.about(about or None)
123
124    def about(self, subject, **kws):
125        """
126        Sets the current subject. Will convert the given object into an
127        `URIRef` if it's not an `Identifier`.
128
129        Example:
130            ```python
131            >>> d = Describer()
132            >>> d._current() #doctest: +ELLIPSIS
133            rdflib.term.BNode(...)
134            >>> d.about("http://example.org/")
135            >>> d._current()
136            rdflib.term.URIRef('http://example.org/')
137
138            ```
139        """
140        kws.setdefault("base", self.base)
141        subject = cast_identifier(subject, **kws)
142        if self._subjects:
143            self._subjects[-1] = subject
144        else:
145            self._subjects.append(subject)
146
147    def value(self, p, v, **kws):
148        """
149        Set a literal value for the given property. Will cast the value to an
150        `Literal` if a plain literal is given.
151
152        Example:
153            ```python
154            >>> from rdflib import URIRef
155            >>> from rdflib.namespace import RDF, RDFS
156            >>> d = Describer(about="http://example.org/")
157            >>> d.value(RDFS.label, "Example")
158            >>> d.graph.value(URIRef('http://example.org/'), RDFS.label)
159            rdflib.term.Literal('Example')
160
161            ```
162        """
163        v = cast_value(v, **kws)
164        self.graph.add((self._current(), p, v))
165
166    def rel(self, p, o=None, **kws):
167        """Set an object for the given property. Will convert the given object
168        into an `URIRef` if it's not an `Identifier`. If none is given, a
169        new `BNode` is used.
170
171        Returns a context manager for use in a `with` block, within which the
172        given object is used as current subject.
173
174        Example:
175            ```python
176            >>> from rdflib import URIRef
177            >>> from rdflib.namespace import RDF, RDFS
178            >>> d = Describer(about="/", base="http://example.org/")
179            >>> _ctxt = d.rel(RDFS.seeAlso, "/about")
180            >>> d.graph.value(URIRef('http://example.org/'), RDFS.seeAlso)
181            rdflib.term.URIRef('http://example.org/about')
182
183            >>> with d.rel(RDFS.seeAlso, "/more"):
184            ...     d.value(RDFS.label, "More")
185            >>> (URIRef('http://example.org/'), RDFS.seeAlso,
186            ...         URIRef('http://example.org/more')) in d.graph
187            True
188            >>> d.graph.value(URIRef('http://example.org/more'), RDFS.label)
189            rdflib.term.Literal('More')
190
191            ```
192        """
193
194        kws.setdefault("base", self.base)
195        p = cast_identifier(p)
196        o = cast_identifier(o, **kws)
197        self.graph.add((self._current(), p, o))
198        return self._subject_stack(o)
199
200    def rev(self, p, s=None, **kws):
201        """
202        Same as `rel`, but uses current subject as *object* of the relation.
203        The given resource is still used as subject in the returned context
204        manager.
205
206        Example:
207            ```python
208            >>> from rdflib import URIRef
209            >>> from rdflib.namespace import RDF, RDFS
210            >>> d = Describer(about="http://example.org/")
211            >>> with d.rev(RDFS.seeAlso, "http://example.net/"):
212            ...     d.value(RDFS.label, "Net")
213            >>> (URIRef('http://example.net/'), RDFS.seeAlso,
214            ...         URIRef('http://example.org/')) in d.graph
215            True
216            >>> d.graph.value(URIRef('http://example.net/'), RDFS.label)
217            rdflib.term.Literal('Net')
218
219            ```
220        """
221        kws.setdefault("base", self.base)
222        p = cast_identifier(p)
223        s = cast_identifier(s, **kws)
224        self.graph.add((s, p, self._current()))
225        return self._subject_stack(s)
226
227    def rdftype(self, t):
228        """Shorthand for setting rdf:type of the current subject.
229
230        Example:
231            ```python
232            >>> from rdflib import URIRef
233            >>> from rdflib.namespace import RDF, RDFS
234            >>> d = Describer(about="http://example.org/")
235            >>> d.rdftype(RDFS.Resource)
236            >>> (URIRef('http://example.org/'),
237            ...     RDF.type, RDFS.Resource) in d.graph
238            True
239
240            ```
241        """
242        self.graph.add((self._current(), RDF.type, t))
243
244    def _current(self):
245        return self._subjects[-1]
246
247    @contextmanager
248    def _subject_stack(self, subject):
249        self._subjects.append(subject)
250        yield None
251        self._subjects.pop()
252
253
254def cast_value(v, **kws):
255    if not isinstance(v, Literal):
256        v = Literal(v, **kws)
257    return v
258
259
260def cast_identifier(ref, **kws):
261    ref = ref or BNode()
262    if not isinstance(ref, Identifier):
263        ref = URIRef(ref, **kws)
264    return ref