Example #1
0
def main():
    QtCore.QCoreApplication(sys.argv)

    fileName = ''
    className = ''
    encoding = ''
    i = 1
    while i < len(sys.argv):
        if sys.argv[i] == '--name':
            i += 1
            className = sys.argv[i]

        elif sys.argv[i] == '--encoding':
            i += 1
            encoding = sys.argv[i]

        elif i == len(sys.argv) - 1:
            fileName = sys.argv[i]

        i += 1

    parser = Soprano.PluginManager.instance().discoverParserForSerialization(
        Soprano.mimeTypeToSerialization(encoding), encoding)
    it = parser.parseFile(fileName, QtCore.QUrl("http://dummybaseuri.org"),
                          Soprano.mimeTypeToSerialization(encoding), encoding)
    graph = Soprano.Graph()
    while it.next():
        graph.addStatement(it.current())

    sourceFile = open(className + '.py', 'w')

    allResources = extractRelevantResources(graph)
    normalizedResources = {}
    done = []
    for resource in allResources:
        uri = resource.uri().toString()
        if not uri in normalizedResources:
            name = resource.uri().fragment()
        if not len(name) == 0 and not name in done:
            normalizedResources[uri] = name

    namespaceUri = QtCore.QUrl(normalizedResources.keys()[0])
    namespaceUri.setFragment('')
    ontoNamespace = namespaceUri
    print 'Namespace: %s' % namespaceUri
    print dir(sourceFile)

    print >> sourceFile, 'from PyQt4 import QtCore'
    for uri, name in normalizedResources.iteritems():
        print >> sourceFile, "%s = QtCore.QUrl('%s')" % (normalizeName(name),
                                                         uri)
Example #2
0
def extractRelevantResources(graph):
    resources = []
    it = graph.listStatements(
        Soprano.ResourceNode(),
        Soprano.ResourceNode(Soprano.Vocabulary.RDF.type()),
        Soprano.ResourceNode())
    while it.next():
        s = it.current()
        if not s.context().isValid() or not graph.containsStatement(
                s.context(), Soprano.ResourceNode(
                    Soprano.Vocabulary.RDF.type()),
                Soprano.ResourceNode(Soprano.Vocabulary.NRL.GraphMetadata())):
            resources.append(s.subject())
    return resources
Example #3
0
def main():
    QtCore.QCoreApplication( sys.argv )

    fileName = ''
    className = ''
    encoding = ''
    i = 1
    while i < len(sys.argv):
        if sys.argv[i] == '--name':
            i+=1
            className = sys.argv[i]

        elif sys.argv[i] == '--encoding':
            i+=1
            encoding = sys.argv[i]
            
        elif i == len(sys.argv)-1:
            fileName = sys.argv[i]

        i+=1

    parser = Soprano.PluginManager.instance().discoverParserForSerialization( Soprano.mimeTypeToSerialization( encoding ), encoding )
    it = parser.parseFile( fileName, QtCore.QUrl("http://dummybaseuri.org"), Soprano.mimeTypeToSerialization( encoding ), encoding )
    graph = Soprano.Graph()
    while it.next():
        graph.addStatement( it.current() )

    sourceFile = open(className+'.py', 'w')

    allResources = extractRelevantResources(graph)
    normalizedResources = {}
    done = []
    for resource in allResources:
        uri = resource.uri().toString()
        if not uri in normalizedResources:
            name = resource.uri().fragment()
        if not len(name) == 0 and not name in done:
            normalizedResources[uri] = name

    namespaceUri = QtCore.QUrl(normalizedResources.keys()[0])
    namespaceUri.setFragment('')
    ontoNamespace = namespaceUri
    print 'Namespace: %s' % namespaceUri
    print dir(sourceFile)

    print >> sourceFile, 'from PyQt4 import QtCore'
    for uri, name in normalizedResources.iteritems():
        print >> sourceFile, "%s = QtCore.QUrl('%s')" % (normalizeName(name), uri)
Example #4
0
def addPimoStatements(statements):
    ctx = pimoContext()
    model = Nepomuk.ResourceManager.instance().mainModel()

    for statement in statements:
        statement.setContext(Soprano.Node(ctx))
        model.addStatement(statement)

    return Soprano.Error.ErrorNone
