Python rdflib.namespace.RDFS.label() Examples

The following are 30 code examples of rdflib.namespace.RDFS.label(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rdflib.namespace.RDFS , or try the search function .
Example #1
Source File: helpers.py    From pySHACL with Apache License 2.0 6 votes vote down vote up
def __init__(self, node, sht_graph, result_node, data_graph, shapes_graph, label=None, status=None):
        """

        :param sht_graph:
        :type sht_graph: rdflib.Graph
        :param data_graph:
        :type data_graph: rdflib.Graph
        :param shapes_graph:
        :type shapes_graph: rdflib.Graph
        :param label:
        """
        self.node = node
        self.sht_graph = sht_graph
        self.sht_result = result_node
        self.data_graph = data_graph
        self.shapes_graph = shapes_graph
        self.label = label
        self.status = status 
Example #2
Source File: test_organization_rdf.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_all_fields(self):
        org = OrganizationFactory(url=faker.uri())
        org_url = url_for('organizations.show_redirect',
                          org=org.id,
                          _external=True)
        o = organization_to_rdf(org)
        g = o.graph

        self.assertIsInstance(o, RdfResource)
        self.assertEqual(len(list(g.subjects(RDF.type, FOAF.Organization))), 1)

        self.assertEqual(o.value(RDF.type).identifier, FOAF.Organization)

        self.assertIsInstance(o.identifier, URIRef)
        self.assertEqual(o.identifier.toPython(), org_url)
        self.assertEqual(o.value(FOAF.name), Literal(org.name))
        self.assertEqual(o.value(RDFS.label), Literal(org.name))
        self.assertEqual(o.value(FOAF.homepage).identifier, URIRef(org.url)) 
Example #3
Source File: rdf.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def user_to_rdf(user, graph=None):
    '''
    Map a Resource domain model to a DCAT/RDF graph
    '''
    graph = graph or Graph(namespace_manager=namespace_manager)
    if user.id:
        user_url = url_for('users.show_redirect',
                           user=user.id,
                           _external=True)
        id = URIRef(user_url)
    else:
        id = BNode()
    o = graph.resource(id)
    o.set(RDF.type, FOAF.Person)
    o.set(FOAF.name, Literal(user.fullname))
    o.set(RDFS.label, Literal(user.fullname))
    if user.website:
        o.set(FOAF.homepage, URIRef(user.website))
    return o 
Example #4
Source File: test_user_rdf.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_all_fields(self):
        user = UserFactory(website=faker.uri())
        user_url = url_for('users.show_redirect',
                           user=user.id,
                           _external=True)
        u = user_to_rdf(user)
        g = u.graph

        self.assertIsInstance(u, RdfResource)
        self.assertEqual(len(list(g.subjects(RDF.type, FOAF.Person))), 1)

        self.assertEqual(u.value(RDF.type).identifier, FOAF.Person)

        self.assertIsInstance(u.identifier, URIRef)
        self.assertEqual(u.identifier.toPython(), user_url)
        self.assertEqual(u.value(FOAF.name), Literal(user.fullname))
        self.assertEqual(u.value(RDFS.label), Literal(user.fullname))
        self.assertEqual(u.value(FOAF.homepage).identifier,
                         URIRef(user.website)) 
Example #5
Source File: helpers.py    From pySHACL with Apache License 2.0 6 votes vote down vote up
def __init__(self, base, sht_graph, node, includes, entries=None, label=None):
        """
        Manifest constructor
        :param base: string
        :type base: the "file://x" location uri of the base manifest graph
        :param sht_graph:
        :type sht_graph: rdflib.Graph
        :param node: The Graph Node of the manifest itself. (unused)
        :type node: rdflib.term.Identifier
        :param includes:
        :type includes: list(Manifest)
        :param entries:
        :type entries: list | None
        :param label:
        """
        self.base = base
        self.sht_graph = sht_graph
        self.node = node
        self.includes = includes
        self.entries = entries
        self.label = label 
Example #6
Source File: datatype_to_rdf_tests.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_rdf_concept_list(self):
        dt = self.DT.get_instance("concept-list")
        concept_list = [
            "d75977c1-635b-41d5-b53d-1c82d2237b67",  # junk sculpture@en, has aat identifier
            "4beb7055-8a6e-45a3-9bfb-32984b6f82e0",  # "example document type"@en-us, no ext id}
        ]

        edge_info = {}
        edge_info["range_tile_data"] = concept_list
        edge_info["r_uri"] = URIRef("http://vocab.getty.edu/aat/300047196")
        edge_info["d_uri"] = URIRef("test")
        edge = Mock()
        edge.ontologyproperty = CIDOC_NS["P2_has_type"]
        edge.rangenode.ontologyclass = CIDOC_NS["E55_Type"]
        graph = dt.to_rdf(edge_info, edge)

        edge_info["r_uri"] = ARCHES_NS["concepts/037daf4d-054a-44d2-9c0a-108b59e39109"]
        graph += dt.to_rdf(edge_info, edge)

        self.assertTrue((edge_info["d_uri"], edge.ontologyproperty, URIRef("http://vocab.getty.edu/aat/300047196")) in graph)
        self.assertTrue((URIRef("http://vocab.getty.edu/aat/300047196"), RDFS.label, Literal("junk sculpture")) in graph)
        self.assertTrue((edge_info["d_uri"], edge.ontologyproperty, ARCHES_NS["concepts/037daf4d-054a-44d2-9c0a-108b59e39109"]) in graph)
        self.assertTrue((ARCHES_NS["concepts/037daf4d-054a-44d2-9c0a-108b59e39109"], RDFS.label, Literal("example document type")) in graph) 
Example #7
Source File: datatype_to_rdf_tests.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_rdf_concept(self):
        dt = self.DT.get_instance("concept")
        # d75977c1-635b-41d5-b53d-1c82d2237b67 should be the ConceptValue for "junk sculpture"
        # Main concept should be 0ad97528-0fb0-43bf-afee-0fb9dde78b99
        # should also have an identifier of http://vocab.getty.edu/aat/300047196

        edge_info = {}
        edge_info["range_tile_data"] = "d75977c1-635b-41d5-b53d-1c82d2237b67"
        edge_info["r_uri"] = URIRef("http://vocab.getty.edu/aat/300047196")
        edge_info["d_uri"] = URIRef("test")
        edge = Mock()
        edge.ontologyproperty = CIDOC_NS["P2_has_type"]
        edge.rangenode.ontologyclass = CIDOC_NS["E55_Type"]

        graph = dt.to_rdf(edge_info, edge)
        print(graph.serialize(format="ttl"))
        self.assertTrue((edge_info["d_uri"], edge.ontologyproperty, URIRef("http://vocab.getty.edu/aat/300047196")) in graph)
        self.assertTrue((URIRef("http://vocab.getty.edu/aat/300047196"), RDFS.label, Literal("junk sculpture")) in graph) 
Example #8
Source File: concept_types.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def append_to_document(self, document, nodevalue, nodeid, tile, provisional=False):
        try:
            assert isinstance(nodevalue, (list, tuple))  # assert nodevalue is an array
        except AssertionError:
            nodevalue = [nodevalue]
        for valueid in nodevalue:
            value = self.get_value(valueid)
            date_range = self.get_concept_dates(value.concept)
            if date_range is not None:
                min_date = ExtendedDateFormat(date_range["min_year"]).lower
                max_date = ExtendedDateFormat(date_range["max_year"]).upper
                if {"gte": min_date, "lte": max_date} not in document["date_ranges"]:
                    document["date_ranges"].append(
                        {"date_range": {"gte": min_date, "lte": max_date}, "nodegroup_id": tile.nodegroup_id, "provisional": provisional}
                    )
            document["domains"].append(
                {
                    "label": value.value,
                    "conceptid": value.concept_id,
                    "valueid": valueid,
                    "nodegroup_id": tile.nodegroup_id,
                    "provisional": provisional,
                }
            )
            document["strings"].append({"string": value.value, "nodegroup_id": tile.nodegroup_id, "provisional": provisional}) 
Example #9
Source File: models.py    From open-context-py with GNU General Public License v3.0 6 votes vote down vote up
def save_entity_labels(self):
        """ saves labels of entities in a vocabulary """
        output = False
        if self.graph is not False and self.vocabulary_uri is not False:
            output = []
            if self.replace_old:
                LinkEntity.objects.filter(vocab_uri=self.vocabulary_uri).delete()
            for s, p, o in self.graph.triples((None,
                                               RDFS.label,
                                               None)):
                subject_uri = s.__str__()  # get the URI of the subject as a string
                label = o.__str__()  # get the Label of from object as a string
                le_ents = LinkEntity.objects.filter(uri=subject_uri)[:1]
                if len(le_ents) < 1 or self.replace_old:
                    newr = LinkEntity()
                    newr.uri = subject_uri
                    newr.label = label
                    newr.alt_label = label
                    newr.ent_type = 'class'
                    newr.vocab_uri = self.vocabulary_uri
                    newr.save()
                    act_t = {'s': subject_uri,
                             'o': label}
                    output.append(act_t)
        return output 
Example #10
Source File: skosify.py    From Skosify with MIT License 6 votes vote down vote up
def initialize_concept_scheme(rdf, cs, label, language, set_modified):
    """Initialize a concept scheme: Optionally add a label if the concept
    scheme doesn't have a label, and optionally add a dct:modified
    timestamp."""

    # check whether the concept scheme is unlabeled, and label it if possible
    labels = list(rdf.objects(cs, RDFS.label)) + \
        list(rdf.objects(cs, SKOS.prefLabel))
    if len(labels) == 0:
        if not label:
            logging.warning(
                "Concept scheme has no label(s). "
                "Use --label option to set the concept scheme label.")
        else:
            logging.info(
                "Unlabeled concept scheme detected. Setting label to '%s'" %
                label)
            rdf.add((cs, RDFS.label, Literal(label, language)))

    if set_modified:
        curdate = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + 'Z'
        rdf.remove((cs, DCTERMS.modified, None))
        rdf.add((cs, DCTERMS.modified, Literal(curdate, datatype=XSD.dateTime))) 
Example #11
Source File: assoc_rdfgen.py    From ontobio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def emit_label(self, s, o):
        return self.emit(s, RDFS.label, Literal(o)) 
Example #12
Source File: api.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def get_uri_label_from_graph(self, uri):
        """ gets the label (and graph)
            for an Uberon enity identified by a URI
        """
        label = False
        graph = self.get_uri_graph(uri)
        if graph is not False:
            for s, p, o in self.graph.triples((None,
                                               RDFS.label,
                                               None)):
                subject_uri = s.__str__()  # get the URI of the subject as a string
                label = o.__str__()  # get the Label of the object as a string
                break
        return label 
Example #13
Source File: skosify.py    From Skosify with MIT License 5 votes vote down vote up
def check_labels(rdf, preflabel_policy):
    """Check that resources have only one prefLabel per language (S14)
    and check overlap between disjoint label properties (S13)."""
    check.preflabel_uniqueness(rdf, preflabel_policy)
    check.label_overlap(rdf, True) 
Example #14
Source File: assoc_rdfgen.py    From ontobio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def lookup_relation(self, label):
        label = label.replace('_', ' ')

        # Return the cached label -> URI or None
        if label in self.ro_lookup:
            return self.uri(self.ro_lookup[label])
        else:
            return None 
Example #15
Source File: assoc_rdfgen.py    From ontobio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, label=None):
        self.base = genid(base="http://model.geneontology.org") + '/'
        self.graph = rdflib.Graph(identifier=self.base)
        self.graph.bind("owl", OWL)
        self.graph.bind("obo", "http://purl.obolibrary.org/obo/")

        self.graph.add((self.base, RDF.type, OWL.Ontology))
        if label != None:
            self.graph.add((self.base, RDFS.label, Literal(label))) 
