예제 #1
0
    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)
예제 #2
0
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
예제 #3
0
    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)
예제 #4
0
    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())
예제 #5
0
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
예제 #6
0
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)
예제 #7
0
    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)
예제 #8
0
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
예제 #9
0
    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()
예제 #10
0
    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()
예제 #11
0
    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)
예제 #12
0
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
예제 #13
0
def scrap1():
    url = QUrl("nepomuk:/res/a8b8ed53-3f5e-4199-b824-f7f0360408c5")
    res = Nepomuk.Resource(url)
    print res

    print res.genericIcon()
    print "finishing"
예제 #14
0
 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)
예제 #15
0
 def save(self):
     
     super(WebsiteEditor, self).save()
     
     self.resource.setProperty(NIE.url, Nepomuk.Variant(QUrl(unicode(self.ui.url.text()))))
     
     self.ui.updateFields()
예제 #16
0
 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)
예제 #17
0
def createResource(label, nepomukType):
    newResource = Nepomuk.Resource()
    newResource.setLabel(label)
    #res.setDescription("")

    types = newResource.types()
    types.append(nepomukType)
    newResource.setTypes(types)
    return newResource
예제 #18
0
 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)
예제 #19
0
 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)
예제 #20
0
    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))
예제 #21
0
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
예제 #22
0
    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)
예제 #23
0
    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()
예제 #24
0
    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()
예제 #25
0
    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'))
예제 #26
0
 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 ""
예제 #27
0
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
예제 #28
0
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
예제 #29
0
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))
예제 #30
0
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