Skip to content

Utilities

kgm.utils

path_or_url(s: str) -> Path | str

Converts a string into a Path, preserving http(s)://...

Source code in kgm/utils.py
59
60
61
62
63
64
def path_or_url(s: str) -> Path | str:
    """Converts a string into a Path, preserving http(s)://..."""
    if s.startswith("http") and "://" in str(s):
        return s
    else:
        return Path(s)

get_files_from_artifact(manifest: Path | tuple[Path, Path, Graph], artifact: Node) -> list[Path | str] | Generator[Path]

Returns an iterable (list or generator) of Path objects for files within an artifact literal.

This function will correctly interpret artifacts such as 'file.ttl', '*.ttl', '/trig' etc.

Source code in kgm/utils.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def get_files_from_artifact(
    manifest: Path | tuple[Path, Path, Graph], artifact: Node
) -> list[Path | str] | Generator[Path]:
    """Returns an iterable (list or generator) of Path objects for files within an artifact literal.

    This function will correctly interpret artifacts such as 'file.ttl', '*.ttl', '**/*.trig' etc.
    """
    manifest_path, manifest_root, manifest_graph = get_manifest_paths_and_graph(
        manifest
    )

    if str(artifact).startswith("http") and "://" in str(artifact):
        return [str(artifact)]
    elif isinstance(artifact, Literal):
        if not any(marker in str(artifact) for marker in "*?["):
            return [manifest_root / path_or_url(str(artifact))]
        else:
            pattern = Path(str(artifact))
            root = Path(pattern.anchor) if pattern.is_absolute() else manifest_root
            if pattern.is_absolute():
                pattern = pattern.relative_to(root)
            return (file for file in root.glob(str(pattern)) if file.is_file())
    elif isinstance(artifact, BNode):
        contentLocation = manifest_graph.value(
            subject=artifact, predicate=SDO.contentLocation
        )
        return get_files_from_artifact(
            (manifest_path, manifest_root, manifest_graph), contentLocation
        )
    else:
        raise TypeError(f"Unsupported artifact type: {type(artifact)}")

get_identifier_from_file(file: Path) -> list[URIRef]

Returns a list if RDFLib graph identifier (URIRefs) from a triples or quads file for all KNOWN_ENTITY_CLASSES objects

Source code in kgm/utils.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def get_identifier_from_file(file: Path) -> list[URIRef]:
    """Returns a list if RDFLib graph identifier (URIRefs) from a triples or quads file
    for all KNOWN_ENTITY_CLASSES objects"""
    if file.name.endswith(".ttl"):
        g = load_graph(file)
        for entity_class in KNOWN_ENTITY_CLASSES:
            v = g.value(predicate=RDF.type, object=entity_class)
            if v is not None:
                return [v]
    elif file.name.endswith(".trig"):
        gs = []
        d = load_graph(file)
        for g in d.graphs():
            gs.append(g.identifier)
        return gs
    else:
        return []

get_manifest_paths_and_graph(manifest: Path | tuple[Path, Path, Graph]) -> (Path, Graph)

Reads either a Manifest file from a Path, or a Manifest file from a Path and its root directory, a Path, and the Manifest as a deserialized Graph and returns the Manifest Path, its root dir as a Path and its content as a Graph

Source code in kgm/utils.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def get_manifest_paths_and_graph(
    manifest: Path | tuple[Path, Path, Graph],
) -> (Path, Graph):
    """Reads either a Manifest file from a Path, or a Manifest file from a Path and its root directory,
    a Path, and the Manifest as a deserialized Graph and returns the Manifest Path, its root dir as a Path
    and its content as a Graph"""

    if isinstance(manifest, Path):
        manifest_path = manifest
        manifest_root = Path(manifest).parent.resolve()
        manifest_graph = kgm.validate(manifest)
    else:  # (Path, Path, Graph)
        manifest_path = manifest[0]
        manifest_root = manifest[1]
        manifest_graph = manifest[2]

    return manifest_path, manifest_root, manifest_graph

resource_is_ignored(manifest_graph: Graph, resource: Node) -> bool

Whether a resource descriptor opts all of its artifacts out of processing.

Source code in kgm/utils.py
155
156
157
def resource_is_ignored(manifest_graph: Graph, resource: Node) -> bool:
    """Whether a resource descriptor opts all of its artifacts out of processing."""
    return (resource, PREZ.ignore, Literal(True)) in manifest_graph

get_artifact_main_entity_iri(artifact: Path, manifest: Path | tuple[Path, Path, Graph], artifact_graph: Graph = None, cc: URIRef = None, atype: URIRef = None) -> URIRef

