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 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 setModelData(self, editor, model, index): if index.column() == 0: sindex = self.table.table.model().mapToSource(index) cindex = editor.currentIndex() relation = index.model().sourceModel().relations[sindex.row()] predicate = relation[0] direct = relation[2] if direct: subject = self.table.resource object = relation[1] else: subject = relation[1] object = self.table.resource newPredicate = self.sortedProps[cindex][0] if newPredicate.uri().toString() != predicate.uri().toString(): self.table.setCursor(Qt.WaitCursor) subject.addProperty(newPredicate.uri(), Nepomuk.Variant(object.resourceUri())) subject.removeProperty(predicate.uri(), Nepomuk.Variant(object.resourceUri())) self.table.unsetCursor() #don't do that since the model gets already updated through signal emission #index.model().sourceModel().relations[index.row()] = (newPredicate, object, direct) else: QItemDelegate.setModelData(self, editor, model, index)
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 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 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 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 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 save(self): super(ContactEditor, self).save() self.resource.setProperty( NCO.nameGiven, Nepomuk.Variant(unicode(self.ui.firstname.text()))) self.resource.setProperty( NCO.nameFamily, Nepomuk.Variant(unicode(self.ui.lastname.text()))) self.resource.setProperty(NCO.emailAddress, Nepomuk.Variant(self.ui.email.text())) self.resource.setProperty(NCO.phoneNumber, Nepomuk.Variant(self.ui.phone.text())) self.ui.updateFields()
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 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 scrap1(): url = QUrl("nepomuk:/res/a8b8ed53-3f5e-4199-b824-f7f0360408c5") res = Nepomuk.Resource(url) print res print res.genericIcon() print "finishing"
def processAction(self, key, propvalue): if key == COPY_TO_CLIPBOARD: clipboard = QApplication.clipboard() clipboard.setText(propvalue[1].toString()) elif key == ADD_PROPERTY: elt = (Soprano.Vocabulary.RDFS.comment(), Nepomuk.Variant("")) self.table.model().sourceModel().addProperty(elt)
def save(self): super(WebsiteEditor, self).save() self.resource.setProperty(NIE.url, Nepomuk.Variant(QUrl(unicode(self.ui.url.text())))) self.ui.updateFields()
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 createResource(label, nepomukType): newResource = Nepomuk.Resource() newResource.setLabel(label) #res.setDescription("") types = newResource.types() types.append(nepomukType) newResource.setTypes(types) return 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 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 setModelData(self, editor, model, index): if index.column() == 0: sindex = self.table.table.model().mapToSource(index) cindex = editor.currentIndex() predicateUrl = index.model().sourceModel().data[sindex.row()][0] value = index.model().sourceModel().data[sindex.row()][1] newPredicate = self.sortedProps[cindex][0] if newPredicate.uri() != predicateUrl: self.table.setCursor(Qt.WaitCursor) self.table.resource.addProperty(newPredicate.uri(), Nepomuk.Variant(value)) self.table.resource.removeProperty(predicateUrl, Nepomuk.Variant(value)) self.table.unsetCursor() #here we need to update the model since it won't get updated by signal emission index.model().sourceModel().data[sindex.row()] = (newPredicate.uri(), value) elif index.column() == 1: sindex = self.table.table.model().mapToSource(index) predicateUrl = index.model().sourceModel().data[sindex.row()][0] value = index.model().sourceModel().data[sindex.row()][1] #TODO: fix that (class comparison won't work since QSpinBox.__class__ is a pyqtWrapperType if str(editor.__class__) in ("<class 'PyQt4.QtGui.QSpinBox'>", "<class 'PyQt4.QtGui.QDoubleSpinBox'>"): newValue = editor.value() elif str(editor.__class__) == "<class 'PyQt4.QtGui.QDateEdit'>": newValue = editor.date() elif str(editor.__class__) == "<class 'PyQt4.QtGui.QDateTimeEdit'>": newValue = editor.dateTime() elif str(editor.__class__) == "<class 'PyQt4.QtGui.QLineEdit'>": newValue = editor.text() self.table.setCursor(Qt.WaitCursor) self.table.resource.addProperty(predicateUrl, Nepomuk.Variant(newValue)) self.table.resource.removeProperty(predicateUrl, Nepomuk.Variant(value)) self.table.unsetCursor() #here we need to update the model since it won't get updated by signal emission index.model().sourceModel().data[sindex.row()] = (predicateUrl, Nepomuk.Variant(newValue))
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 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 updateRangeLiteral(self): #save the resource to create it if it doesn't exist yet if not self.resource: self.save() idx = self.ui.literalBox.currentIndex() data = self.ui.literalBox.itemData(idx) literalTypeUri = QUrl(data.toString()) self.mainWindow.setCursor(Qt.WaitCursor) self.resource.setProperty(Soprano.Vocabulary.RDFS.range(), Nepomuk.Variant(literalTypeUri)) self.ui.updateFields() self.mainWindow.unsetCursor()
def save(self): #TODO: validate that name trimmed is not empty super(TaskEditor, self).save() priority = TMO.TMO_Instance_Priority_Medium if self.ui.lowPriority.isChecked(): priority = TMO.TMO_Instance_Priority_Low elif self.ui.highPriority.isChecked(): priority = TMO.TMO_Instance_Priority_High state = TMO.TMO_Instance_TaskState_New if self.ui.stateRunning.isChecked(): state = TMO.TMO_Instance_TaskState_Running elif self.ui.stateCompleted.isChecked(): state = TMO.TMO_Instance_TaskState_Completed dueDate = None if self.ui.dateBox.isChecked(): dueDate = self.ui.dueDate.date() self.resource.setLabel(self.ui.label.text()) self.resource.setProperty(TMO.priority, Nepomuk.Variant(priority)) self.resource.setProperty(TMO.taskState, Nepomuk.Variant(state)) if dueDate: self.resource.setProperty(TMO.dueDate, Nepomuk.Variant(dueDate)) else: self.resource.removeProperty(TMO.dueDate) if self.superTask is not None: self.resource.removeProperty(TMO.superTask) self.resource.setProperty(TMO.superTask, Nepomuk.Variant(self.superTask)) self.mainWindow.emit(SIGNAL('taskHierarchyUpdated')) else: #TODO: distinguish between the old and the new task attributes self.resource.removeProperty(TMO.superTask) self.mainWindow.emit(SIGNAL('taskHierarchyUpdated'))
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 scrap(): labelTerm = Nepomuk.Query.ComparisonTerm( Nepomuk.Types.Property(Soprano.Vocabulary.NAO.prefLabel()), Nepomuk.Query.LiteralTerm(Soprano.LiteralValue("Alex")), Nepomuk.Query.ComparisonTerm.Contains) labelTerm.setVariableName("label") #query = Nepomuk.Query.Query(labelTerm) nepomukType = Nepomuk.Types.Class(NCO.Contact) typeTerm = Nepomuk.Query.ResourceTypeTerm(nepomukType) query = Nepomuk.Query.Query(typeTerm) data = findResources(query.toSparqlQuery()) for elt in data: elt.addProperty(Soprano.Vocabulary.RDF.type(), Nepomuk.Variant(NCO.PersonContact))
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