Example #5
0
def findResourceByLabel(label, match=Nepomuk.Query.ComparisonTerm.Regexp):
    literalTerm = Nepomuk.Query.LiteralTerm(Soprano.LiteralValue(label))
    prop = Nepomuk.Types.Property(Soprano.Vocabulary.NAO.prefLabel())
    term = Nepomuk.Query.ComparisonTerm(prop, literalTerm, match)
    query = Nepomuk.Query.Query(term)
    sparql = query.toSparqlQuery()
    data = findResources(sparql)
    if len(data) > 0:
        return data[0]
    else:
        return None
Example #6
0
def labelExists(label):
    """Returns True if a ressource nao:prefLabel matches the argument."""
    literalTerm = Nepomuk.Query.LiteralTerm(Soprano.LiteralValue(label))
    prop = Nepomuk.Types.Property(Soprano.Vocabulary.NAO.prefLabel())
    term = Nepomuk.Query.ComparisonTerm(prop, literalTerm,
                                        Nepomuk.Query.ComparisonTerm.Equal)
    query = Nepomuk.Query.Query(term)
    sparql = query.toSparqlQuery()
    data = sparqlToResources(sparql)
    if len(data) > 0:
        return True

    return False
Example #7
0
def fullTextSearch(term,
                   queryNextReadySlot,
                   queryFinishedSlot=None,
                   controller=None):
    if term is None:
        return

    if len(term.strip()) == 0:
        return

    term = Nepomuk.Query.LiteralTerm(Soprano.LiteralValue(term))
    query = Nepomuk.Query.Query(term)
    sparql = query.toSparqlQuery()
    #data = executeQuery(sparql)
    executeAsyncQuery(sparql, queryNextReadySlot, queryFinishedSlot,
                      controller)
Example #8
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))
Example #9
0
def findResourcesByLabel(label,
                         queryNextReadySlot,
                         queryFinishedSlot=None,
                         controller=None):

    label = label.replace("*", ".*")
    label = label.replace("?", ".")

    literalTerm = Nepomuk.Query.LiteralTerm(Soprano.LiteralValue(label))
    prop = Nepomuk.Types.Property(Soprano.Vocabulary.NAO.prefLabel())
    term = Nepomuk.Query.ComparisonTerm(prop, literalTerm,
                                        Nepomuk.Query.ComparisonTerm.Regexp)
    query = Nepomuk.Query.Query(term)
    sparql = query.toSparqlQuery()

    executeAsyncQuery(sparql, queryNextReadySlot, queryFinishedSlot,
                      controller)
Example #10
0
def abbrevToOntology(abbrev):
    abbrevTerm = Nepomuk.Query.ComparisonTerm(
        Nepomuk.Types.Property(
            Soprano.Vocabulary.NAO.hasDefaultNamespaceAbbreviation()),
        Nepomuk.Query.LiteralTerm(Soprano.LiteralValue(abbrev)),
        Nepomuk.Query.ComparisonTerm.Equal)
    ontoType = Nepomuk.Types.Class(Soprano.Vocabulary.NRL.Ontology())
    typeTerm = Nepomuk.Query.ResourceTypeTerm(ontoType)
    andTerm = Nepomuk.Query.AndTerm(abbrevTerm, typeTerm)
    query = Nepomuk.Query.Query(andTerm)

    ontologies = findResources(query.toSparqlQuery())
    print query.toSparqlQuery()

    if len(ontologies) > 0:
        ontology = ontologies[0]
        return ontology
    return None
Example #11
0
def findResourcesByTypeAndLabel(typeUri,
                                label,
                                queryNextReadySlot,
                                queryFinishedSlot=None,
                                controller=None):

    label = label.replace("*", ".*")
    label = label.replace("?", ".")
    label = label.replace("'", "\\'")

    nepomukType = Nepomuk.Types.Class(typeUri)
    typeTerm = Nepomuk.Query.ResourceTypeTerm(nepomukType)

    literalTerm = Nepomuk.Query.LiteralTerm(Soprano.LiteralValue(label))
    prop = Nepomuk.Types.Property(Soprano.Vocabulary.NAO.prefLabel())
    labelTerm = Nepomuk.Query.ComparisonTerm(
        prop, literalTerm, Nepomuk.Query.ComparisonTerm.Regexp)

    andTerm = Nepomuk.Query.AndTerm(typeTerm, labelTerm)

    query = Nepomuk.Query.Query(andTerm)
    sparql = query.toSparqlQuery()
    executeAsyncQuery(sparql, queryNextReadySlot, queryFinishedSlot,
                      controller)
