示例#1
0
 def dumpNQ(self, out):
     cg = rdflib.graph.ConjunctiveGraph()
     for key in self.gix.keys():
         if key in self.included.keys():
             g = self.gix[key]
             self.fixgraph(g)
             for prefix, namespace in NamespaceManager(g).namespaces():
                 NamespaceManager(cg).bind(prefix, namespace)
             for trip in self.gix[key].triples((None, None, None)):
                 cg.add((trip[0], trip[1], trip[2], key))
     NamespaceManager(cg).bind("dc", "http://purl.org/dc/elements/1.1/")
     cg.serialize(destination=out, format='trig')
示例#2
0
 def dumpTTL(self, out):
     cg = TBCGraph()
     for key in self.gix.keys():
         if key in self.included.keys():
             g = self.gix[key]
             self.fixgraph(g)
             for prefix, namespace in NamespaceManager(g).namespaces():
                 NamespaceManager(cg).bind(prefix, namespace)
             for trip in self.gix[key].triples((None, None, None)):
                 cg.add((trip[0], trip[1], trip[2]))
     NamespaceManager(cg).bind("dc", "http://purl.org/dc/elements/1.1/")
     cg.add((URIRef("http://example.org/all"), RDF.type, OWL.Ontology))
     cg.serialize(destination=out, format='ttl')
示例#3
0
 def __init__(self, host_url):
     self._graph = Graph()
     self._ns_manager = NamespaceManager(self._graph)
     self._initialize_prefixes()
     self._namespaces = dict(
         (x, Namespace(y)) for x, y in self._ns_manager.namespaces())
     self._host_url = host_url
示例#4
0
    def initgraphconfig(self, rev):
        """Initialize graph settings.

        Public method to initalize graph settings. This method will be run only once.
        """
        if self.graphconf is None:
            self.graphconf = Graph()
            self.nsMngrGraphconf = NamespaceManager(self.graphconf)
            self.nsMngrGraphconf.bind('', self.quit, override=False)

        graph_files, config_files, rdf_files = self.get_blobs_from_repository(
            rev)

        if len(graph_files) == 0 and len(config_files) == 0:
            self.mode = 'graphfiles'
        elif len(graph_files) > 0 and len(config_files) > 0:
            raise InvalidConfigurationError(
                "Conflict. Found graphfiles and QuitStore configuration file.")
        elif len(graph_files) > 0:
            self.mode = 'graphfiles'
            self.__init_graph_conf_with_blobs(graph_files, rev)
        elif len(config_files) == 1:
            self.mode = 'configuration'
            self.__init_graph_conf_from_configuration(config_files[0],
                                                      rdf_files)
        else:
            raise InvalidConfigurationError(
                "Conflict. Found more than one QuitStore configuration file.")
示例#5
0
def write_countries_to_turtle(countries):
    g = Graph()
    namespace_manager = NamespaceManager(Graph())
    n_dbpedia_res = Namespace("http://dbpedia.org/resource/")
    n_dbo_res = Namespace("http://dbpedia.org/ontology/")
    n_custom_ontology = Namespace("http://www.semanticweb.org/sws/group4/ontology/")
    n_custom_resources = Namespace("http://www.semanticweb.org/sws/group4/resources/")

    namespace_manager.bind('swo', n_custom_ontology, override=False)
    namespace_manager.bind('sws', n_custom_resources, override=False)
    namespace_manager.bind('dbp', n_dbpedia_res, override=False)
    namespace_manager.bind('dbo', n_dbo_res, override=False)
    g.namespace_manager = namespace_manager

    # country = n_dbpedia_res[country_str.replace(" ", "_")]
    for country, risk in countries:
        c = URIRef(n_dbpedia_res[country.replace(" ", "_")])

        # add the country as a named individual
        g.add((c, RDF.type, n_dbo_res.Country))

        # add risk level
        g.add((c, n_custom_ontology['Risk_Level'], Literal(risk)))

    # write to output file
    g.serialize(destination=f'ttl/countries.ttl', format='turtle')
