def setup(self): # Create a namespace object for the Friend of a friend namespace. self.FOAF = Namespace("http://xmlns.com/foaf/0.1/") self.TRUST = Namespace("http://www.abundantplunder.com/trust/owl/trust.owl#") self.WOT = Namespace("http://xmlns.com/wot/0.1/") self.RDF = Namespace("http://www.w3.org/2000/01/rdf-schema#") # load trust values into list for later trust = TripleStore() trust.load("http://www.abundantplunder.com/trust/owl/trust.owl#") self.trustValues = [] for s in trust.subjects(self.RDF["subPropertyOf"], self.TRUST["trustValue"]): self.trustValues.append(s)
def handle__t__test(self, testURI="http://www.w3.org/TR/owl-test/Manifest.rdf"): """Load a test description (manifest) and run the tests. Testing is done in a manner set by previous options. (such as...?) Reasonable options include all the various RDF and OWL tests, such as in http://www.w3.org/2002/03owlt/editors-draft/draft/Manifest.rdf """ store = TripleStore() print "Loading %s..." % testURI, store.load(testURI) print " Done." resultStore = TripleStore() try: runTests(store, resultStore) except KeyboardInterrupt, k: print "KeyboardInterrupt"
def setup(self): # Create a namespace object for the Friend of a friend namespace. # figure out trailing pound thing... #self.FOAF = Namespace(self.server.config.foaf_url + "#") #self.TRUST = Namespace(self.server.config.trust_url + "#") #self.WOT = Namespace(self.server.config.wot_url + "#") #self.RDF = Namespace(self.server.config.rdf_url + "#") self.FOAF = Namespace("http://xmlns.com/foaf/0.1/#") self.TRUST = Namespace("http://brondsema.gotdns.com/svn/dmail/schema/tags/release-1.0/trust.owl#") self.WOT = Namespace("http://xmlns.com/wot/0.1/#") self.RDF = Namespace("http://www.w3.org/2000/01/rdf-schema#") # load trust values into list for later trust = TripleStore() #trust.load(self.server.config.trust_url) trust.load("http://brondsema.gotdns.com/svn/dmail/schema/tags/release-1.0/trust.owl#") self.trustValues = [] for s in trust.subjects(self.RDF["subPropertyOf"], self.TRUST["trustValue"]): self.trustValues.append(s)
def validate(self, uri_fingerprint, require_hex_fpr=1): """validate the format of the document""" FOAF = Namespace("http://xmlns.com/foaf/0.1/") TRUST = Namespace("http://www.konfidi.org/ns/trust/1.2#") WOT = Namespace("http://xmlns.com/wot/0.1/") RDF = Namespace("http://www.w3.org/2000/01/rdf-schema#") store = TripleStore() # TODO: verify all <truster>s have fingerprints # and that they're all the same try: store.parse(StringInputSource(self.content)) except SAXParseException: raise FOAFServerError, "invalid XML: " + str(sys.exc_info()[1]) fingerprint = last_fingerprint = None for (relationship, truster) in store.subject_objects(TRUST["truster"]): for (key) in store.objects(truster, WOT["hasKey"]): fingerprint = store.objects(key, WOT["fingerprint"]).next() if last_fingerprint: if fingerprint != last_fingerprint: raise FOAFServerError, "All wot:fingerprint's from trust:truster's PubKeys must be the same. Found '%s' and '%s'" % (fingerprint, last_fingerprint) last_fingerprint = fingerprint # per http://xmlns.com/wot/0.1/, we really shouldn't replace these fingerprint = fingerprint.replace(" ", "") fingerprint = fingerprint.replace(":", "") if require_hex_fpr and not(ishex(fingerprint)): raise FOAFServerError, "Invalid fingerprint format; must be hex" if uri_fingerprint and uri_fingerprint != fingerprint: raise FOAFServerError, "URI fingerprint doesn't match FOAF fingerprint" return fingerprint
def load(self, source): print "Update Listener: parsing input: %s" % source # this is the main object we're concerned with trust = TripleStore() trust.load(source) # new version count = 0 for (relationship, truster) in trust.subject_objects(self.TRUST["truster"]): # clean up the fingerprints source_fingerprint = trust.objects(truster, self.WOT["fingerprint"]).next() sink_fingerprint = trust.objects(trust.objects(relationship, self.TRUST["trusted"]).next(), self.WOT["fingerprint"]).next() # turn these off for now, for our test cases. figure a better solution later source_fingerprint = re.sub(r'[^0-9A-Z]', r'', source_fingerprint.upper()) sink_fingerprint = re.sub(r'[^0-9A-Z]', r'', sink_fingerprint.upper()) source = self.server.getPerson(source_fingerprint) sink = self.server.getPerson(sink_fingerprint) for item in trust.objects(relationship, self.TRUST["about"]): topic = trust.objects(item, self.TRUST["topic"]).next().split("#")[1] rating = float(trust.objects(item, self.TRUST["rating"]).next()) if rating >= 0.0 and rating <= 1.0: source.addTrustLink(sink.getFingerprint(), topic, rating) count += 1 return "Added %d trust links." % count
def __init__(self, subject, rdfStore=None): """ Creates a new rdfDict given the particular subject and an optional TripleStore (rdfStore). If no TripleStore is provided, creates a new one. """ # store the subject self.subject = subject # store or create the triple store if rdfStore is None: self.store = TripleStore() else: self.store = rdfStore
def extractXMPTriples(fname, triples=None): """Extract the XMP RDF data for PDF and JPG files and return and RDFLib triple store. If the triples parameter is not None, then it is considered to be an already existing triple store that has to be extended by the new set of triples. @param fname: the filename for the image or the pdf file @type fname: a string, denoting the file name @param triples: an RDFLib TripleStore (default: None) @type triples: rdflib.TripleStore @return: triples @rtype: RDFLib TripleStore """ rdf = extractXMP(fname) # If it is at that point, no exception has been raised, ie, the rdf content exists # # Note the import here, not in the header; the module should be usable without RDFLib, too... from rdflib.TripleStore import TripleStore if triples == None: triples = TripleStore() # The logical thing to do would be to wrap rdf into a StringIO and load it into the triples # but that does not work with TripleStore, which expects a file name (or I have not found other means) # Ie, the rdf content should be stored in a temporary file. tempfile = fname + "__.rdf" store = file(tempfile, "w") store.write(rdf) store.flush() store.close() triples.load(tempfile) try: # on Windows this may not work... os.remove(tempfile) except: # This works only when called from cygwin. However, is there anybody in his/her able mind # using Windows and python without some sort of a unix emulation ;-) os.system("rm %s" % tempfile) return triples
def load(self, source): # TODO: don't let duplicate trust levels on certain subjects be entered! print "Update Listener: parsing input" # this is the main object we're concerned with store = TripleStore() store.load(source) # For each foaf:Person in the store print out its mbox property. truster = store.subjects(self.TRUST["trusts"]).next() f = store.objects(truster, self.WOT["fingerprint"]).next() p = self.server.getPerson(f) for trustee in store.objects(truster, self.TRUST["trusts"]): f2 = store.objects(trustee, self.WOT["fingerprint"]).next() # we do this to make sure they exist. p2 = self.server.getPerson(f2) for value, resource in store.predicate_objects(trustee): if value in self.trustValues: p.addTrustLink(f2, resource.split("#")[1], resource, TrustValue.TrustValue(value.split("#")[1]))
class rdfStore: """ Provides RDF parsing and output functions for CC license and work definitions. """ def __init__(self): # initialize the TripleStore for managing RDF self.store = TripleStore() def parse(self, rdf): """ Parse the given String, rdf, into it's component triples. """ self.store.parse( StringInputSource (rdf) ) def subjects(self): """A generator which successivly returns each subject contained in the store, wrapped in an instance of rdfDict.""" for subject in self.store.subjects(): yield rdfDict(subject, store=self.store) def output(self): """ Return a string containing the RDF representation of the licenses and works.""" if self.store is not None: rdf = cStringIO.StringIO() self.store.serialize(stream=rdf) return rdf.getvalue() else: return "" __str__ = output def append(self, newItem): """ Adds a new work or license to the RDF store. """ # make sure the stores aren't the same if (newItem.store is not self.store): # add each triple from the newItem's store to this store for triple in newItem.store.triples(): self.store.add(triple)
def __init__(self, source='', defaultStatements=(), context='', **kw): ntpath, stmts, format = _loadRDFFile(source, defaultStatements, context) if format == 'unsupported': self.format = 'nt' self.path = ntpath else: self.format = (format == 'ntriples' and 'nt') or (format == 'rdfxml' and 'xml') or 'error' assert self.format != 'error', 'unexpected format' self.path = source from rdflib.TripleStore import TripleStore RDFLibModel.__init__(self, TripleStore()) for stmt in stmts: self.addStatement(stmt)
def load(self, source): print "Update Listener: parsing input: %s" % source # this is the main object we're concerned with store = TripleStore() store.load(source) # For each foaf:Person in the store print out its mbox property. truster = store.subjects(self.TRUST["trusts"]).next() f = store.objects(truster, self.WOT["fingerprint"]).next() p = self.server.getPerson(f) for trustee in store.objects(truster, self.TRUST["trusts"]): f2 = store.objects(trustee, self.WOT["fingerprint"]).next() # we do this to make sure they exist. p2 = self.server.getPerson(f2) for value, resource in store.predicate_objects(trustee): if value in self.trustValues: self.server.lock.acquire_write() #time.sleep(15) p.addTrustLink(f2, resource.split("#")[1], resource, BasicTrustValue(value.split("#")[1])) self.server.lock.release_write()
""" read XMP xml files """ # see http://www.xml.com/lpt/a/1107 # see also raptor-utls # rapper -o ntriples http://planetrdf.com/guide/rss.rdf # rapper -o ntriples ../tests/fixture/xmp/sample_xmp.rdf from rdflib.TripleStore import TripleStore from rdflib.Namespace import Namespace ns_dc = Namespace("http://purl.org/dc/elements/1.1/") ns_pr = Namespace("http://prismstandard.org/1.0#") store = TripleStore() store.load("../tests/fixture/xmp/sample_xmp.rdf") # print dir(store) quit() # For all triples that have prism:publicationTime as their predicate, for s, o in store.subject_objects(ns_pr["publicationTime"]): # if the triples' object is greater than the cutoff date, if o > cutOffDate: # print the date, author name, and title. print o, for object in store.objects(s, ns_dc["creator"]): print object + ": ", for object in store.objects(s, ns_dc["title"]): print object
def __init__(self): # initialize the TripleStore for managing RDF self.store = TripleStore()
def get_model(): model = TripleStore() model.load("file:/home/httpd/htdocs/foaf.rdf") return model
people[source][prop].append(i) if len(people) < 1: sources = model.subjects(FOAF['nick'], Literal(name_or_nick)) for source in sources: people[source] = {} props = get_props() for prop in props.keys(): people[source][prop] = list() available = model.objects(source, URIRef(props[prop][1])) for i in available: people[source][prop].append(i) return people if __name__ == "__main__": mem_model = TripleStore() wordlist = get_words() FOAF = Namespace("http://xmlns.com/foaf/0.1/") GEO = Namespace("http://www.w3.org/2003/01/geo/wgs84_pos#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") DC = Namespace("http://purl.org/dc/elements/1.1/") CYC = Namespace("http://opencyc.sourceforge.net/daml/cyc.daml#") print "Image Annotation Tool" print "Enter the URI of a photo to annotate:" uri = raw_input("> ") mem_model.add((URIRef(uri), URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), URIRef("http://xmlns.com/foaf/0.1/Image"))) print "Should I add a thumbnail for this image, by adding '.sized' before the extension?" thumbnail = raw_input("> ") if thumbnail:
from rdflib.URIRef import URIRef from rdflib.Literal import Literal from rdflib.BNode import BNode from rdflib.Namespace import Namespace from rdflib.constants import TYPE from rdflib.TripleStore import TripleStore t = TripleStore() t.load("example.rdf", format="xml") print t
class rdfDict: """ Provides a dictionary-like wrapper around a set of RDF triples with a common subject. In addition to the standard dictionary interface provides convenience methods for manipulating the triples. """ def __init__(self, subject, rdfStore=None): """ Creates a new rdfDict given the particular subject and an optional TripleStore (rdfStore). If no TripleStore is provided, creates a new one. """ # store the subject self.subject = subject # store or create the triple store if rdfStore is None: self.store = TripleStore() else: self.store = rdfStore def __str__(self): """ Return the string representation of this instance using an algorithm inspired by the Dublic Core dumb-down method. """ output_str = '' pairs = [] type_item = None for key in self: if (key.find("#type") != -1): type_item = key else: pairs.append((key, self.getAll(key))) output_str = str(self.getFirst(type_item)) + ": " for pair in pairs: output_str = '%s %s: %s;' % (output_str, str(pair[0]), ", ".join([str(n) for n in pair[1]]) ) return output_str def about(self): """ Return the subject used to create the instance (usually equivalent to rdf:about. """ return self.subject def __getvalues(self, key): """ Returns a list of values for a particular key; coerces BNodes to rdfDicts and mangles Literals with language attributes (if available). """ values = [ n for n in self.store.objects(subject=self.subject, predicate=key) ] result = [] for value in values: if (isinstance(value, BNode)): # coerce to rdfDict result.append(rdfDict(value, self.store)) else: result.append(value) return result def __getitem__(self, key): """ Return the object described in RDF with a subject of self.subject and a predicate of key. If more than one match is found, raises an AmbiguousKeyError. """ result = self.__getvalues(key) if (len(result) == 0): # no item was found, throw an exception raise KeyError() elif (len(result) > 1): # check if there is more than one option raise AmbiguousKeyError() else: # otherwise return object value return result[0] def getFirst(self, key): """ Returns the first object having the predicate key. If no match is found returns None. """ if ( (self.subject, URIRef(key), None) in self.store): return self.__getvalues(key)[0] else: return None def getAll(self, key): """ Returns a list of objects which have a predicate of key. The list may be empty or contain only a single element. """ return self.__getvalues(key) def __setitem__(self, key, value): """ Adds an RDF triple of the values (self.subject, key, value); any objects with the same subject/predicate are replaced. """ if (self.subject, key, none) in self.store: del self[key] self.store.add( (self.subject, key, value) ) def add (self, key, value): """ Adds an RDF triple consisting of the subject, key and value. """ self.store.add( (self.subject, key, value) ) def addAll (self, key, values): """ Adds the list of objects in values with the same subject and predicate. """ for value in values: self.add (key, value) def __len__(self): """ Returns the number of predicate-object pairs associated with the subject self.subject. """ return len(self.store) def __delitem__(self, key): """ Removes all items with the given key. """ if (self.subject, key, None) in self.store: self.store.remove( (self.subject, key, None) ) else: raise KeyError() def remove (self, key, value): """ Removes a specific key-value pair. """ self.store.remove( (self.subject, key, value) ) def __iter__(self): """ Returns an iterator over the unique keys (predicates) for the given subject. """ return iter(sets.Set(self.store.predicates(subject=self.subject))) iterkeys = __iter__ def __contains__(self, key): """ Returns true if the given key appears as a predicate of the subject. """ return ( (self.subject, key, None) in self.store )
from rdflib.URIRef import URIRef from rdflib.Literal import Literal from rdflib.BNode import BNode from rdflib.Namespace import Namespace from rdflib.constants import TYPE # Import RDFLib's default TripleStore implementation. from rdflib.TripleStore import TripleStore # Create a namespace object for the Friend of a friend namespace. FOAF = Namespace("http://xmlns.com/foaf/0.1/") store = TripleStore() store.prefix_mapping("dc", "http://http://purl.org/dc/elements/1.1/") store.prefix_mapping("foaf", "http://xmlns.com/foaf/0.1/") # Create an identifier to use as the subject for Donna. donna = BNode() from rdflib.constants import DATATYPE # Add triples using store's add method. store.add((donna, TYPE, FOAF["Person"])) store.add((donna, FOAF["nick"], Literal("donna"))) store.add((donna, FOAF["name"], Literal("Donna Fales"))) # Iterate over triples in store and print them out. print "--- printing raw triples ---" for s, p, o in store: print s, p, o
if not form.has_key('description'): print 'Content-Type: text/html\r' print '\r' print "<H1>Error</H1>" print "Please fill in the 'description' field with an appropriate Turtle graph." else: tmpfile = mkstemp()[1] data = convert(form['description'].value, 'turtle', 'ntriples', infile=tmpfile) graph = TripleStore() graph.parse(StringIO(data), format='nt') thisURI = URIRef('http://%s%s' % (os.environ['HTTP_HOST'], os.environ['REQUEST_URI'])) graphNode = URIRef('file://%s' % tmpfile) FOAF = Namespace("http://xmlns.com/foaf/0.1/") try: bnode = graph.objects(graphNode, FOAF["primaryTopic"]).next() except StopIteration: print 'Content-Type: text/plain\r' print '\r' print 'no primary topic given'
'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)
for i in available: people[source][prop].append(i) if len(people) < 1: sources = model.subjects(FOAF['nick'], Literal(name_or_nick)) for source in sources: people[source] = {} props = get_props() for prop in props.keys(): people[source][prop] = list() available = model.objects(source, URIRef(props[prop][1])) for i in available: people[source][prop].append(i) return people if __name__ == "__main__": mem_model = TripleStore() wordlist = get_words() FOAF = Namespace("http://xmlns.com/foaf/0.1/") GEO = Namespace("http://www.w3.org/2003/01/geo/wgs84_pos#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") DC = Namespace("http://purl.org/dc/elements/1.1/") CYC = Namespace("http://opencyc.sourceforge.net/daml/cyc.daml#") print "Image Annotation Tool" print "Enter the URI of a photo to annotate:" uri = raw_input("> ") mem_model.add((URIRef(uri), URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), URIRef("http://xmlns.com/foaf/0.1/Image"))) print "Should I add a thumbnail for this image, by adding '.sized' before the extension?" thumbnail = raw_input("> ") if thumbnail: thumb = "%ssized.%s"%(uri[:-3],uri[-3:]) mem_model.add((URIRef(uri), FOAF['thumbnail'], URIRef(thumb)))
'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)
from rdflib.TripleStore import TripleStore from rdflib.constants import DATATYPE import Person import TrustConnection import TrustSubject import TrustValue # Create a namespace object for the Friend of a friend namespace. FOAF = Namespace("http://xmlns.com/foaf/0.1/") TRUST = Namespace("http://www.abundantplunder.com/trust/owl/trust.owl#") WOT = Namespace("http://xmlns.com/wot/0.1/") RDF = Namespace("http://www.w3.org/2000/01/rdf-schema#") # this is the main object we're concerned with store = TripleStore() store.load("example2.rdf") # master dictionary containing all the people # will a plain old dictionary suffice, or do I need a hashtable? people = {} # load trust values into list for later trust = TripleStore() trust.load("http://www.abundantplunder.com/trust/owl/trust.owl#") trustValues = [] for s in trust.subjects(RDF["subPropertyOf"], TRUST["trustValue"]): trustValues.append(s) # For each foaf:Person in the store print out its mbox property. print "--- printing trust: ---"