Example #12
0
def pimoContext():
    sparql = "select ?c ?onto where {?c a <%s> . OPTIONAL {?c a ?onto . FILTER(?onto=<%s>). } } " % (
        str(PIMO.PersonalInformationModel.toString()),
        str(Soprano.Vocabulary.NRL.Ontology().toString()))
    model = Nepomuk.ResourceManager.instance().mainModel()
    it = model.executeQuery(sparql, Soprano.Query.QueryLanguageSparql)
    if it.next():
        pimoContext = it.binding(0).uri()
        if not it.binding(1).isValid():
            stmt = Soprano.Statement(
                Soprano.Node(pimoContext),
                Soprano.Node(Soprano.Vocabulary.RDF.type()),
                Soprano.Node(Soprano.Vocabulary.NRL.Ontology()),
                Soprano.Node(pimoContext))
            model.addStatement(stmt)

    else:
        pimoContext = QUrl(
            Nepomuk.ResourceManager.instance().generateUniqueUri())
        stmt = Soprano.Statement(Soprano.Node(pimoContext),
                                 Soprano.Node(Soprano.Vocabulary.RDF.type()),
                                 Soprano.Node(PIMO.PersonalInformationModel),
                                 Soprano.Node(pimoContext))
        model.addStatement(stmt)
        stmt = Soprano.Statement(
            Soprano.Node(pimoContext),
            Soprano.Node(Soprano.Vocabulary.RDF.type()),
            Soprano.Node(Soprano.Vocabulary.NRL.Ontology()),
            Soprano.Node(pimoContext))
        model.addStatement(stmt)
    it.close()
    return pimoContext
Example #13
0
def createPimoProperty(label,
                       domainUri,
                       rangeUri=Soprano.Vocabulary.RDFS.Resource(),
                       comment=None,
                       icon=None):
    if not rangeUri.isValid():
        print "[Ginkgo] Invalid range"
        return QUrl()

    if not label or len(label) == 0:
        print "[Ginkgo] Empty label"
        return QUrl()

    domainClass = Nepomuk.Types.Class(domainUri)
    pimoThingClass = Nepomuk.Types.Class(PIMO.Thing)

    if domainUri != PIMO.Thing and not domainClass.isSubClassOf(
            pimoThingClass):
        print "[Ginkgo] New PIMO properties need to have a pimo:Thing related domain."

    #propertyUri = Nepomuk.ResourceManager.instance().generateUniqueUri(label)
    pimoxNs = "http://www.semanticdesktop.org/ontologies/pimox#"
    propertyId = label.replace(" ", "")
    propertyUri = QUrl(pimoxNs + propertyId)

    stmts = []
    stmts.append(
        Soprano.Statement(Soprano.Node(propertyUri),
                          Soprano.Node(Soprano.Vocabulary.RDF.type()),
                          Soprano.Node(Soprano.Vocabulary.RDF.Property())))
    #stmts.append(Soprano.Statement(Soprano.Node(propertyUri), Soprano.Node(Soprano.Vocabulary.RDFS.subPropertyOf()), Soprano.Node(PIMO.isRelated)))
    stmts.append(
        Soprano.Statement(Soprano.Node(propertyUri),
                          Soprano.Node(Soprano.Vocabulary.RDFS.domain()),
                          Soprano.Node(domainUri)))
    stmts.append(
        Soprano.Statement(Soprano.Node(propertyUri),
                          Soprano.Node(Soprano.Vocabulary.RDFS.range()),
                          Soprano.Node(rangeUri)))
    #TODO set the prefLabel of the resource corresponding to this property?
    #TODO why a property needs to be a subproperty of itself
    stmts.append(
        Soprano.Statement(
            Soprano.Node(propertyUri),
            Soprano.Node(Soprano.Vocabulary.RDFS.subPropertyOf()),
            Soprano.Node(propertyUri)))
    stmts.append(
        Soprano.Statement(Soprano.Node(propertyUri),
                          Soprano.Node(Soprano.Vocabulary.RDFS.label()),
                          Soprano.Node(Soprano.LiteralValue(label))))
    stmts.append(
        Soprano.Statement(
            Soprano.Node(propertyUri),
            Soprano.Node(Soprano.Vocabulary.NAO.created()),
            Soprano.Node(Soprano.LiteralValue(QDateTime.currentDateTime()))))

    if addPimoStatements(stmts) == Soprano.Error.ErrorNone:
        #we reset the entity so that its properties will get refreshed
        domainClass.reset()
        return Nepomuk.Resource(propertyUri)

    return None
