def statementAddedSlot(self, statement): predicateUri = statement.predicate().uri() predicate = Nepomuk.Types.Property(predicateUri) #if the range of the predicate is a literal, return if not predicate.range().isValid(): return #the table doesn't display type relations if predicateUri == Soprano.Vocabulary.RDF.type(): return subjectUri = statement.subject().uri() objectUri = statement.object().uri() if self.resource and subjectUri == self.resource.resourceUri(): #check that the object is a resource, not a literal #TODO: improve this check if str(objectUri.toString()).find( "http://www.w3.org/2001/XMLSchema#") < 0: object = Nepomuk.Resource(objectUri) self.table.model().sourceModel().addRelation( predicate, object, True) elif self.resource and objectUri == self.resource.resourceUri(): subject = Nepomuk.Resource(subjectUri) self.table.model().sourceModel().addRelation( predicate, subject, False)
def updateFields(self): super(PropertyEditorUi, self).updateFields() if self.editor.resource: domainUri = QUrl( self.editor.resource.property( Soprano.Vocabulary.RDFS.domain()).toString()) domainResource = Nepomuk.Resource(domainUri) self.domain.setText(domainResource.genericLabel()) rangeUri = QUrl( self.editor.resource.property( Soprano.Vocabulary.RDFS.range()).toString()) if str(rangeUri.toString()).find( "http://www.w3.org/2001/XMLSchema") == 0: self.isLiteral.setChecked(True) idx = self.literalBox.findData(QVariant(rangeUri.toString())) if idx > 0: self.literalBox.setCurrentIndex(idx) else: self.isLiteral.setChecked(False) rangeResource = Nepomuk.Resource(rangeUri) self.range.setText(rangeResource.genericLabel()) self.stack.setCurrentWidget(self.rangeClassWidget) else: domainResource = Nepomuk.Resource(self.editor.domainUri) self.domain.setText(domainResource.genericLabel())
def statementRemovedSlot(self, statement): predicateUri = statement.predicate().uri() predicate = Nepomuk.Types.Property(predicateUri) if not predicate.range().isValid(): return subjectUri = statement.subject().uri() objectUri = statement.object().uri() subject = Nepomuk.Resource(subjectUri) object = Nepomuk.Resource(objectUri) if self.resource == subject or self.resource == object: self.table.model().sourceModel().removeRelation( subject, predicate, object)
def scrap1(): url = QUrl("nepomuk:/res/a8b8ed53-3f5e-4199-b824-f7f0360408c5") res = Nepomuk.Resource(url) print res print res.genericIcon() print "finishing"
def tag_danbooru_item(filename, tags, blacklist=None, board_url=None): """Tag a file using a specific :class:`DanbooruItem` tags.""" resource_manager = Nepomuk.ResourceManager.instance() if not resource_manager.initialized(): # Nepomuk not running - bail out return absolute_path = QtCore.QFileInfo(filename).absoluteFilePath() resource = Nepomuk.File(KUrl(absolute_path)) for tag in tags: if blacklist is not None and tag in blacklist: continue nepomuk_tag = Nepomuk.Tag(tag) nepomuk_tag.setLabel(tag) resource.addTag(nepomuk_tag) if board_url is not None: website_resource = Nepomuk.Resource(board_url) website_resource.addType(Nepomuk.Vocabulary.NFO.Website()) website_resource.setLabel(board_url.prettyUrl()) resource.setDescription( i18n("Retrieved from %1").arg(board_url.prettyUrl())) resource.addIsRelated(website_resource)
def findInverseRelationsTemp(uri): resource = Nepomuk.Resource(uri) relations = dict() props = resourceTypesProperties(resource) for property in props: #skip the RDF.type() property, otherwise for classes we get all their instances if property.uri() == Soprano.Vocabulary.RDF.type(): continue irel = Nepomuk.ResourceManager.instance().allResourcesWithProperty( property.uri(), Nepomuk.Variant(resource)) if len(irel) > 0 and relations.has_key(property.uri().toString()): relations[property.uri().toString()] = relations[ property.uri().toString()].union(irel) elif len(irel) > 0: relations[property.uri().toString()] = set(irel) #TODO: the dict should directly contain property objects, and compare them properly #see how to give the dict a good hash function for properties (based on the comparison of their uri) newrelations = dict() for key in relations.keys(): prop = Nepomuk.Types.Property(QUrl(key)) newrelations[prop] = relations[key] return newrelations
def findRelations(uri): resource = Nepomuk.Resource(uri) relations = dict() props = resource.properties() for prop in props: if props[prop].isResourceList(): relations[prop.toString()] = set(props[prop].toResourceList()) elif props[prop].isResource(): relations[prop.toString()] = set([props[prop].toResource()]) props = resourceTypesProperties(resource) for property in props: irel = Nepomuk.ResourceManager.instance().allResourcesWithProperty( property.uri(), Nepomuk.Variant(resource)) if len(irel) > 0 and relations.has_key(property.uri().toString()): relations[property.uri().toString()] = relations[ property.uri().toString()].union(irel) elif len(irel) > 0: relations[property.uri().toString()] = set(irel) #TODO: the dict should directly contain property objects, and compare them properly #see how to give the dict a good hash function for properties (based on the comparison of their uri) newrelations = dict() for key in relations.keys(): prop = Nepomuk.Types.Property(QUrl(key)) newrelations[prop] = relations[key] return newrelations
def itemAt(self, index): resource = self.resources[index.row()] column = index.column() if column == 0: return resource.genericLabel() elif column == 1: return resource.property( Soprano.Vocabulary.NAO.lastModified()).toDateTime() elif column == 2: for type in resource.types(): if type != Soprano.Vocabulary.RDFS.Resource(): label = type.toString() label = unicode(label) if label.find("#") > 0: label = label[label.find("#") + 1:] if label == "FileDataObject": label = "File" elif label == "TextDocument": label = "File" #return a QString instead of a str for the proxy model, which handles only QString elif label.find("nepomuk:/") == 0: #this is a custom type, we need to get the label of the ressource typeResource = Nepomuk.Resource(label) label = typeResource.genericLabel() else: label = label[label.rfind("/") + 1:] return QString(label)
def findRelateds(uri): resource = Nepomuk.Resource(uri) related = set(resource.isRelateds()) relatedInverse = set(resource.isRelatedOf()) pimoRelated = resource.property(PIMO.isRelated) urls = pimoRelated.toUrlList() for elt in urls: related.add(Nepomuk.Resource(elt)) pimoRelatedInverse = Nepomuk.ResourceManager.instance( ).allResourcesWithProperty(PIMO.isRelated, Nepomuk.Variant(resource)) relations = related.union(relatedInverse).union(pimoRelatedInverse) return relations
def onTypeFilterChanged(self): action = self.sender() nepomukType = action.property("nepomukType") self.typeUri = QUrl(nepomukType.toString()) label = nepomukType.toString() label = unicode(label) if self.typeUri == Soprano.Vocabulary.RDFS.Resource(): label = i18n("All") elif label.find("#") > 0: label = label[label.find("#") + 1:] if label == "FileDataObject": label = "File" elif label == "TextDocument": label = "File" #return a QString instead of a str for the proxy model, which handles only QString elif label.find("nepomuk:/") == 0: #this is a custom type, we need to get the label of the ressource typeResource = Nepomuk.Resource(label) label = typeResource.genericLabel() else: label = label[label.rfind("/") + 1:] self.typeFilterButton.setText(i18n(label)) self.searchMatchingItems()
def statementAddedSlot(self, statement): predicate = statement.predicate().uri() if predicate == soprano.Soprano.Vocabulary.RDF.type(): object = statement.object().uri() if object == self.nepomukType: subject = statement.subject().uri() newresource = Nepomuk.Resource(subject) self.addResource(newresource)
def addSendMailAction(self): for item in self.selectedResources: res = Nepomuk.Resource(item) #TODO: check that the NCO.emailAddress property is not void if not NCO.PersonContact in res.types(): return action = QAction(i18n("&Write e-mail to"), self) action.setProperty("key", QVariant(WRITE_EMAIL)) self.addAction(action)
def createResource(label, nepomukType): newResource = Nepomuk.Resource() newResource.setLabel(label) #res.setDescription("") types = newResource.types() types.append(nepomukType) newResource.setTypes(types) return newResource
def newEntityHandler(self, entityUri, occurrences): resource = Nepomuk.Resource(entityUri) label = u"%s" % resource.genericLabel() relevance = occurrences[0][2] print "%s [%s] [%s]" % (label, entityUri, relevance) #if self.text.find(label) >=0: if relevance >= 0.9: if resource != self.resource and resource not in self.relations and resource not in self.model.resources: self.addResource(resource)
def hasLiteralRange(pptyUrl): propResource = Nepomuk.Resource(pptyUrl) rangeValue = str( propResource.property(Soprano.Vocabulary.RDFS.range()).toString()) if rangeValue.find("http://www.w3.org/2001/XMLSchema#") == 0: return True if rangeValue.find("http://www.w3.org/2000/01/rdf-schema#Literal") == 0: return True return False
def addExternalOpenAction(self): if len(self.selectedResources) == 1: resource = Nepomuk.Resource(self.selectedResources[0]) if resource and NFO.FileDataObject in resource.types(): action = QAction(i18n("Open &file"), self) action.setProperty("key", QVariant(OPEN_FILE)) self.addAction(action) if resource and NFO.Website in resource.types(): action = QAction(i18n("Open &page"), self) action.setProperty("key", QVariant(OPEN_PAGE)) self.addAction(action)
def getFileResource(path): absolutePath = os.path.abspath(path) name = os.path.basename(path) url = "file://" + absolutePath file = Nepomuk.Resource(QUrl(url)) # print file.isValid() if len(file.resourceUri().toString()) == 0: file.setProperty(NIE.url, Nepomuk.Variant(QUrl(url))) file.setProperty(NFO.fileName, Nepomuk.Variant(name)) file.setLabel(name) return file
def queryNextReadySlot(self, query): node = query.binding("r") resource = Nepomuk.Resource(node.uri()) self.addResource(resource) #TODO: find the proper way if self.resourcestable and self.resourcestable.dialog and self.resourcestable.dialog.__class__ == getClass( "ginkgo.dialogs.livesearchdialog.LiveSearchDialog"): if not self.resourcestable.table.selectionModel().hasSelection(): self.resourcestable.table.selectionModel().clearSelection() self.resourcestable.table.selectRow(0) query.next()
def itemAt(self, index): column = index.column() if column == 0: propname = self.data[index.row()][0] propertyResource = Nepomuk.Resource(QUrl(propname)) return propertyResource.genericLabel() #if propname.find("#") > 0: # propname = propname[propname.find("#") + 1:] #return propname elif column == 1: value = self.data[index.row()][1] if value: return value.toString() return ""
def do_soprano(): from PyKDE4.nepomuk import Nepomuk print "0" from PyKDE4.soprano import Soprano fileName = 'test' manager = Nepomuk.ResourceManager.instance() print manager resource = Nepomuk.Resource('file://%s' % fileName, Soprano.Vocabulary.Xesam.File()) resource.setTags([]) # Nepomuk.Tag( tag ) for tag in tags resource.setRating(max(rating, 0)) resource.setDescription(description) print resource
def findInverseRelations(uri): sparql = "select * where {?s ?p <%s>}" % uri #TODO: use the query API model = Nepomuk.ResourceManager.instance().mainModel() iter = model.executeQuery(sparql, Soprano.Query.QueryLanguageSparql) data = [] while iter.next(): bindingSet = iter.current() subject = Nepomuk.Resource(bindingSet.value("s").uri()) predicate = Nepomuk.Types.Property(bindingSet.value("p").uri()) data.append((subject, predicate)) return data
def findResourcesByLabelSync(label): queryString = "select distinct ?r, ?label where { ?r <http://www.semanticdesktop.org/ontologies/2007/08/15/nao#prefLabel> ?label . FILTER regex(?label, \"%s\", \"i\") }" % label model = Nepomuk.ResourceManager.instance().mainModel() iter = model.executeQuery(queryString, Soprano.Query.QueryLanguageSparql) bindingNames = iter.bindingNames() data = [] while iter.next(): bindingSet = iter.current() for i in range(len(bindingNames)): v = bindingSet.value(bindingNames[i]) if not v.isLiteral(): resource = Nepomuk.Resource(v.uri()) data.append(resource) else: value = v.literal().toString() return data
def addChildren(self, node, typeResource): typeClass = Nepomuk.Types.Class(typeResource.resourceUri()) subClasses = typeClass.subClasses() tuples = [] for subClass in subClasses: #TODO: why subClass are not instance of Resource? #TODO: why pimo:Thing is not listed in the subClasses of itself while it is in the database #don't add to the children list a class that subclasses itself if typeResource.resourceUri() == subClass.uri(): continue subClassResource = Nepomuk.Resource(subClass.uri()) #check that the subClassResource was not added yet #TODO: make sure the subClass method returns each class only once even if #the subclass is returned several times flag = False for item in tuples: if item[0].resourceUri() == subClassResource.resourceUri(): flag = True break if not flag: tuples.append((subClassResource, subClassResource.genericLabel())) sortedResources = sorted(tuples, key=lambda tuple: tuple[1]) for tuple in sortedResources: child = ResourceNode(tuple[0], node) node.addChild(child) #if there's a node for the same resource in the root children, remove that node toRemove = [] index = 0 for rootChild in self.rootItem.children: rootChildResource = rootChild.nodeData if rootChildResource.resourceUri() == tuple[0].resourceUri(): toRemove.append(index) index = index + 1 delta = 0 for idx in toRemove: self.rootItem.children.pop(idx - delta) delta = delta + 1 self.addChildren(child, tuple[0])
def processAction(self, key, selectedResources): if key == OPEN_IN_NEW_TAB: for uri in selectedResources: self.mainWindow.openResource(uri, newTab=True) elif key == DELETE: for uri in selectedResources: self.mainWindow.removeResource(uri) elif key == OPEN_FILE: for uri in selectedResources: self.mainWindow.openResourceExternally(uri, True) elif key == OPEN_PAGE: for uri in selectedResources: self.mainWindow.openResourceExternally(uri, False) elif key == WRITE_EMAIL: self.mainWindow.writeEmail(selectedResources) elif key == SET_AS_CONTEXT: resource = Nepomuk.Resource(selectedResources[0]) self.mainWindow.setResourceAsContext(resource)
def findResources(sparql): model = Nepomuk.ResourceManager.instance().mainModel() iter = model.executeQuery(sparql, Soprano.Query.QueryLanguageSparql) bindingNames = iter.bindingNames() data = [] while iter.next(): bindingSet = iter.current() for i in range(len(bindingNames)): v = bindingSet.value(bindingNames[i]) uri = v.uri() #.genericLabel() resource = Nepomuk.Resource(uri) data.append(resource) return data
def updateFields(self): if self.editor.resource: if hasattr(self, "name"): self.name.setText(self.editor.resource.property(Soprano.Vocabulary.NAO.prefLabel()).toString()) if hasattr(self, "url"): if len(self.editor.resource.property(NIE.url).toString()) > 0: self.url.setText(self.editor.resource.property(NIE.url).toString()) else: self.url.setText(self.editor.resource.uri()) prefLabel = self.editor.resource.property(Soprano.Vocabulary.NAO.prefLabel()).toString() p = QPalette() p.setColor(QPalette.Text, p.color(QPalette.Normal, QPalette.Text)) self.label.setPalette(p) f = self.label.font() f.setItalic(False) self.label.setFont(f) self.label.setText(prefLabel) types = "" for type in self.editor.resource.types(): if type == Soprano.Vocabulary.RDFS.Resource(): continue typestr = str(type.toString()) if typestr.find("#") > 0: typestr = typestr[typestr.find("#") + 1:] elif typestr.find("nepomuk:/") == 0: #this is a custom type, we need to get the label of the ressource typeResource = Nepomuk.Resource(typestr) typestr = typeResource.genericLabel() else: typestr = typestr[typestr.rfind("/") + 1:] types = types + i18n(typestr) + ", " if len(types) > 0: types = types[0:len(types) - 2] self.typesInfo.setText(i18n("Type(s): ") + types) self.relationsTable.setResource(self.editor.resource) self.propsTable.setResource(self.editor.resource)
def loadOntologyClasses(self, ontologyUri): #type = Soprano.Vocabulary.RDFS.Resource() #rootClass = Nepomuk.Types.Class(rootType) #sparql = "select distinct ?subject where { graph <%s> { ?subject a rdfs:Class . } }" % ontologyUri.toString() classes = datamanager.findOntologyClasses(ontologyUri) rootTypeResource = Nepomuk.Resource(Soprano.Vocabulary.RDFS.Resource()) self.rootItem = ResourceNode(rootTypeResource) #first we add all children to the root #then we load the children of the root children, and we remove the root children which have ancestors for classResource in classes: child = ResourceNode(classResource, self.rootItem) self.rootItem.addChild(child) for child in self.rootItem.children: classResource = child.nodeData self.addChildren(child, classResource)
def createModel(self): self.model = TypesTableModel(self) self.model.setHeaders([i18n("Ontology"), i18n("Name")]) #TODO: find built-in conversion resourceSet = [] array = [] # for elt in resourceTypes: # typeResource = Nepomuk.Resource(elt) # ressourceArray.append(typeResource) # rootClass = Nepomuk.Types.Class(Soprano.Vocabulary.RDFS.Resource()) # self.addChildren(rootClass.uri(), array) #add the root element, Resource, to the set of types #resourceSet.append(Nepomuk.Resource(Soprano.Vocabulary.RDFS.Resource())) for typeUri in self.typesUris: resourceSet.append(Nepomuk.Resource(typeUri)) self.model.setResources(resourceSet)
def __init__(self, mainWindow=False, resource=None, nepomukType=None, superTask=None): super(TaskEditor, self).__init__(mainWindow=mainWindow, resource=resource, nepomukType=nepomukType) self.defaultIcon = "" self.superTask = None if self.resource: superTask = self.resource.property(TMO.superTask) if superTask and superTask.toString(): self.superTask = Nepomuk.Resource(superTask.toString()) elif superTask: self.superTask = superTask self.ui = TaskEditorUi(self)
def findDirectRelations(uri): resource = Nepomuk.Resource(uri) relations = dict() props = resource.properties() for prop in props: if props[prop].isResourceList(): relations[prop.toString()] = set(props[prop].toResourceList()) elif props[prop].isResource(): #TODO: it seems there's a Nepomuk bug with property rdfs:range when its value is not a Resource type #see range.py checkuri = str(props[prop].toResource().resourceUri().toString()) if len(checkuri.strip()) > 0: relations[prop.toString()] = set([props[prop].toResource()]) newrelations = dict() for key in relations.keys(): prop = Nepomuk.Types.Property(QUrl(key)) newrelations[prop] = relations[key] return newrelations