示例#6
0
def getSubgraph(g, subject, max_depth=100):
    """
    Retrieve the subgraph of g with subject.

    Given the graph ``g``, extract the subgraph identified
    as the object of the triple with subject ``subject``.

    Args:
        g (Graph): Source graph
        subject (URIRef): Subject of the root of the subgraph to retrieve
        max_depth (integer): Maximum recursion depth

    Returns:
        (Graph) The subgraph of g with subject.

    Example:

    .. jupyter-execute:: examples/code/eg_getsubgraph_01.py

    """
    sg = ConjunctiveGraph()
    sg.namespace_manager = NamespaceManager(g)
    sg += g.triples((subject, None, None))
    inflateSubgraph(g, sg, sg, max_depth=max_depth)
    return sg
示例#7
0
    def serialize(g, uri):
        def match_ns(term):
            filter_ns = [ns for ns in rev_ns if ns in term]
            if filter_ns:
                ns = filter_ns.pop()
                if rev_ns[ns]:
                    found_ns.append((rev_ns[ns], ns))
                del rev_ns[ns]

        rev_ns = {ns: prefix for prefix, ns in g.namespaces()}
        found_ns = []
        for s, p, o in g:
            match_ns(s)
            match_ns(p)
            match_ns(o)

        g.namespace_manager = NamespaceManager(Graph())
        for (prefix, ns) in found_ns:
            g.bind(prefix, ns)

        format = 'text/turtle' if request_wants_turtle(
        ) else 'application/ld+json'
        if format == 'text/turtle':
            g_str = g.serialize(format='turtle')
        else:
            g_str = serialize_in_json(g, uri=uri)
        gw_host = proxy.host + '/'
        if 'localhost' in gw_host and gw_host != request.host_url:
            g_str = g_str.replace(gw_host, request.host_url)
        return g_str
示例#8
0
    def canonicalTerm(self, term):

        if isinstance(term, URIRef):

            if self.prolog is not None:
                namespace_manager = NamespaceManager(Graph())

                for prefix,uri in list(self.prolog.prefixBindings.items()):
                    namespace_manager.bind(prefix, uri, override=False)

                try:
                    prefix,uri,localName = namespace_manager.compute_qname(term)
                except:
                    return term

                if prefix not in self.prolog.prefixBindings:
                    return term
                else:
                    return ':'.join([prefix, localName])

            else:
                return term

        elif isinstance(term, Literal):
            return term.n3()

        elif isinstance(term, BNode):
            return term.n3()

        else:
            assert isinstance(term, Variable)
            return term.n3()
示例#9
0
文件: ajax.py 项目: suchmaske/rdfedit
def serialize_graph(request, rdfjson, base):

    editgraph = Graph()
    editgraph.parse(data=rdfjson, format="rdf-json")

    namespace_manager = NamespaceManager(Graph())
    for ns in namespaces_dict:
        namespace_manager.bind(ns,
                               Namespace(namespaces_dict[ns]),
                               override=False)

    editgraph.namespace_manager = namespace_manager

    if base:
        """
        RDFLib Module to insert the base during serialization is buggy. Manual insertion needed
        graphxml_string = editgraph.serialize(format="pretty-xml", base=base)
        """
        graphxml_string = editgraph.serialize(format="pretty-xml").decode(
            'utf-8', 'ignore')
        graphxml_string = graphxml_string.replace(
            'rdf:RDF\n', 'rdf:RDF\n  xml:base="' + base + '"\n')
        # print graphxml_string
    else:
        graphxml_string = editgraph.serialize(format="pretty-xml")

    graphxml_to_db = RDF_XML(rdfxml_string=graphxml_string)
    graphxml_to_db.save()
    print graphxml_to_db.id

    return json.dumps({'message': graphxml_to_db.id})