Example #16
Source File: rdflib_bridge.py    From ontobio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rdfgraph_to_ontol(rg):
    """
    Return an Ontology object from an rdflib graph object

    Status: Incomplete
    """
    digraph = networkx.MultiDiGraph()
    from rdflib.namespace import RDF
    label_map = {}
    for c in rg.subjects(RDF.type, OWL.Class):
        cid = contract_uri_wrap(c)
        logger.info("C={}".format(cid))
        for lit in rg.objects(c, RDFS.label):
            label_map[cid] = lit.value
            digraph.add_node(cid, label=lit.value)
        for s in rg.objects(c, RDFS.subClassOf):
            # todo - blank nodes
            sid = contract_uri_wrap(s)
            digraph.add_edge(sid, cid, pred='subClassOf')

    logger.info("G={}".format(digraph))
    payload = {
        'graph': digraph,
        #'xref_graph': xref_graph,
        #'graphdoc': obographdoc,
        #'logical_definitions': logical_definitions
    }
            
    ont = Ontology(handle='wd', payload=payload)
    return ont 
Example #17
Source File: wikidata.py    From followthemoney with MIT License 5 votes vote down vote up
def transform(input):
    prev = None
    entity = None
    for (s, p, o) in parse_triples(input):
        if s != prev and entity is not None:
            # print(entity.to_dict())
            pass
        if s != prev:
            prev = s
            if s.startswith(SPECIAL):
                qid = s[len(SPECIAL):]
            else:
                qid = s[len(ENTITY):]
            entity = model.make_entity('Thing')
            entity.make_id(qid)
            entity.add('wikidataId', qid)
            if s.startswith(ENTITY):
                entity.add('sourceUrl', str(s))

        if p in [SKOS.prefLabel, RDFS.label, SCHEMA.name]:
            entity.add('name', str(o))
            continue

        print(s, p, o)

        if p == PROP.P31:
            # print((p, o))
            pass 
