Coverage for rdflib_ocdm/support.py: 96%
34 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-11-01 22:02 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-11-01 22:02 +0000
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3# Copyright 2023 Arcangelo Massari <arcangelo.massari@unibo.it>
4#
5# Permission to use, copy, modify, and/or distribute this software for any purpose
6# with or without fee is hereby granted, provided that the above copyright notice
7# and this permission notice appear in all copies.
8#
9# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
11# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
12# OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
13# DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
14# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
15# SOFTWARE.
17from __future__ import annotations
19import re
20from typing import Match
22from rdflib import RDF, XSD, Dataset, Graph, Literal, URIRef
24prov_regex: str = r"^(.+)/prov/([a-z][a-z])/([1-9][0-9]*)$"
26def _get_match(regex: str, group: int, string: str) -> str:
27 match: Match = re.match(regex, string)
28 if match is not None:
29 return match.group(group)
30 else:
31 return ""
33def is_string_empty(string: str) -> bool:
34 return string is None or string.strip() == ""
36def get_prov_count(res: URIRef) -> str:
37 string_iri: str = str(res)
38 if "/prov/" in string_iri:
39 return _get_match(prov_regex, 3, string_iri)
41def get_entity_subgraph(graph: Graph, entity: URIRef) -> Graph:
42 subj_graph: Dataset|Graph = Dataset() if isinstance(graph, Dataset) else Graph()
43 if isinstance(graph, Dataset):
44 for quad in graph.quads((entity, None, None, None)):
45 subj_graph.add(quad)
46 elif isinstance(graph, Graph): 46 ↛ 49line 46 didn't jump to line 49 because the condition on line 46 was always true
47 for triple in graph.triples((entity, None, None)):
48 subj_graph.add(triple)
49 return subj_graph
51def create_literal(g: Graph, res: URIRef, p: URIRef, s: str, dt: URIRef = None, nor: bool = True) -> None:
52 if not is_string_empty(s):
53 datatype = dt if dt is not None else XSD.string
54 g.add((res, p, Literal(s, datatype=datatype, normalize=nor)))
56def create_type(g: Dataset|Graph, res: URIRef, res_type: URIRef, identifier: str = None) -> None:
57 if isinstance(g, Dataset):
58 g.add((res, RDF.type, res_type, identifier))
59 elif isinstance(g, Graph): 59 ↛ exitline 59 didn't return from function 'create_type' because the condition on line 59 was always true
60 g.add((res, RDF.type, res_type))