示例#10
0
def get_manager(graph=None):
    if graph is None:
        graph = Graph()
    m = NamespaceManager(graph)
    m.bind('bibo', bibo)
    m.bind('carriers', carriers)
    m.bind('dc', dc)
    m.bind('dcmitype', dcmitype)
    m.bind('dcterms', dcterms)
    m.bind('ebucore', ebucore)
    m.bind('edm', edm)
    m.bind('ex', ex)
    m.bind('fabio', fabio)
    m.bind('fedora', fedora)
    m.bind('foaf', foaf)
    m.bind('geo', geo)
    m.bind('iana', iana)
    m.bind('ldp', ldp)
    m.bind('ndnp', ndnp)
    m.bind('oa', oa)
    m.bind('ore', ore)
    m.bind('owl', owl)
    m.bind('pcdm', pcdm)
    m.bind('pcdmuse', pcdmuse)
    m.bind('premis', premis)
    m.bind('prov', prov)
    m.bind('rdf', rdf)
    m.bind('rdfs', rdfs)
    m.bind('rel', rel)
    m.bind('sc', sc)
    m.bind('skos', skos)
    m.bind('xs', xs)
    return m
    def export_rdf(self, model_view='geometryview', rdf_mime='text/turtle'):
        g = Graph()
        s = URIRef(self.uri)
        GEO = Namespace("http://www.opengis.net/ont/geosparql#")
        SF = Namespace("http://www.opengis.net/ont/sf#")
        GEOX = Namespace("http://linked.data.gov.au/def/geox#")
        nsm = NamespaceManager(g)
        nsm.bind('geo', 'http://www.opengis.net/ont/geosparql#')
        nsm.bind('sf', 'http://www.opengis.net/ont/sf#')
        nsm.bind('geox', 'http://linked.data.gov.au/def/geox#')

        g.add((s, RDF.type, GEO.Geometry))

        list_of_geometry_types = ("Point", "Polygon", "LineString",
                                  "MultiPoint", "MultiLineString",
                                  "MultiPolygon")
        if self.instance['type'] in list_of_geometry_types:
            g.add((s, RDF.type,
                   URIRef("http://www.opengis.net/ont/sf#{geomType}".format(
                       geomType=self.instance['type']))))
            resource_uri = self._find_resource_uris()
            if resource_uri is not None:
                g.add((s, GEOX.isGeometryOf, URIRef(resource_uri)))
            wkt = self._geojson_to_wkt()
            g.add((s, GEO.asWKT, Literal(wkt, datatype=GEO.wktLiteral)))

        return g.serialize(format=self._get_rdf_mimetype(rdf_mime), nsm=nsm)
示例#12
0
    def init_database(self):
        """ Open the configured database """
        self._init_rdf_graph()
        L.debug("opening " + str(self.source))
        try:
            self.source.open()
        except OpenFailError as e:
            L.error('Failed to open the data source because: %s', e)
            raise

        nm = NamespaceManager(self['rdf.graph'])
        self['rdf.namespace_manager'] = nm
        self['rdf.graph'].namespace_manager = nm

        # A runtime version number for the graph should update for all changes
        # to the graph
        self['rdf.graph.change_counter'] = 0

        self['rdf.graph'].store.dispatcher.subscribe(
            TripleAddedEvent, self._context_changed_handler())
        self['rdf.graph'].store.dispatcher.subscribe(
            TripleRemovedEvent, self._context_changed_handler())

        self['rdf.graph']._add = self['rdf.graph'].add
        self['rdf.graph']._remove = self['rdf.graph'].remove
        self['rdf.graph'].add = self._my_graph_add
        self['rdf.graph'].remove = self._my_graph_remove
        nm.bind("", self['rdf.namespace'])
示例#13
0
class AIFSerializer(TurtleSerializer):
    xsd_namespace_manager = NamespaceManager(Graph())
    xsd_namespace_manager.bind('xsd', XSD)

    # when writing BNode as subjects, write closing bracket
    # in a new line at the end
    def s_squared(self, subject):
        if (self._references[subject] > 0) or not isinstance(subject, BNode):
            return False
        self.write('\n' + self.indent() + '[')
        self.predicateList(subject)
        self.write('\n] .')
        return True

    # when printing Literals, directly call Literal.n3()
    def label(self, node, position):
        if node == RDF.nil:
            return '()'
        if position is VERB and node in self.keywords:
            return self.keywords[node]
        if isinstance(node, Literal):
            return node.n3(namespace_manager=self.xsd_namespace_manager)
        else:
            node = self.relativize(node)

            return self.getQName(node, position == VERB) or node.n3()