Example #18
Source File: datatypes.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def transform_export_values(self, value, *args, **kwargs):
        ret = ""
        if (
            kwargs["concept_export_value_type"] is None
            or kwargs["concept_export_value_type"] == ""
            or kwargs["concept_export_value_type"] == "label"
        ):
            ret = self.get_option_text(models.Node.objects.get(nodeid=kwargs["node"]), value)
        elif kwargs["concept_export_value_type"] == "both":
            ret = value + "|" + self.get_option_text(models.Node.objects.get(nodeid=kwargs["node"]), value)
        elif kwargs["concept_export_value_type"] == "id":
            ret = value
        return ret 
Example #19
Source File: test_organization_rdf.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_minimal(self):
        org = OrganizationFactory.build()  # Does not have an URL
        o = organization_to_rdf(org)
        g = o.graph

        self.assertIsInstance(o, RdfResource)
        self.assertEqual(len(list(g.subjects(RDF.type, FOAF.Organization))), 1)

        self.assertEqual(o.value(RDF.type).identifier, FOAF.Organization)

        self.assertIsInstance(o.identifier, BNode)
        self.assertEqual(o.value(FOAF.name), Literal(org.name))
        self.assertEqual(o.value(RDFS.label), Literal(org.name)) 
Example #20
Source File: test_user_rdf.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_minimal(self):
        user = UserFactory.build()  # Does not have an URL
        u = user_to_rdf(user)
        g = u.graph

        self.assertIsInstance(u, RdfResource)
        self.assertEqual(len(list(g.subjects(RDF.type, FOAF.Person))), 1)

        self.assertEqual(u.value(RDF.type).identifier, FOAF.Person)

        self.assertIsInstance(u.identifier, BNode)
        self.assertEqual(u.value(FOAF.name), Literal(user.fullname))
        self.assertEqual(u.value(RDFS.label), Literal(user.fullname)) 
