def labchords2RDF(infilename, outfilename, format="xml", audiofilename=None, withdescriptions=False): if withdescriptions: commonchords = ConjunctiveGraph() commonchords.load("CommonChords.rdf") extrachords = ConjunctiveGraph() infile = open(infilename, 'r') lines = infile.readlines() mi = mopy.MusicInfo() homepage = mopy.foaf.Document("http://sourceforge.net/projects/motools") mi.add(homepage) program = mopy.foaf.Agent() program.name = "labchords2RDF.py" program.homepage = homepage mi.add(program) tl = RelativeTimeLine("#tl") tl.label = "Timeline derived from "+infilename tl.maker = program mi.add(tl) intervalNum = 0 for line in lines: i = Interval("#i"+str(intervalNum)) try: [start_s, end_s, label] = parseLabLine(line) i.beginsAtDuration = secondsToXSDDuration(start_s) i.endsAtDuration = secondsToXSDDuration(end_s) #i.label = "Interval containing "+label+" chord." i.onTimeLine = tl # Produce chord object for the label : chordURI = "http://purl.org/ontology/chord/symbol/"+label.replace("#","s").replace(",","%2C") if withdescriptions and \ len(list(commonchords.predicate_objects(URIRef(chordURI)))) == 0 and \ len(list(extrachords.predicate_objects(URIRef(chordURI)))) == 0: # Deref to grab chord info print "loading "+chordURI+"..." extrachords.load(chordURI) c = mopy.chord.Chord(chordURI) c_event = mopy.chord.ChordEvent("#ce"+str(intervalNum)) c_event.chord = c c_event.label = label c_event.time = i except Exception, e: raise Exception("Problem parsing input file at line "+str(intervalNum+1)+" !\n"+str(e)) mi.add(i) mi.add(c) mi.add(c_event) intervalNum+=1
def get_graph(self, with_mappings=False, include_mapping_target=False, acceptance=False, target_uri=None): """Get Graph instance of this EDMRecord. :param target_uri: target_uri if you want a sub-selection of the whole graph :param acceptance: if the acceptance data should be listed :param include_mapping_target: Boolean also include the mapping target triples in graph :param with_mappings: Boolean integrate the ProxyMapping into the graph """ rdf_string = self.source_rdf if acceptance and self.acceptance_rdf: rdf_string = self.acceptance_rdf graph = ConjunctiveGraph(identifier=self.named_graph) graph.namespace_manager = namespace_manager graph.parse(data=rdf_string, format='nt') if with_mappings: proxy_resources, graph = ProxyResource.update_proxy_resource_uris(self.dataset, graph) self.proxy_resources.add(*proxy_resources) for proxy_resource in proxy_resources: graph = graph + proxy_resource.to_graph(include_mapping_target=include_mapping_target) if target_uri and not target_uri.endswith("/about") and target_uri != self.document_uri: g = Graph(identifier=URIRef(self.named_graph)) subject = URIRef(target_uri) for p, o in graph.predicate_objects(subject=subject): g.add((subject, p, o)) graph = g return graph
def get_dbpedia_resource_triples(uri, lang): g = ConjunctiveGraph('SPARQLStore') g.open(get_dbpedia_endpoint(lang)) triples = [] for p, o in g.predicate_objects(URIRef(uri)): if isinstance(o, Literal): triples.append({ 'p': unicode(p), 'o': unicode(o), 'lang': o.language }) return triples
def get_dbpedia_resource_triples(uri, lang): g = ConjunctiveGraph('SPARQLStore') g.open(get_dbpedia_endpoint(lang)) triples = [] for p, o in g.predicate_objects(URIRef(uri)): if isinstance(o, Literal): triples.append({ 'p': unicode(p), 'o': unicode(o), 'lang': o.language }) return triples
def __init__(self, conn, name): user = irods.irodsUser(conn, name) self.id = user.getId() self.username = id self.email = "" self.address = "" self.tel = "" self.realName = "" self.description = "" self.flags = {} umd = user.getUserMetadata() for u in umd: if u[0] == 'rdf': # try to parse try: g = ConjunctiveGraph() except: continue for (key,val) in NS.iteritems(): g.bind(key, val) data = StringInputSource(umd[1]) try: if umd[2]: g.parse(data, umd[2]) else: g.parse(data) me = NS['demo']['users/%s'] % self.id for (p,o) in g.predicate_objects(me): if predicateMap.has_key(p): setattr(self, predicateMap[p], str(o)) except: # rdf exists, could parse, but is broken raise elif u[0] in self.simpleFields: setattr(self, u[0], u[1]) elif u[0] == 'flags': # should be a {} of flag : [obj, obj] # xxx pass
def __init__(self, conn, name): user = irods.irodsUser(conn, name) self.id = user.getId() self.username = id self.email = "" self.address = "" self.tel = "" self.realName = "" self.description = "" self.flags = {} umd = user.getUserMetadata() for u in umd: if u[0] == 'rdf': # try to parse try: g = ConjunctiveGraph() except: continue for (key, val) in NS.iteritems(): g.bind(key, val) data = StringInputSource(umd[1]) try: if umd[2]: g.parse(data, umd[2]) else: g.parse(data) me = NS['demo']['users/%s'] % self.id for (p, o) in g.predicate_objects(me): if predicateMap.has_key(p): setattr(self, predicateMap[p], str(o)) except: # rdf exists, could parse, but is broken raise elif u[0] in self.simpleFields: setattr(self, u[0], u[1]) elif u[0] == 'flags': # should be a {} of flag : [obj, obj] # xxx pass
description = ns.R7zDsGb0eQYf6uJETHG3qBx # predicate for dataprop (description) newAsana = ns.newElement1 positiveAffect = rdfGraph.subjects(RDFS.label, Literal("положительно влияет на", "ru")).__next__() negativeAffect = rdfGraph.subjects(RDFS.label, Literal("отрицательно влияет на", "ru")).__next__() backbone = rdfGraph.subjects(RDFS.label, Literal("Позвоночник", lang="ru")).__next__() print(f"\nLabel of root element is {rdfGraph.label(asana)}") print("\nFull information of root element:") for po in rdfGraph.predicate_objects(asana): print(po) print("\nGetting all instances for type of root element") printElements(rdfGraph) #Adding new asana bnode = BNode() # class relations rdfGraph.add((newAsana, RDF.type, asana)) rdfGraph.add((newAsana, RDF.type, bnode)) rdfGraph.add((newAsana, RDFS.label, Literal("Новая асана", lang="ru"))) rdfGraph.add((newAsana, description, Literal("Описание процесса выполнения", datatype=XSD.string))) rdfGraph.add((bnode, OWL.onProperty, URIRef(negativeAffect))) rdfGraph.add((bnode, OWL.someValuesOf, URIRef(backbone)))
def GScsv2RDF(infilename, outfilename, format="xml", withdescriptions=False): if withdescriptions: commonchords = ConjunctiveGraph() commonchords.load("CommonChords.rdf") extrachords = ConjunctiveGraph() lines = open(infilename).readlines() # # Initial model bits # mi = mopy.MusicInfo() homepage = mopy.foaf.Document("http://sourceforge.net/projects/motools") mi.add(homepage) program = mopy.foaf.Agent() program.name = "GScsv2RDF.py" program.homepage = homepage mi.add(program) tl = TimeLine("#tl") tl.label = "Timeline derived from "+infilename tl.maker = program mi.add(tl) [artistStr, titleStr] = [f.strip() for f in lines[0].split("\t")] # Add artist & title metadata signal = Signal() signal.time = sig_int = Interval() sig_int.label="Whole signal interval"; sig_int.beginsAtDuration = secondsToXSDDuration(0); sig_int.onTimeLine = tl signal.published_as = track = Track() artist = MusicArtist() artist.made = track artist.name = artistStr track.title = titleStr mi.add(sig_int) mi.add(signal) mi.add(track) mi.add(artist) lineNum = 1 segmentNum = 0 thisSegment_i = None chordSymbol='' t_secs = 0.0 for line in lines[1:]: # print "parsing line "+str(lineNum) try: lastChordSymbol = chordSymbol t_secs = getTimestamp(line) chordSymbol = getChordSymbol(line) if chordSymbol != lastChordSymbol: # print " handling new chord symbol" segmentNum += 1 lastSegment_i = thisSegment_i thisSegment_i = Interval("#i_"+str(segmentNum)) thisSegment_i.beginsAtDuration = secondsToXSDDuration(t_secs) if lastSegment_i != None: # print " terminating last interval" lastSegment_i.endsAtDuration = secondsToXSDDuration(t_secs) thisSegment_i.intervalAfter = lastSegment_i lastSegment_i.intervalBefore = thisSegment_i mi.add(thisSegment_i) chordURI = "http://purl.org/ontology/chord/symbol/"+chordSymbol.replace("#","s").replace(",","%2C") if withdescriptions and \ len(list(commonchords.predicate_objects(URIRef(chordURI)))) == 0 and \ len(list(extrachords.predicate_objects(URIRef(chordURI)))) == 0: # Deref to grab chord info print "loading <"+chordURI+">..." extrachords.load(chordURI) c = Chord(chordURI) c_event = ChordEvent("#ce_"+str(segmentNum)) c_event.chord = c c_event.time = thisSegment_i c_event.label = chordSymbol mi.add(c); mi.add(c_event); # print " added new chord event for "+chordURI except Exception, e: print("ERROR : Problem parsing input file at line "+str(lineNum)+" !\n") raise lineNum+=1
def mma2RDF(infilename, outfilename, format="xml", audiofilename=None, withdescriptions=False): if withdescriptions: commonchords = ConjunctiveGraph() commonchords.load("CommonChords.rdf") extrachords = ConjunctiveGraph() # Compile mma file and grab output lines = os.popen(mmabin + ' "' + infilename + '" -nrw').readlines() print "\n".join(lines) # # Initial model bits # mi = mopy.MusicInfo() homepage = mopy.foaf.Document("http://sourceforge.net/projects/motools") mi.add(homepage) program = mopy.foaf.Agent() program.name = "mma2RDF.py" program.homepage = homepage mi.add(program) tl = TimeLine("#tl") tl.label = "Timeline derived from " + infilename tl.maker = program mi.add(tl) # extract tempo from mma file tempo = 60 mmafile = open(infilename, "r") for line in mmafile: if line.startswith("Tempo "): tempo = int(line[len("Tempo ") :].strip().split()[0]) print "Found tempo = " + str(tempo) break lineNum = 1 thisBar_i = None i = None t_secs = 0.0 for line in lines: print "parsing line " + str(lineNum) try: # i = None barNum = getBarNum(line) lastBar_i = thisBar_i thisBar_i = Interval("#i_" + str(barNum)) thisBar_i.beginsAtDuration = secondsToXSDDuration(t_secs) if lastBar_i != None: lastBar_i.endsAtDuration = secondsToXSDDuration(t_secs) thisBar_i.intervalAfter = lastBar_i lastBar_i.intervalBefore = thisBar_i mi.add(thisBar_i) chordMMASymbols = getChordSymbols(line) beatNum = 1 for chordMMASymbol in chordMMASymbols: if chordMMASymbol != "/": print " handling new chord symbol" if i != None: print " terminating last interval" i.endsAtDuration = secondsToXSDDuration(t_secs) mi.add(i) i = Interval("#i_" + str(barNum) + "_" + str(beatNum)) i.onTimeLine = tl i.beginsAtDuration = secondsToXSDDuration(t_secs) chordURI = "http://purl.org/ontology/chord/symbol/" + mmaSymbolToChordSymbol( chordMMASymbol ).replace("#", "s").replace(",", "%2C") if ( withdescriptions and len(list(commonchords.predicate_objects(URIRef(chordURI)))) == 0 and len(list(extrachords.predicate_objects(URIRef(chordURI)))) == 0 ): # Deref to grab chord info print "loading <" + chordURI + ">..." extrachords.load(chordURI) c = Chord(chordURI) c_event = ChordEvent("#ce_" + str(barNum) + "_" + str(beatNum)) c_event.chord = c c_event.time = i c_event.label = mmaSymbolToChordSymbol(chordMMASymbol) mi.add(c) mi.add(c_event) mi.add(i) print " added new chord event for " + chordURI else: if beatNum == 1: # Need to continue the last seen chord print " continuing last bar's chord" # i = Interval("i_"+str(barNum)+"_"+str(beatNum)) # i.onTimeLine = tl # i.beginsAtDuration = secondsToXSDDuration(t_secs) # c_event = ChordEvent("ce_"+str(barNum)+"_"+str(beatNum)) # c_event.chord = c # c_event.time = i # mi.add(c_event); mi.add(i) beatNum += 1 t_secs += 60.0 / tempo except Exception, e: print ("ERROR : Problem parsing input file at line " + str(lineNum) + " !\n") raise lineNum += 1
# from pprint import pprint pprint(list(primer)) # just think .whatever((s, p, o)) # here we report on what we know pprint(list(primer.subjects())) pprint(list(primer.predicates())) pprint(list(primer.objects())) # and other things that make sense # what do we know about pat? pprint(list(primer.predicate_objects(myNS.pat))) # who is what age? pprint(list(primer.subject_objects(myNS.age))) # Okay, so lets now work with a bigger # dataset from the example, and start # with a fresh new graph. primer = ConjunctiveGraph() # Lets start with a verbatim string straight from the primer text: mySource = """