This repository was archived by the owner on Apr 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsparta.py
537 lines (471 loc) · 19.9 KB
/
sparta.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#!/usr/bin/env python
"""
sparta.py - a Simple API for RDF
Sparta is a simple API for RDF that binds RDF nodes to Python
objects and RDF arcs to attributes of those Python objects. As
such, it can be considered a "data binding" from RDF to Python.
Requires rdflib <http://www.rdflib.net/> version 2.3.1+.
"""
__license__ = """
Copyright (c) 2001-2006 Mark Nottingham <mnot@pobox.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
__version__ = "0.9-pre"
import base64
import rdflib # http://rdflib.net/
from rdflib.Identifier import Identifier as ID
from rdflib.URIRef import URIRef as URI
from rdflib.BNode import BNode
from rdflib.Literal import Literal
from rdflib import RDF, RDFS
RDF_SEQi = "http://www.w3.org/1999/02/22-rdf-syntax-ns#_%s"
MAX_CARD = URI("http://www.w3.org/2002/07/owl#maxCardinality")
CARD = URI("http://www.w3.org/2002/07/owl#cardinality")
RESTRICTION = URI("http://www.w3.org/2002/07/owl#Restriction")
FUNC_PROP = URI("http://www.w3.org/2002/07/owl#FunctionalProperty")
ON_PROP = URI("http://www.w3.org/2002/07/owl#onProperty")
ONE = Literal("1")
class ThingFactory:
"""
Fed a store, return a factory that can be used to instantiate
Things into that world.
"""
def __init__(self, store, schema_store=None, alias_map=None):
"""
store - rdflib.Graph.Graph instance
schema_store - rdflib.Graph.Graph instance; defaults to store
"""
self.store = store
self.schema_store = schema_store or self.store
self.alias_map = alias_map or {}
def __call__(self, ident, **props):
"""
ident - either:
a) None (creates a new BNode)
b) rdflib.URIRef.URIRef instance
c) str in the form prefix_localname
props - dict of properties and values, to be added. If the value is a list, its
contents will be added to a ResourceSet.
returns Thing instance
"""
return Thing(self.store, self.schema_store, self.alias_map, ident, props)
def addAlias(self, alias, uri):
"""
Add an alias for an pythonic name to a URI, which overrides the
default prefix_localname syntax for properties and object names. Intended to
be used for URIs which are unmappable.
E.g.,
.addAlias("foobar", "http://example.com/my-unmappable-types#blah-type")
will map the .foobar property to the provided URI.
"""
self.alias_map[alias] = uri
class Thing:
""" An RDF resource, as uniquely identified by a URI. Properties
of the resource are avaiable as attributes; for example:
.prefix_localname is the property in the namespace mapped
to the "prefix" prefix, with the localname "localname".
A "python literal datatype" is a datatype that maps to a Literal type;
e.g., int, float, bool.
A "python data representation" is one of:
a) a python literal datatype
b) a self.__class__ instance
c) a list containing a and/or b
"""
def __init__(self, store, schema_store, alias_map, ident, props=None):
"""
store - rdflib.Graph.Graph
schema_store - rdflib.Graph.Graph
ident - either:
a) None (creates a new BNode)
b) rdflib.URIRef.URIRef instance
c) str in the form prefix_localname
props - dict of properties and values, to be added. If the value is a list, its
contents will be added to a ResourceSet.
"""
self._store = store
self._schema_store = schema_store
self._alias_map = alias_map
if ident is None:
self._id = BNode()
elif isinstance(ident, ID):
self._id = ident
else:
self._id = self._AttrToURI(ident)
if props is not None:
for attr, obj in props.items():
if type(obj) is type([]):
[self.__getattr__(attr).add(o) for o in obj]
else:
self.__setattr__(attr, obj)
def __getattr__(self, attr):
"""
attr - either:
a) str starting with _ (normal attribute access)
b) str that is a URI
c) str in the form prefix_localname
returns a python data representation or a ResourceSet instance
"""
if attr[0] == '_':
raise AttributeError
else:
if ":" in attr:
pred = URI(attr)
else:
try:
pred = self._AttrToURI(attr)
except ValueError:
raise AttributeError
if self._isUniqueObject(pred):
try:
obj = self._store.triples((self._id, pred, None)).next()[2]
except StopIteration:
raise AttributeError
return self._rdfToPython(pred, obj)
else:
return ResourceSet(self, pred)
def __setattr__(self, attr, obj):
"""
attr - either:
a) str starting with _ (normal attribute setting)
b) str that is a URI
c) str in the form prefix_localname
obj - a python data representation or a ResourceSet instance
"""
if attr[0] == '_':
self.__dict__[attr] = obj
else:
if ":" in attr:
pred = URI(attr)
else:
try:
pred = self._AttrToURI(attr)
except ValueError:
raise AttributeError
if self._isUniqueObject(pred):
self._store.remove((self._id, pred, None))
self._store.add((self._id, pred, self._pythonToRdf(pred, obj)))
elif isinstance(obj, ResourceSet) or type(obj) is type(set()):
ResourceSet(self, pred, obj.copy())
else:
raise TypeError
def __delattr__(self, attr):
"""
attr - either:
a) str starting with _ (normal attribute deletion)
b) str that is a URI
c) str in the form prefix_localname
"""
if attr[0] == '_':
del self.__dict__[attr]
else:
if ":" in attr:
self._store.remove((self._id, URI(attr), None))
else:
try:
self._store.remove((self._id, self._AttrToURI(attr), None))
except ValueError:
raise AttributeError
def _rdfToPython(self, pred, obj):
"""
Given a RDF predicate and object, return the equivalent Python object.
pred - rdflib.URIRef.URIRef instance
obj - rdflib.Identifier.Identifier instance
returns a python data representation
"""
obj_types = self._getObjectTypes(pred, obj)
if isinstance(obj, Literal): # typed literals
return self._literalToPython(obj, obj_types)
elif RDF.List in obj_types:
return self._listToPython(obj)
elif RDF.Seq in obj_types:
l, i = [], 1
while True:
counter = URI(RDF_SEQi % i)
try:
item = self._store.triples((obj, counter, None)).next()[2]
except StopIteration:
return l
l.append(self._rdfToPython(counter, item))
i += 1
elif isinstance(obj, ID):
return self.__class__(self._store, self._schema_store, self._alias_map, obj)
else:
raise ValueError
def _pythonToRdf(self, pred, obj):
"""
Given a Python predicate and object, return the equivalent RDF object.
pred - rdflib.URIRef.URIRef instance
obj - a python data representation
returns rdflib.Identifier.Identifier instance
"""
obj_types = self._getObjectTypes(pred, obj)
if RDF.List in obj_types:
blank = BNode()
self._pythonToList(blank, obj) ### this actually stores things...
return blank
elif RDF.Seq in obj_types: ### so will this
blank = BNode()
i = 1
for item in obj:
counter = URI(RDF_SEQi % i)
self._store.add((blank, counter, self._pythonToRdf(counter, item)))
i += 1
return blank
elif isinstance(obj, self.__class__):
if obj._store is not self._store:
obj.copyTo(self._store) ### and this...
return obj._id
else:
return self._pythonToLiteral(obj, obj_types)
def _literalToPython(self, obj, obj_types):
"""
obj - rdflib.Literal.Literal instance
obj_types - iterator yielding rdflib.URIRef.URIRef instances
returns a python literal datatype
"""
for obj_type in obj_types:
try:
return SchemaToPython[str(obj_type)][0](obj)
except KeyError:
pass
return SchemaToPythonDefault[0](obj)
def _pythonToLiteral(self, obj, obj_types):
"""
obj - a python literal datatype
obj_types - iterator yielding rdflib.URIRef.URIRef instances
returns rdflib.Literal.Literal instance
"""
for obj_type in obj_types:
try:
return Literal(SchemaToPython[str(obj_type)][1](obj))
except KeyError:
pass
return Literal(SchemaToPythonDefault[1](obj))
def _listToPython(self, subj):
"""
Given a RDF list, return the equivalent Python list.
subj - rdflib.Identifier.Identifier instance
returns list of python data representations
"""
try:
first = self._store.triples((subj, RDF.first, None)).next()[2]
except StopIteration:
return []
try:
rest = self._store.triples((subj, RDF.rest, None)).next()[2]
except StopIteration:
return ValueError
return [self._rdfToPython(RDF.first, first)] + self._listToPython(rest) ### type first?
def _pythonToList(self, subj, members):
"""
Given a Python list, store the eqivalent RDF list.
subj - rdflib.Identifier.Identifier instance
members - list of python data representations
"""
first = self._pythonToRdf(RDF.first, members[0])
self._store.add((subj, RDF.first, first))
if len(members) > 1:
blank = BNode()
self._store.add((subj, RDF.rest, blank))
self._pythonToList(blank, members[1:])
else:
self._store.add((subj, RDF.rest, RDF.nil))
def _AttrToURI(self, attr):
"""
Given an attribute, return a URIRef.
attr - str in the form prefix_localname
returns rdflib.URIRef.URIRef instance
"""
if self._alias_map.has_key(attr):
return URI(self._alias_map[attr])
else:
prefix, localname = attr.split("_", 1)
return URI("".join([self._store.namespace_manager.store.namespace(prefix), localname]))
def _URIToAttr(self, uri):
"""
Given a URI, return an attribute.
uri - str that is a URI
returns str in the form prefix_localname. Not the most efficient thing around.
"""
for alias, alias_uri in self._alias_map.items():
if uri == alias_uri:
return alias
for ns_prefix, ns_uri in self._store.namespace_manager.namespaces():
if ns_uri == uri[:len(ns_uri)]:
return "_".join([ns_prefix, uri[len(ns_uri):]])
raise ValueError
def _getObjectTypes(self, pred, obj):
"""
Given a predicate and an object, return a list of the object's types.
pred - rdflib.URIRef.URIRef instance
obj - rdflib.Identifier.Identifier instance
returns list containing rdflib.Identifier.Identifier instances
"""
obj_types = [o for (s, p, o) in self._schema_store.triples(
(pred, RDFS.range, None))]
if isinstance(obj, URI):
obj_types += [o for (s, p, o) in self._store.triples((obj, RDF.type, None))]
return obj_types
def _isUniqueObject(self, pred):
"""
Given a predicate, figure out if the object has a cardinality greater than one.
pred - rdflib.URIRef.URIRef instance
returns bool
"""
# pred rdf:type owl:FunctionalProperty - True
if (pred, RDF.type, FUNC_PROP) in self._schema_store:
return True
# subj rdf:type [ rdfs:subClassOf [ a owl:Restriction; owl:onProperty pred; owl:maxCardinality "1" ]] - True
# subj rdf:type [ rdfs:subClassOf [ a owl:Restriction; owl:onProperty pred; owl:cardinality "1" ]] - True
subj_types = [o for (s, p, o) in self._store.triples((self._id, RDF.type, None))]
for type in subj_types:
superclasses = [o for (s, p, o) in \
self._schema_store.triples((type, RDFS.subClassOf, None))]
for superclass in superclasses:
if (
(superclass, RDF.type, RESTRICTION) in self._schema_store and
(superclass, ON_PROP, pred) in self._schema_store
) and \
(
(superclass, MAX_CARD, ONE) in self._schema_store or
(superclass, CARD, ONE) in self._schema_store
): return True
return False
def __repr__(self):
return self._id
def __str__(self):
try:
return self._URIToAttr(self._id)
except ValueError:
return str(self._id)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self._id == other._id
elif isinstance(other, ID):
return self._id == other
def __ne__(self, other):
if self is other: return False
else: return True
def properties(self):
"""
List unique properties.
returns list containing self.__class__ instances
"""
return [self.__class__(self._store, self._schema_store, self._alias_map, p)
for (s,p,o) in self._store.triples((self._id, None, None))]
def copyTo(self, store):
"""
Recursively copy statements to the given store.
store - rdflib.Store.Store
"""
for (s, p, o) in self._store.triples((self._id, None, None)):
store.add((s, p, o))
if isinstance(o, (URI, BNode)):
self.__class__(self._store, self._schema_store, self._alias_map, o).copyTo(store)
class ResourceSet:
"""
A set interface to the object(s) of a non-unique RDF predicate. Interface is a subset
(har, har) of set().copy() returns a set.
"""
def __init__(self, subject, predicate, iterable=None):
"""
subject - rdflib.Identifier.Identifier instance
predicate - rdflib.URIRef.URIRef instance
iterable -
"""
self._subject = subject
self._predicate = predicate
self._store = subject._store
if iterable is not None:
for obj in iterable:
self.add(obj)
def __len__(self):
return len(list(
self._store.triples((self._subject._id, self._predicate, None))))
def __contains__(self, obj):
if isinstance(obj, self._subject.__class__):
obj = obj._id
else: ### doesn't use pythonToRdf because that might store it
obj_types = self._subject._getObjectTypes(self._predicate, obj)
obj = self._subject._pythonToLiteral(obj, obj_types)
return (self._subject._id, self._predicate, obj) in self._store
def __iter__(self):
for (s, p, o) in \
self._store.triples((self._subject._id, self._predicate, None)):
yield self._subject._pythonToRdf(self._predicate, o)
def copy(self):
return set(self)
def add(self, obj):
self._store.add((self._subject._id, self._predicate,
self._subject._pythonToRdf(self._predicate, obj)))
def remove(self, obj):
if not obj in self:
raise KeyError
self.discard(obj)
def discard(self, obj):
if isinstance(obj, self._subject.__class__):
obj = obj._id
else: ### doesn't use pythonToRdf because that might store it
obj_types = self._subject._getObjectTypes(self._predicate, obj)
obj = self._subject._pythonToLiteral(obj, obj_types)
self._store.remove((self._subject._id, self._predicate, obj))
def clear(self):
self._store.remove((self._subject, self._predicate, None))
SchemaToPythonDefault = (unicode, unicode)
SchemaToPython = { # (schema->python, python->schema) Does not validate.
'http://www.w3.org/2001/XMLSchema#string': (unicode, unicode),
'http://www.w3.org/2001/XMLSchema#normalizedString': (unicode, unicode),
'http://www.w3.org/2001/XMLSchema#token': (unicode, unicode),
'http://www.w3.org/2001/XMLSchema#language': (unicode, unicode),
'http://www.w3.org/2001/XMLSchema#boolean': (bool, lambda i:unicode(i).lower()),
'http://www.w3.org/2001/XMLSchema#decimal': (float, unicode),
'http://www.w3.org/2001/XMLSchema#integer': (long, unicode),
'http://www.w3.org/2001/XMLSchema#nonPositiveInteger': (int, unicode),
'http://www.w3.org/2001/XMLSchema#long': (long, unicode),
'http://www.w3.org/2001/XMLSchema#nonNegativeInteger': (int, unicode),
'http://www.w3.org/2001/XMLSchema#negativeInteger': (int, unicode),
'http://www.w3.org/2001/XMLSchema#int': (int, unicode),
'http://www.w3.org/2001/XMLSchema#unsignedLong': (long, unicode),
'http://www.w3.org/2001/XMLSchema#positiveInteger': (int, unicode),
'http://www.w3.org/2001/XMLSchema#short': (int, unicode),
'http://www.w3.org/2001/XMLSchema#unsignedInt': (long, unicode),
'http://www.w3.org/2001/XMLSchema#byte': (int, unicode),
'http://www.w3.org/2001/XMLSchema#unsignedShort': (int, unicode),
'http://www.w3.org/2001/XMLSchema#unsignedByte': (int, unicode),
'http://www.w3.org/2001/XMLSchema#float': (float, unicode),
'http://www.w3.org/2001/XMLSchema#double': (float, unicode), # doesn't do the whole range
# duration
# dateTime
# time
# date
# gYearMonth
# gYear
# gMonthDay
# gDay
# gMonth
# hexBinary
'http://www.w3.org/2001/XMLSchema#base64Binary': (base64.decodestring, lambda i:base64.encodestring(i)[:-1]),
'http://www.w3.org/2001/XMLSchema#anyURI': (str, str),
}
if __name__ == '__main__':
# use: "python -i sparta.py [URI for RDF file]+"
from rdflib.TripleStore import TripleStore
import sys
mystore = TripleStore()
for arg in sys.argv[1:]:
mystore.parse(arg)
thing = ThingFactory(mystore)