Example #21
Source File: helpers.py    From pySHACL with Apache License 2.0 5 votes vote down vote up
def collect_tests(self):
        if not self.has_entries:
            return []
        tests = []
        g = self.sht_graph
        for entry in self.entries:
            test_types = set(g.objects(entry, RDF.type))
            if SHT.Validate not in test_types:
                continue
            try:
                label = next(iter(g.objects(entry, RDFS.label)))
                label = str(label)
            except StopIteration:
                label = None
            try:
                action = next(iter(g.objects(entry, MF.action)))
            except StopIteration:
                raise RuntimeError("MF Validate has no value for mf:action")
            try:
                result = next(iter(g.objects(entry, MF.result)))
            except StopIteration:
                raise RuntimeError("MF Validate has no value for mf:result")
            try:
                data_graph = next(iter(g.objects(action, SHT.dataGraph)))
            except StopIteration:
                raise RuntimeError("mf:action has no value for sht:dataGraph")
            try:
                shapes_graph = next(iter(g.objects(action, SHT.shapesGraph)))
            except StopIteration:
                raise RuntimeError("mf:action has no value for sht:shapesGraph")
            try:
                status = next(iter(g.objects(entry, MF.status)))
            except StopIteration:
                raise RuntimeError("MF Validate has no value for mf:status")
            if str(shapes_graph) == str(data_graph):
                shapes_graph = None
            if str(data_graph) == self.base:
                data_graph = self.sht_graph
            test = SHTValidate(entry, self.sht_graph, result, data_graph, shapes_graph, label=label, status=status)
            tests.append(test)
        return tests 