Gets the IRI of the instance of the Main Entity in an artifact where the class of the Main Entity is either one of KNOWN_ENTITY_CLASSES or supplied in the Manifest either as a class to search for - by using schema:additionalType - or by directly indicating the IRI of the main Entity with schema:mainEntity

Source code in kgm/utils.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def get_artifact_main_entity_iri(
    artifact: Path,
    manifest: Path | tuple[Path, Path, Graph],
    artifact_graph: Graph = None,
    cc: URIRef = None,
    atype: URIRef = None,
) -> URIRef:
    """Gets the IRI of the instance of the Main Entity in an artifact where the class of the Main Entity is either
    one of KNOWN_ENTITY_CLASSES or supplied in the Manifest either as a class to search for - by using schema:additionalType
     - or by directly indicating the IRI of the main Entity with schema:mainEntity"""

    # load the manifest
    # get Main Entity directly from Manifest mainEntity indicated
    # load the artifact graph
    # check artifact graph load
    # get Main Entity class using specified atype
    # get Main Entity class via Manifest additionalType indicated
    # get Main Entity class via known profiles' classes
    # get Main Entity classes from KNOWN_ENTITY_CLASSES static list
    # build the query to look for the Main Entity in the artifact
    # check artifact query return
    # query the artifact for the Main Entity
    # check the Main Entity query return
    # return

    known_entity_classes = []

    # load the manifest
    manifest_path, manifest_root, manifest_graph = get_manifest_paths_and_graph(
        manifest
    )

    # get Main Entity directly from Manifest mainEntity indicated
    import os

    artifact_path_abs = absolutise_path(artifact, manifest_root)
    artifact_path_rel = os.path.relpath(artifact, start=os.path.dirname(manifest_path))
    artifact_file = artifact.name
    # artifact_path_rel = Path(str(artifact_path_abs).replace(os.path.commonpath([artifact.parent, manifest_root]), "")) / artifact_file
    q = (
        """
        PREFIX prof: <http://www.w3.org/ns/dx/prof/>
        PREFIX schema: <https://schema.org/>

        SELECT ?iri
        WHERE {
            VALUES ?cl {
                "{artifact_path_abs}"
                "{artifact_path_rel}"
                "{artifact_file}"
            }
            ?resource prof:hasArtifact ?bn .
            ?bn schema:contentLocation ?cl .            
            ?bn schema:mainEntity ?iri .
        }
        """.replace("{artifact_path_abs}", str(artifact_path_abs))
        .replace("{artifact_path_rel}", str(artifact_path_rel))
        .replace("{artifact_file}", str(artifact_file))
    )

    for r in manifest_graph.query(q):
        return URIRef(r["iri"])

    # load the artifact graph
    g = artifact_graph if artifact_graph is not None else load_graph(artifact_path_abs)

    # check artifact graph load
    if not isinstance(g, Graph):
        raise ValueError(
            f"Could not load a graph of the artifact at {artifact_path_abs}"
        )

    # get Main Entity class using specified atype
    if atype is not None:
        known_entity_classes.append(str(atype))

    # get Main Entity class via Manifest additionalType indicated
    if len(known_entity_classes) < 1:
        q = (
            """
            PREFIX prof: <http://www.w3.org/ns/dx/prof/>
            PREFIX schema: <https://schema.org/>

            SELECT DISTINCT ?at
            WHERE {
                VALUES ?art {
                    "{artifact_path_abs}"
                    "{artifact_path_rel}"
                    "{artifact_file}"
                }
                ?resource 
                    prof:hasArtifact ?art ;        
                    schema:additionalType ?at ;
                .
            }
            """.replace("{artifact_path_abs}", str(artifact_path_abs))
            .replace("{artifact_path_rel}", str(artifact_path_rel))
            .replace("{artifact_file}", str(artifact_file))
        )

        for r in manifest_graph.query(q):
            known_entity_classes.append(r["at"])

    # get Main Entity class via known profiles' classes
    if len(known_entity_classes) < 1:
        if cc is not None:
            if cc in KNOWN_PROFILES.keys():
                for m_e_c in KNOWN_PROFILES[cc]["main_entity_classes"]:
                    known_entity_classes.append(str(m_e_c))

    # get Main Entity classes from KNOWN_ENTITY_CLASSES static list
    known_entity_classes = list(
        dict.fromkeys(str(x) for x in [*known_entity_classes, *KNOWN_ENTITY_CLASSES])
    )

    # build the query to look for the Main Entity in the artifact
    known_entity_classes_str = f"<{'>\n                <'.join(known_entity_classes)}>"
    q = f"""
        SELECT DISTINCT ?me
        WHERE {{
            VALUES ?t {{
                {known_entity_classes_str.strip()}
            }}
            ?me a ?t .
        }}
        """
    mes = []

    # query the artifact for the Main Entity
    for r in query(g, q, return_format="python", return_bindings_only=True):
        if r.get("me"):
            mes.append(r["me"])

    # check the Main Entity query return
    if len(mes) != 1:
        if len(mes) > 1:
            raise ValueError(
                f"The artifact at {artifact_path_abs} has more than one Main Entity: {', '.join(mes)} "
                f"based on the class {cc if cc is not None else '(none given)'}. There must only be one."
            )
        else:
            raise ValueError(
                f"The artifact at {artifact_path_abs} has no recognizable Main Entity, "
                f"based on the classes {cc if cc is not None else '(none given)'}. There must be one."
            )

    # return
    return URIRef(mes[0])