示例#14
0
	def __init__(self, text=""):
		super(Sketch, self).__init__()
		
		self.rdfGraph = rdflib.Graph()
		self.namespace_manager = NamespaceManager(self.rdfGraph)
		
		self.SUPPORTED_FORMATS = ['xml', 'n3', 'turtle', 'nt', 'pretty-xml', 'dot']
		
		PREFIXES = [
					("", "http://this.sketch#"),
					("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
					("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
					("xml", "http://www.w3.org/XML/1998/namespace"),
					("xsd", "http://www.w3.org/2001/XMLSchema#"),
					('foaf', "http://xmlns.com/foaf/0.1/"),
					("npg", "http://ns.nature.com/terms/"),
					("npgg", "http://ns.nature.com/graphs/"),
					("npgx", "http://ns.nature.com/extensions/"),
					("bibo", "http://purl.org/ontology/bibo/"),
					("skos", "http://www.w3.org/2004/02/skos/core#"),
					("owl", "http://www.w3.org/2002/07/owl#"),
					]
		for pref in PREFIXES:
			self.bind(pref)
		if text:
			self.add(text)
示例#15
0
class Namespace(models.Model):
    """
        defines a namespace so we can use short prefix where convenient 
    """
    objects = NamespaceManager()

    uri = models.CharField('uri', max_length=100, unique=True, null=False)
    prefix = models.CharField('prefix', max_length=8, unique=True, null=False)
    notes = models.TextField(_(u'change note'), blank=True)

    def natural_key(self):
        return (self.uri)

    def get_base_uri(self):
        return self.uri[0:-1]

    def is_hash_uri(self):
        return self.uri[-1] == '#'

    @staticmethod
    def getNamespace(prefix):
        try:
            return Namespace.objects.get(prefix=prefix)
        except:
            return None

    class Meta:
        verbose_name = _(u'namespace')
        verbose_name_plural = _(u'namespaces')

    def __unicode__(self):
        return self.uri
示例#16
0
    def init(self):
        """ Open the configured database """
        self._init_rdf_graph()
        L.debug("opening " + str(self.source))
        try:
            self.source.open()
        except OpenFailError as e:
            L.error('Failed to open the data source because: %s', e)
            raise

        nm = NamespaceManager(self['rdf.graph'])
        self['rdf.namespace_manager'] = nm
        self['rdf.graph'].namespace_manager = nm

        # A runtime version number for the graph should update for all changes
        # to the graph
        self['rdf.graph.change_counter'] = 0

        self['rdf.graph']._add = self['rdf.graph'].add
        self['rdf.graph']._remove = self['rdf.graph'].remove
        self['rdf.graph'].add = self._my_graph_add
        self['rdf.graph'].remove = self._my_graph_remove
        try:
            nm.bind("", self['rdf.namespace'])
        except Exception:
            L.warning("Failed to bind default RDF namespace %s",
                      self['rdf.namespace'],
                      exc_info=True)
示例#17
0
 def test_namespaces_via_manager(self):
     """
     This tests that NamespaceManager.namespaces works correctly with an
     abstract Store.
     """
     namespace_manager = NamespaceManager(Graph(store=Store()))
     self.assertEqual(list(namespace_manager.namespaces()), [])
示例#18
0
    def __init__(self, doDebug=False):
        self.doDebug = doDebug
        self.rdfGraph = Graph()

        self.NMgr = NamespaceManager(self.rdfGraph)
        for (k, v) in RDFNS.nsTable.items():
            self.NMgr.bind(k, v[1])
示例#19
0
    def __init__(self,
                 configfile='config.ttl',
                 features=None,
                 upstream=None,
                 targetdir=None,
                 namespace=None,
                 oauthclientid=None,
                 oauthclientsecret=None):
        """Initialize store configuration.

        This method checks if the config file is given and reads the config file.
        If the config file is missing, it will be generated after analyzing the
        file structure.
        """
        logger = logging.getLogger('quit.conf.QuitConfiguration')
        logger.debug('Initializing configuration object.')

        self.features = features
        self.configchanged = False
        self.sysconf = Graph()
        self.upstream = None
        self.namespace = None
        self.oauthclientid = oauthclientid
        self.oauthclientsecret = oauthclientsecret

        self.nsMngrSysconf = NamespaceManager(self.sysconf)
        self.nsMngrSysconf.bind('', self.quit, override=False)

        self.__initstoreconfig(namespace=namespace,
                               upstream=upstream,
                               targetdir=targetdir,
                               configfile=configfile)
示例#20
0
def load_graph_prefixes():
    namespace_manager = NamespaceManager(Graph())

    # restPrefix = Namespace('http://restaurants.recommender.es/od-data/restaurant/')
    # locPrefix = Namespace('http://restaurants.recommender.es/od-data/location/')
    # ratePrefix = Namespace('http://restaurants.recommender.es/od-data/rate/')
    # contPrefix = Namespace('http://restaurants.recommender.es/od-data/contact/')
    #
    # namespace_manager.bind('rest', restPrefix)
    # namespace_manager.bind('loc', locPrefix)
    # namespace_manager.bind('rate', ratePrefix)
    # namespace_manager.bind('cont', contPrefix)

    tree = ET.parse('metadata.xml')
    root = tree.getroot()

    prefixes = root.find("prefixes")

    for prefix in prefixes:
        namespace = Namespace(prefix.find('namespace').text)
        prefix_name = prefix.get('name')

        namespace_manager.bind(prefix_name, namespace)

    return namespace_manager
示例#21
0
def apply_catalyst_napespace_manager(graph):
    # setup the RDF graph to be parsed
    npm = NamespaceManager(Graph())
    npm.bind("owl", "http://www.w3.org/2002/07/owl#")
    npm.bind("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
    npm.bind("rdfs", "http://www.w3.org/2000/01/rdf-schema#")
    npm.bind("xsd", "http://www.w3.org/2001/XMLSchema#")
    npm.bind("trig", "http://www.w3.org/2004/03/trix/rdfg-1/")
    npm.bind("foaf", "http://xmlns.com/foaf/0.1/")
    npm.bind("dcterms", "http://purl.org/dc/terms/")
    npm.bind("sioc", "http://rdfs.org/sioc/ns#")
    npm.bind("oa", "http://www.openannotation.org/ns/")
    npm.bind("idea", "http://purl.org/catalyst/idea#")
    npm.bind("ibis", "http://purl.org/catalyst/ibis#")
    npm.bind("assembl", "http://purl.org/assembl/core#")
    npm.bind("catalyst", "http://purl.org/catalyst/core#")
    npm.bind("version", "http://purl.org/catalyst/version#")
    npm.bind("vote", "http://purl.org/catalyst/vote#")
    npm.bind("eg_site", "http://www.assembl.net/")
    npm.bind("eg_d1", "http://www.assembl.net/discussion/1/")
    npm.bind("kmieg", "http://maptesting.kmi.open.ac.uk/api/")
    npm.bind("kmiegnodes", "http://maptesting.kmi.open.ac.uk/api/nodes/")
    graph.namespace_manager = npm
    for c in graph.contexts():
        c.namespace_manager = npm
示例#22
0
def serialization(dict1, dict2):
    rdf = Graph()
    namespace_manager = NamespaceManager(rdf)
    namespace_manager.bind("skos", SKOS)
    VIVO = Namespace("http://vivoweb.org/ontology/core#")
    namespace_manager.bind("core", VIVO)

    # Delete double quotes in comp_keys keys
    for k in list(dict2):
        if '"' in k:
            k_clean = k.replace('"', "")
            dict2[k_clean] = dict2[k]
            del dict2[k]

    # Build semantic triple of concepts
    for uri in dict2:
        concept = URIRef(uri)
        rdf.add((concept, RDF.type, SKOS.Concept))
        for keyword in dict2[uri]:
            rdf.add((concept, RDFS.label, Literal(keyword["keyword"], lang=keyword["language"])))

    # Build semantic triple of researcher
    for researcher in dict1:
        rdf.add((URIRef(researcher["researcher"]), VIVO.hasResearchArea, URIRef(researcher["term"])))

    print(rdf.serialize(format="turtle", encoding="UTF-8").decode("utf-8"))

    # Serialize to a file
    rdf.serialize(destination="../files/researchers_areas.ttl", format="turtle")
示例#23
0
def loadSOGraph(
    filename=None,
    data=None,
    publicID=None,
    normalize=True,
    deslop=True,
    format="json-ld",
):
    """
    Load RDF string or file to an RDFLib ConjunctiveGraph

    Creates a ConjunctiveGraph from  the provided file or text. If both are
    provided then text is used.

    NOTE: Namespace use of ``<http://schema.org>``, ``<https://schema.org>``, or
    ``<http://schema.org/>`` is normalized to ``<https://schema.org/>`` if
    ``normalize`` is True.

    NOTE: Case of ``SO:`` properties in `SO_TERMS` is adjusted consistency if
    ``deslop`` is True

    Args:
        filename (string):  path to RDF file on disk
        data (string): RDF text
        publicID (string): (from rdflib) The logical URI to use as the document base. If None specified the document location is used.
        normalize (boolean): Normalize the use of schema.org namespace
        deslop (boolean): Adjust schema.org terms for case consistency
        format (string): The serialization format of the RDF to load

    Returns:
        ConjunctiveGraph: The loaded graph

    Example:

    .. jupyter-execute:: examples/code/eg_loadsograph_01.py

    """
    g = ConjunctiveGraph()
    if data is not None:
        g.parse(data=data, format=format, publicID=publicID)
    elif filename is not None:
        g.parse(filename, format=format, publicID=publicID)
    if not (normalize or deslop):
        return g
    # Now normalize the graph namespace use to https://schema.org/
    ns = NamespaceManager(g)
    ns.bind(SO_PREFIX, SCHEMA_ORG, override=True, replace=True)
    g2 = ConjunctiveGraph()
    g2.namespace_manager = ns
    for s, p, o in g:
        trip = [s, p, o]
        if normalize:
            for i, t in enumerate(trip):
                trip[i] = _normalizeTerm(t)
        if deslop:
            for i, t in enumerate(trip):
                trip[i] = _desloppifyTerm(g, t)
        g2.add(trip)
    return g2
示例#24
0
    def _render_dcat_rdf(self):
        # get vocab RDF
        g = Graph()
        # map nice prefixes to namespaces
        NamespaceManager(g)
        DCAT = Namespace("https://www.w3.org/ns/dcat#")
        g.namespace_manager.bind("dcat", DCAT)
        g.namespace_manager.bind("dct", DCTERMS)
        g.namespace_manager.bind("owl", OWL)
        g.namespace_manager.bind("skos", SKOS)
        s = URIRef(self.vocab.uri)

        g.add((s, RDF.type, DCAT.Dataset))
        if self.vocab.title:
            g.add((s, DCTERMS.title, Literal(self.vocab.title)))
        if self.vocab.description:
            g.add((s, DCTERMS.description, Literal(self.vocab.description)))
        if self.vocab.creator:
            if (self.vocab.creator[:7] == "http://"
                    or self.vocab.creator[:7] == "https://"):  # if url
                g.add((s, DCTERMS.creator, URIRef(self.vocab.creator)))
            else:  # else literal
                g.add((s, DCTERMS.creator, Literal(self.vocab.creator)))
        if self.vocab.created:
            g.add((s, DCTERMS.created,
                   Literal(self.vocab.created, datatype=XSD.date)))
        if self.vocab.modified:
            g.add((s, DCTERMS.modified,
                   Literal(self.vocab.modified, datatype=XSD.date)))
        if self.vocab.versionInfo:
            g.add((s, OWL.versionInfo, Literal(self.vocab.versionInfo)))
        if self.vocab.accessURL:
            g.add((s, DCAT.accessURL, URIRef(self.vocab.accessURL)))
        if self.vocab.downloadURL:
            g.add((s, DCAT.downloadURL, URIRef(self.vocab.downloadURL)))

        sp = URIRef(SYSTEM_URI_BASE + "/sparql")
        g.add((sp, DCAT.servesDataset, s))
        g.add((sp, DCTERMS.title, Literal("VocPrez SPARQL Service")))
        api = URIRef(SYSTEM_URI_BASE)
        g.add((api, DCAT.servesDataset, s))
        g.add((api, DCTERMS.title, Literal("VocPrez Linked Data API")))

        if self.vocab.other_properties is not None:
            for prop in self.vocab.other_properties:
                # other properties from DCAT, DCTERMS only
                if str(prop.uri).startswith(("https://www.w3.org/ns/dcat#",
                                             "http://purl.org/dc/terms/")):
                    g.add((s, URIRef(prop.uri), prop.value))

        # serialise in the appropriate RDF format
        if self.mediatype in ["application/rdf+json", "application/json"]:
            return Response(g.serialize(format="json-ld"),
                            mimetype=self.mediatype,
                            headers=self.headers)
        else:
            return Response(g.serialize(format=self.mediatype),
                            mimetype=self.mediatype,
                            headers=self.headers)
示例#25
0
 def create_graph(self):
     self.rdf_graph = Graph()
     namespace_manager = NamespaceManager(self.rdf_graph)
     namespace_manager.bind('ros', ROS, override=False)
     namespace_manager.bind('dul', DUL, override=False)
     namespace_manager.bind('owl', OWL, override=False)
     namespace_manager.bind('rdf', RDF, override=False)
     namespace_manager.bind('wf', EASE_WF, override=False)
示例#26
0
 def export_rdf(self, model_view='default', rdf_mime='text/turtle'):
     g = Graph()
     s = URIRef(self.uri)
     DCAT = Namespace("http://www.w3.org/ns/dcat#")
     nsm = NamespaceManager(g)
     nsm.bind('dcat', 'http://www.w3.org/ns/dcat#')
     g.add((s, RDF.type, DCAT.Dataset))
     return g.serialize(format=self._get_rdf_mimetype(rdf_mime), nsm=nsm)
示例#27
0
文件: conf.py 项目: mindis/QuitStore
    def __init__(self,
                 configmode=None,
                 configfile='config.ttl',
                 features=None,
                 repository=None,
                 targetdir=None,
                 namespace=None):
        """The init method.

        This method checks if the config file is given and reads the config file.
        If the config file is missing, it will be generated after analyzing the
        file structure.
        """
        logger = logging.getLogger('quit.conf.QuitConfiguration')
        logger.debug('Initializing configuration object.')

        self.features = features
        self.configchanged = False
        self.sysconf = Graph()
        self.graphconf = None
        self.origin = None
        self.graphs = {}
        self.files = {}
        self.namespace = None

        self.quit = Namespace('http://quit.aksw.org/vocab/')
        self.nsMngrSysconf = NamespaceManager(self.sysconf)
        self.nsMngrSysconf.bind('',
                                'http://quit.aksw.org/vocab/',
                                override=False)
        self.nsMngrGraphconf = NamespaceManager(self.sysconf)
        self.nsMngrGraphconf.bind('',
                                  'http://quit.aksw.org/vocab/',
                                  override=False)

        try:
            self.__initstoreconfig(namespace=namespace,
                                   repository=repository,
                                   targetdir=targetdir,
                                   configfile=configfile,
                                   configmode=configmode)
        except InvalidConfigurationError as e:
            logger.error(e)
            raise e

        return
示例#28
0
 def add_namespaces(ns_definition):
     g = Graph()
     for ns_def in ns_definition:
         new_NS = Namespace(ns_def[1])
         ns_manager = NamespaceManager(Graph())
         ns_manager.bind(ns_def[0], new_NS)
     return ns_manager
     pass
示例#29
0
    def __init__(self, bindings: dict = None):
        self.graph = Graph()
        self.graph.namespace_manager = NamespaceManager(self.graph)
        for prefix, namespace in bindings.items():
            self.graph.namespace_manager.bind(prefix, namespace)

        self.downwards = defaultdict(lambda: True)
        self.updwards = defaultdict(lambda: True)
示例#30
0
 def dumpNQ(self, out):
     cg = rdflib.graph.ConjunctiveGraph()
     print("Exporting to NQ file {}".format(out))
     for key in self.gix.keys():
         if key in self.included.keys():
             print(" - Processing key {}".format(key))
             graphs = self.gix[key]
             for graph in graphs:
                 #					self.__fixgraph(graph)
                 for prefix, namespace in NamespaceManager(
                         graph).namespaces():
                     NamespaceManager(cg).bind(prefix, namespace)
                 for trip in graph.triples((None, None, None)):
                     cg.add((trip[0], trip[1], trip[2], graph))
         else:
             print(" - Not included: {}".format(key))
     NamespaceManager(cg).bind("dc", "http://purl.org/dc/elements/1.1/")
     cg.serialize(destination=out, format='trig')