Example #22
Source File: concept_types.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def ignore_keys(self):
        return ["http://www.w3.org/2000/01/rdf-schema#label http://www.w3.org/2000/01/rdf-schema#Literal"] 
Example #23
Source File: concept_types.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def ignore_keys(self):
        return ["http://www.w3.org/2000/01/rdf-schema#label http://www.w3.org/2000/01/rdf-schema#Literal"] 
Example #24
Source File: concept_types.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_concept_export_value(self, valueid, concept_export_value_type=None):
        ret = ""
        if valueid is None or valueid.strip() == "":
            pass
        elif concept_export_value_type is None or concept_export_value_type == "" or concept_export_value_type == "label":
            ret = self.get_value(valueid).value
        elif concept_export_value_type == "both":
            ret = valueid + "|" + self.get_value(valueid).value
        elif concept_export_value_type == "id":
            ret = valueid
        return ret 
Example #25
Source File: datatypes.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def ignore_keys(self):
        return ["http://www.w3.org/2000/01/rdf-schema#label http://www.w3.org/2000/01/rdf-schema#Literal"] 
Example #26
Source File: datatypes.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def transform_export_values(self, value, *args, **kwargs):
        new_values = []
        for val in value:
            if (
                kwargs["concept_export_value_type"] is None
                or kwargs["concept_export_value_type"] == ""
                or kwargs["concept_export_value_type"] == "label"
            ):
                new_values.append(self.get_option_text(models.Node.objects.get(nodeid=kwargs["node"]), val))
            elif kwargs["concept_export_value_type"] == "both":
                new_values.append(val + "|" + self.get_option_text(models.Node.objects.get(nodeid=kwargs["node"]), val))
            elif kwargs["concept_export_value_type"] == "id":
                new_values.append(val)
        return ",".join(new_values) 
Example #27
Source File: profiles.py    From daf-recipes with GNU General Public License v3.0 4 votes vote down vote up
def _spatial(self, subject, predicate):
        '''
        Returns a dict with details about the spatial location

        Both subject and predicate must be rdflib URIRef or BNode objects

        Returns keys for uri, text or geom with the values set to
        None if they could not be found.

        Geometries are always returned in GeoJSON. If only WKT is provided,
        it will be transformed to GeoJSON.

        Check the notes on the README for the supported formats:

        https://github.com/ckan/ckanext-dcat/#rdf-dcat-to-ckan-dataset-mapping
        '''

        uri = None
        text = None
        geom = None

        for spatial in self.g.objects(subject, predicate):

            if isinstance(spatial, URIRef):
                uri = unicode(spatial)

            if isinstance(spatial, Literal):
                text = unicode(spatial)

            if (spatial, RDF.type, DCT.Location) in self.g:
                for geometry in self.g.objects(spatial, LOCN.geometry):
                    if (geometry.datatype == URIRef(GEOJSON_IMT) or
                            not geometry.datatype):
                        try:
                            json.loads(unicode(geometry))
                            geom = unicode(geometry)
                        except (ValueError, TypeError):
                            pass
                    if not geom and geometry.datatype == GSP.wktLiteral:
                        try:
                            geom = json.dumps(wkt.loads(unicode(geometry)))
                        except (ValueError, TypeError):
                            pass
                for label in self.g.objects(spatial, SKOS.prefLabel):
                    text = unicode(label)
                for label in self.g.objects(spatial, RDFS.label):
                    text = unicode(label)

        return {
            'uri': uri,
            'text': text,
            'geom': geom,
        } 