print_local_version_indicators(file: Path | str, manifest: Path | str | None = None) -> None

Print the version metadata sync() reads from a local RDF file.

If the file is listed in the manifest, use its metadata before inspecting the RDF. File size is reported for context but is not used in version comparison.

Source code in kgm/utils.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def print_local_version_indicators(
    file: Path | str, manifest: Path | str | None = None
) -> None:
    """Print the version metadata sync() reads from a local RDF file.

    If the file is listed in the manifest, use its metadata before inspecting the RDF.
    File size is reported for context but is not used in version comparison.
    """
    path = Path(file).resolve()
    if not path.is_file():
        raise FileNotFoundError(f"Not a local file: {path}")

    indicators = {}
    manifest_data = (path, path.parent, Graph())
    if manifest is not None:
        manifest_path = Path(manifest).resolve()
        supplied_manifest = (
            manifest_path,
            manifest_path.parent,
            load_graph(manifest_path),
        )
        for artifact, metadata in _get_manifest_artifact_metadata(
            supplied_manifest
        ).items():
            if isinstance(artifact, Path) and artifact.resolve() == path:
                print("Given file found as an artifact in the manifest")
                indicators = metadata
                manifest_data = supplied_manifest
                break

    get_version_indicators_local(manifest_data, path, indicators)

    print(f"File: {file}")
    for key, label in (
        ("main_entity", "Main entity"),
        ("modified_date", "Modified date"),
        ("version_iri", "Version IRI"),
        ("version_info", "Version info"),
    ):
        value = indicators.get(key)
        print(f"{label}: {value if value is not None else '(not set)'}")
    print(f"File size (not compared): {indicators['file_size']} bytes")

compare_version_indicators(first: dict, second: dict) -> VersionIndicatorComparison

Compares Modified Date, Version IRI & Version info for each and returns latest

Source code in kgm/utils.py
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def compare_version_indicators(first: dict, second: dict) -> VersionIndicatorComparison:
    """Compares Modified Date, Version IRI & Version info for each and returns latest"""

    """Even weighted aggregate score for each version indicator"""
    first_score = 0
    second_score = 0
    has_modified_date_comparison = first.get("modified_date") and second.get(
        "modified_date"
    )
    has_version_iri_comparison = first.get("version_iri") and second.get("version_iri")
    has_version_info_comparison = first.get("version_info") and second.get(
        "version_info"
    )

    if (
        not has_modified_date_comparison
        and not has_version_iri_comparison
        and not has_version_info_comparison
    ):
        return VersionIndicatorComparison.CantCalculate

    if has_modified_date_comparison:
        first_date = _modified_date_as_date(first["modified_date"])
        second_date = _modified_date_as_date(second["modified_date"])
        if first_date > second_date:
            first_score += 1
        elif first_date == second_date:
            pass
        else:
            second_score += 1

    if has_version_iri_comparison:
        if str(first["version_iri"]) > str(second["version_iri"]):
            first_score += 1
        elif str(first["version_iri"]) == str(second["version_iri"]):
            pass
        else:
            second_score += 1

    if has_version_info_comparison:
        if str(first["version_info"]) > str(second["version_info"]):
            first_score += 1
        elif str(first["version_info"]) == str(second["version_info"]):
            pass
        else:
            second_score += 1

    # TODO: add test for file_size, Git version etc.

    if first_score > second_score:
        return VersionIndicatorComparison.First
    elif second_score == first_score:
        return VersionIndicatorComparison.Neither
    else:
        return VersionIndicatorComparison.Second

which_is_more_recent(version_indicators: dict, sparql_endpoint: str = None, http_client: httpx2.Client | None = None) -> VersionIndicatorComparison

Tests to see if the given artifact is more recent than a previously stored copy of its content

Source code in kgm/utils.py
638
639
640
641
642
643
644
645
646
647
648
649
def which_is_more_recent(
    version_indicators: dict,
    sparql_endpoint: str = None,
    http_client: httpx2.Client | None = None,
) -> VersionIndicatorComparison:
    """Tests to see if the given artifact is more recent than a previously stored copy of its content"""

    remote = get_version_indicators_sparql(
        version_indicators["main_entity"], sparql_endpoint, http_client
    )

    return compare_version_indicators(version_indicators, remote)