Example #14
0
def createPimoClass(parentClassUri, label, comment=None, icon=None):

    if label is None or len(unicode(label).strip()) == 0:
        print "Class label cannot be empty."
        return None

    parentClass = Nepomuk.Types.Class(parentClassUri)
    pimoThingClass = Nepomuk.Types.Class(PIMO.Thing)
    if parentClassUri != PIMO.Thing and not parentClass.isSubClassOf(
            pimoThingClass):
        print "New PIMO class needs to be subclass of pimo:Thing."
        return None

    #TODO: see pimomodel.cpp
#        if ( !name.isEmpty() ) {
#        QString normalizedName = name.replace( QRegExp( "[^\\w\\.\\-_:]" ), "" );
#        QUrl s = "nepomuk:/" + normalizedName;
#        while( 1 ) {
#            if ( !q->executeQuery( QString("ask where { { <%1> ?p1 ?o1 . } UNION { ?r2 <%1> ?o2 . } UNION { ?r3 ?p3 <%1> . } }")
#                                   .arg( QString::fromAscii( s.toEncoded() ) ), Soprano::Query::QueryLanguageSparql ).boolValue() ) {
#                return s;
#            }
#            s = "nepomuk:/" + normalizedName + '_' +  KRandom::randomString( 20 );
#        }
#    }
#TODO: create a dedicated NS
    pimoxNs = "http://www.semanticdesktop.org/ontologies/pimox#"
    classId = label.replace(" ", "")
    classUri = QUrl(pimoxNs + classId)
    #classUri = Nepomuk.ResourceManager.instance().generateUniqueUri(label)
    stmts = []
    stmts.append(
        Soprano.Statement(Soprano.Node(classUri),
                          Soprano.Node(Soprano.Vocabulary.RDF.type()),
                          Soprano.Node(Soprano.Vocabulary.RDFS.Class())))
    stmts.append(
        Soprano.Statement(Soprano.Node(classUri),
                          Soprano.Node(Soprano.Vocabulary.RDFS.subClassOf()),
                          Soprano.Node(QUrl(parentClassUri))))
    #this is needed for the class to show up as a child of the PIMO class chosen
    if parentClassUri != PIMO.Thing:
        stmts.append(
            Soprano.Statement(
                Soprano.Node(classUri),
                Soprano.Node(Soprano.Vocabulary.RDFS.subClassOf()),
                Soprano.Node(PIMO.Thing)))
    #this is needed until we use an inferencer, otherwise searching for instances of resource won't include the instances of this class
    stmts.append(
        Soprano.Statement(Soprano.Node(classUri),
                          Soprano.Node(Soprano.Vocabulary.RDFS.subClassOf()),
                          Soprano.Node(Soprano.Vocabulary.RDFS.Resource())))
    #TODO: check why pimomodel.cpp does not use Soprano.Node wrapping
    #TODO: check why all classes in the db are subclass of themselves
    stmts.append(
        Soprano.Statement(Soprano.Node(classUri),
                          Soprano.Node(Soprano.Vocabulary.RDFS.subClassOf()),
                          Soprano.Node(QUrl(classUri))))
    stmts.append(
        Soprano.Statement(Soprano.Node(classUri),
                          Soprano.Node(Soprano.Vocabulary.RDFS.label()),
                          Soprano.Node(Soprano.LiteralValue(label))))
    stmts.append(
        Soprano.Statement(
            Soprano.Node(classUri),
            Soprano.Node(Soprano.Vocabulary.NAO.created()),
            Soprano.Node(Soprano.LiteralValue(QDateTime.currentDateTime()))))

    if addPimoStatements(stmts) == Soprano.Error.ErrorNone:
        #the parent's class needs a rerset for reloading its children classes
        parentClass.reset()
        return Nepomuk.Resource(classUri)

    return None
 def __init__(self):
     self.model = Soprano.createModel()