Example #28
Source File: helpers.py    From pySHACL with Apache License 2.0 4 votes vote down vote up
def load_manifest(filename, recursion=0):
    """
    Load a testing Manifest from a file location, return a Manifest object
    :param filename: the filename of the manifest document.
    :type filename: string
    :param recursion: re-entry counter.
    :type recursion: int
    :return: the loaded Manifest object
    :rtype: Manifest
    """
    if recursion >= 10:
        return None
    graph = rdflib.Graph()
    with open(filename, 'rb') as manifest_file:
        if platform.system() == "Windows":
            base = "file:///{}".format(path.abspath(manifest_file.name).replace("\\", "/"))
        else:
            base = "file://{}".format(path.abspath(manifest_file.name))
        graph.parse(file=manifest_file, format='turtle', publicID=base)
    try:
        manifest = next(iter(graph.subjects(RDF.type, MF.Manifest)))
    except StopIteration:
        raise RuntimeError("Test cannot run. mf:Manifest not found in the manifest file: {}.".format(filename))
    try:
        label = next(iter(graph.objects(manifest, RDFS.label)))
        label = str(label)
    except StopIteration:
        label = None
    include_manifests = []
    include_objects = list(graph.objects(manifest, MF.include))
    for i in iter(include_objects):
        if isinstance(i, rdflib.URIRef):
            href = str(i)
            if platform.system() == "Windows":
                if href.startswith("file:///"):
                    child_mf = load_manifest(href[8:], recursion=recursion+1)
                else:
                    raise RuntimeError("Manifest can only include file:/// uris")
            else:
                if href.startswith("file://"):
                    child_mf = load_manifest(href[7:], recursion=recursion + 1)
                else:
                    raise RuntimeError("Manifest can only include file:// uris")
            if child_mf is None:
                raise RuntimeError("Manifest include chain is too deep!")
            include_manifests.append(child_mf)
    try:
        entries_list = next(iter(graph.objects(manifest, MF.entries)))
        entries = []
        for i in graph.items(entries_list):
            entries.append(i)
    except StopIteration:
        entries = None
    mf = Manifest(base, graph, manifest, include_manifests, entries=entries, label=label)
    # if entries and len(entries) > 0:
    #     manifests_with_entries.append(mf)
    return mf 