denormalise_artifacts(manifest: Path | tuple[Path, Path, Graph]) -> dict

Extracts all the artifacts from a Manifest.

Returns a dict of:

Artifact path, Main Entity, Conformance Claims Date Modified Version IRI Version Info Role Version Indicators

Source code in kgm/utils.py
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
def denormalise_artifacts(manifest: Path | tuple[Path, Path, Graph]) -> dict:
    """Extracts all the artifacts from a Manifest.

    Returns a dict of:

    Artifact path,
    Main Entity,
    Conformance Claims
    Date Modified
    Version IRI
    Version Info
    Role
    Version Indicators"""
    manifest_data = get_manifest_paths_and_graph(manifest)
    artifacts_info = _get_manifest_artifact_metadata(manifest_data)
    for artifact, metadata in artifacts_info.items():
        if metadata["role"] in [MRR.CatalogueData, MRR.ResourceData]:
            get_version_indicators_local(manifest_data, artifact, metadata)
    return artifacts_info

store_remote_artifact_locally(manifest: Path | tuple[Path, Path, Graph], sparql_endpoint: str, graph_id: str, http_client: httpx2.Client | None = None) -> Graph

Writes a remote graph to a local file and registers that file as a Resource in the given Manifest.

Only the Resource Role ResourceData is supported.

Source code in kgm/utils.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
def store_remote_artifact_locally(
    manifest: Path | tuple[Path, Path, Graph],
    sparql_endpoint: str,
    graph_id: str,
    http_client: httpx2.Client | None = None,
) -> Graph:
    """Writes a remote graph to a local file and registers that file as a Resource in the given Manifest.

    Only the Resource Role ResourceData is supported."""
    manifest_path, manifest_root, manifest_graph = get_manifest_paths_and_graph(
        manifest
    )
    q = """
        CONSTRUCT {
            ?s ?p ?o
        }
        WHERE {
            GRAPH <xxx> {
                ?s ?p ?o
            }
        }
        """.replace("xxx", graph_id)
    r = query(sparql_endpoint, q, http_client=http_client, return_format="python")
    artifact_path = str(artifact_file_name_from_graph_id(graph_id))
    r.serialize(destination=manifest_root / artifact_path, format="longturtle")

    new_manifest_graph = Graph()
    new_manifest_graph += manifest_graph

    for m in new_manifest_graph.subjects(RDF.type, PREZ.Manifest):
        new_r = BNode()
        for r in new_manifest_graph.objects(m, PROF.hasResource):
            if (r, PROF.hasRole, MRR.ResourceData) in new_manifest_graph:
                new_r = r

        a = BNode()
        new_manifest_graph.add(
            (
                a,
                SDO.contentLocation,
                Literal(artifact_path),  # relative to manifest_root
            )
        )
        new_manifest_graph.add((a, SDO.mainEntity, URIRef(graph_id)))
        new_manifest_graph.add((new_r, PROF.hasArtifact, a))
        new_manifest_graph.add(
            (new_r, PROF.hasRole, MRR.ResourceData)  # only one supported for now
        )
        new_manifest_graph.add((m, PROF.hasResource, new_r))

    return new_manifest_graph

get_background_graph(manifest: Path | tuple[Path, Path, Graph]) -> Graph

Returns the contents of all Manifest resources with role *CatalogueAndResourceLabels as a graph

Source code in kgm/utils.py
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
def get_background_graph(manifest: Path | tuple[Path, Path, Graph]) -> Graph:
    """Returns the contents of all Manifest resources with role *CatalogueAndResourceLabels as a graph"""
    background_graph = Graph()

    # can't use get_manifest_paths_and_graph here as it uses validate
    manifest_path = manifest
    manifest_root = Path(manifest).parent.resolve()
    manifest_graph = load_graph(manifest)

    for resource in manifest_graph.objects(None, PROF.hasResource):
        if resource_is_ignored(manifest_graph, resource):
            continue
        for role in manifest_graph.objects(resource, PROF.hasRole):
            # The data files & background - must be processed after Catalogue
            if role in [
                MRR.CompleteCatalogueAndResourceLabels,
                MRR.IncompleteCatalogueAndResourceLabels,
            ]:
                for artifact in manifest_graph.objects(resource, PROF.hasArtifact):
                    for file in get_files_from_artifact(
                        (manifest_path, manifest_root, manifest_graph), artifact
                    ):
                        if not file.is_file():
                            raise ValueError(
                                f"The artifact {file} in Manifest {manifest} is not a file"
                            )

                        if str(file.name).endswith(".ttl"):
                            background_graph += load_graph(file)

    return background_graph