Example #29
Source File: gazgraph.py    From open-context-py with GNU General Public License v3.0 4 votes vote down vote up
def make_graph(self):
        associated_uris = []
        self.get_db_data()
        if len(self.data_obj.gaz_items) > 0:
            for uuid, gaz_item in self.data_obj.gaz_items.items():
                if gaz_item.is_valid:
                    # only make annotations if the item is valid
                    self.make_add_triple(gaz_item.uri,
                                         RDF.type,
                                         self.make_full_uri('lawd', 'Place'))
                    self.make_add_triple(gaz_item.uri,
                                         RDFS.label,
                                         None,
                                         gaz_item.label)
                    self.make_add_triple(gaz_item.uri,
                                         self.make_full_uri('dcterms', 'title'),
                                         None,
                                         gaz_item.title)
                    self.make_add_triple(gaz_item.uri,
                                         self.make_full_uri('dcterms', 'description'),
                                         None,
                                         gaz_item.description)
                    self.make_add_triple(gaz_item.uri,
                                         self.make_full_uri('dcterms', 'isPartOf'),
                                         gaz_item.project_uri)
                    if isinstance(gaz_item.temporal, str):
                        self.make_add_triple(gaz_item.uri,
                                             self.make_full_uri('dcterms', 'temporal'),
                                             None,
                                             gaz_item.temporal)
                    if gaz_item.geo_meta is not None and gaz_item.geo_meta is not False:
                        # print('ok! geo-meta: ' + str(gaz_item.geo_meta))
                        if len(gaz_item.geo_meta) > 0:
                            geo = gaz_item.geo_meta[0]
                            geo_node = BNode()
                            act_s = URIRef(gaz_item.uri)
                            pred_uri = self.make_full_uri('geo', 'location')
                            act_p = URIRef(pred_uri)
                            self.g.add((act_s, act_p, geo_node))
                            pred_uri = self.make_full_uri('geo', 'lat')
                            act_p = URIRef(pred_uri)
                            self.g.add((geo_node, act_p, Literal(geo.latitude)))
                            pred_uri = self.make_full_uri('geo', 'long')
                            act_p = URIRef(pred_uri)
                            self.g.add((geo_node, act_p, Literal(geo.longitude))) 
Example #30
Source File: skosify.py    From Skosify with MIT License 4 votes vote down vote up
def transform_labels(rdf, defaultlanguage):
    # fix labels and documentary notes with extra whitespace
    for labelProp in (
            SKOS.prefLabel, SKOS.altLabel, SKOS.hiddenLabel,
            SKOSEXT.candidateLabel, SKOS.note, SKOS.scopeNote,
            SKOS.definition, SKOS.example, SKOS.historyNote,
            SKOS.editorialNote, SKOS.changeNote, RDFS.label):
        for conc, label in sorted(rdf.subject_objects(labelProp)):
            if not isinstance(label, Literal):
                continue
            # strip extra whitespace, if found
            if len(label.strip()) < len(label):
                logging.warning(
                    "Stripping whitespace from label of %s: '%s'", conc, label)
                newlabel = Literal(label.strip(), label.language)
                rdf.remove((conc, labelProp, label))
                rdf.add((conc, labelProp, newlabel))
                label = newlabel
            # set default language
            if defaultlanguage and label.language is None:
                logging.warning(
                    "Setting default language of '%s' to %s",
                    label, defaultlanguage)
                newlabel = Literal(label, defaultlanguage)
                rdf.remove((conc, labelProp, label))
                rdf.add((conc, labelProp, newlabel))

    # make skosext:candidateLabel either prefLabel or altLabel
    # make a set of (concept, language) tuples for concepts which have
    # candidateLabels in some language
    conc_lang = set([(c, l.language)
                     for c, l in rdf.subject_objects(SKOSEXT.candidateLabel)])
    for conc, lang in conc_lang:
        # check whether there are already prefLabels for this concept in this
        # language
        if lang not in [pl.language
                        for pl in rdf.objects(conc, SKOS.prefLabel)]:
            # no -> let's transform the candidate labels into prefLabels
            to_prop = SKOS.prefLabel
        else:
            # yes -> let's make them altLabels instead
            to_prop = SKOS.altLabel

        # do the actual transform from candidateLabel to prefLabel or altLabel
        for label in rdf.objects(conc, SKOSEXT.candidateLabel):
            if label.language != lang:
                continue
            rdf.remove((conc, SKOSEXT.candidateLabel, label))
            rdf.add((conc, to_prop, label))

    for conc, label in rdf.subject_objects(SKOSEXT.candidateLabel):
        rdf.remove((conc, SKOSEXT.candidateLabel, label))
        if label.language not in [pl.language
                                  for pl in rdf.objects(conc, SKOS.prefLabel)]:
            # no prefLabel found, make this candidateLabel a prefLabel
            rdf.add((conc, SKOS.prefLabel, label))
        else:
            # prefLabel found, make it an altLabel instead
            rdf.add((conc, SKOS.altLabel, label))