knowledge-enrichment/things_enrichment_tools/__init__.py

322 lines
10 KiB
Python

"""Utilities for updating and enriching Things records.
Three main helpers are provided (plus some auxiliary functions):
- :func:`update_data_property`
- :func:`update_object_property`
- :func:`update_multivalued_object_property`
The all take the to-be-modified record as the first argument. Importantly,
this record need not be a full Thing record. It can also be an object (dict)
that is part of a full record (e.g., an inlined association class instance),
as long as it supports the ``ThingMixin`` interface or is a ``Statement``.
Moreover, they all accept the same arguments for specifying information source
and ownership:
- ``owner_id`` is a string that is writing to an annotation indicating
information ownership of an update
- ``source_id`` is an arbitrary string identifying the nature and/or
version of the information source used for an update
- ``valid_owner_ids`` is a list of ``owner_id`` values to be considered
"ours"
All update functions honor ownership. An update labeled with an owner different
from an existing information item never modifies such existing information.
In order to migrate information ownership ``valid_owner_ids`` has to be used,
and must include any ``owner_id`` to be migrated.
Note that record updates are only made when a record needs to change. A sole
change of information ownership is not considered relevant for an update.
Moreover, In the case of multivalued slots, the order of any existing items is
preserved as much as possible, in order to minimize record difference and aid
(human) curation.
Any record update is done in-place, the function's return value indicates
whether an update was made (``True``) or not (``False``).
"""
from typing import Any
owner_tag = 'pav:importedBy'
owner_tag_expanded = 'http://purl.org/pav/importedBy'
source_tag = 'pav:importedFrom'
def is_subset_dict(small, big):
"""Test whether a big dict contains all key-value pairs of a small dict"""
return all(k in big and big[k] == v for k, v in small.items())
def properties_match(
# object or list of objects (e.g. 'identifiers')
data: dict[str, Any] | list[dict[str, Any]],
# whatever number of key/value pairs that must be present in the data
match: dict[str, Any],
) -> bool:
"""Determine whether a set of property values (simultaneously) exists
Use cases are finding particular predicate/value combinations in an
attribute list, or predicate/object combinations in a statement list,
or slot/value combinations in a record.
"""
if not isinstance(data, list):
data = [data]
return any(is_subset_dict(match, d) for d in data)
def write_mapping(
data: dict[str, Any] | list[dict[str, Any]],
mapping: dict[str, Any],
) -> None:
"""Helper to update a dict or append to a list depending on the type"""
if isinstance(data, list):
data.append(mapping)
else:
data.update(mapping)
def append_object(
recs: list[dict[str, Any]],
obj: dict[str, Any],
*,
owner_id: str | None = None,
source_id: str | None = None,
) -> tuple[list[dict[str, Any]], bool]:
"""Append an object to a list when its information is not already present"""
if properties_match(recs, obj):
# we already have this information in the record
return recs, False
update_with_ownership(obj, owner_id, source_id)
write_mapping(recs, obj)
return recs, True
def update_with_ownership(
rec: dict[str, Any],
owner_id: str | None = None,
source_id: str | None = None,
) -> None:
"""Write ownership/source information in standard format"""
annotations = rec.get('annotations', {})
if owner_id:
annotations[owner_tag] = owner_id
if source_id:
annotations[source_tag] = source_id
if annotations:
rec.update(annotations=annotations)
def matches_owner(
d: dict[str, Any],
valid_owner_ids: list[str | None],
) -> bool:
"""Check if a record's owner matches any in a list of candidated"""
# TODO: annotations could be "expanded": list of dicts with
# annotation_tag/value keys
annot = d.get('annotations', {})
return (annot.get(owner_tag) or annot.get(owner_tag_expanded)) in valid_owner_ids
# TODO: add deletion? difficult, because slot ownership is hard to verify
# TODO: split out multivalued variant?
def update_data_property(
rec: dict[str, Any],
*,
predicate: str,
value: Any,
collection_slot: str = 'attributes',
value_key: str = 'value',
topical_slot: str | None = None,
owner_id: str | None = None,
source_id: str | None = None,
predicate_key: str = 'predicate',
valid_owner_ids: list[str | None] | None = None,
) -> bool:
"""Update a single-valued or multi-valued data property
A data property is a property with a non-class range, i.e.
one that takes literals, including URIs.
By default, data property values are modeled as ``AttributeSpecification``
and are places into the ``attributes`` slot. However, it is also possible
to store values as ``Statement`` instances (with ``collection_slot`` set
to ``characterized_by``, ``value_key`` set to ``object``). Other target
classes can be achieved by also modifying ``predicate_key``.
A data property is defined by a ``predicate`` and a ``value``. Scalar and
multi-valued values are supported. When ``value`` is a list, one attribute
specification per item in the list will be generated.
When ``topical_slot`` is given, and if a corresponding slot does not
already exist in the record, ``value`` is also assigned to this slot.
When no objects are left in the ``collection_slot`` at the end and the
target ``collection_slot`` exists in the record, it will be deleted.
The function returns a boolean flag indicating whether a record update
was made.
"""
modified = False
if topical_slot is not None and topical_slot not in rec:
rec[topical_slot] = value
modified = True
# an attribute specification can only take a scalar value
# so we will split any multivalued valued up
values = value if isinstance(value, list) else [value]
# if no explicit valid owners are given, go with any id that this function
# would write
if valid_owner_ids is None:
valid_owner_ids = [owner_id]
statements = rec.get(collection_slot, [])
# remove all relevant statement matching any stated
# owner with any value NOT matching the given one(s)
statements_minus_deletions = [
s
for s in statements
if not (
s.get(predicate_key) == predicate
and matches_owner(s, valid_owner_ids)
and s.get(value_key, []) not in values
)
]
if len(statements) > len(statements_minus_deletions):
modified = True
statements = statements_minus_deletions
for v in values:
info = {predicate_key: predicate, value_key: v}
statements, obj_appended = append_object(
statements,
info,
owner_id=owner_id,
source_id=source_id,
)
if obj_appended:
modified = True
if statements:
rec[collection_slot] = statements
elif collection_slot in rec:
del rec[collection_slot]
return modified
def update_object_property(
rec: dict[str, Any],
*,
slot: str,
value: dict[str, Any] | None,
owner_id: str | None = None,
source_id: str | None = None,
valid_owner_ids: list[str | None] | None = None,
) -> bool:
"""Update a (single-valued) object property.
This is a special-case, because there can only be a single (object) value.
This implies that conflicting information from other sources/owners cannot
be expressed in the record at all.
When ownership of any existing value and the update does not match, no
update is applied. Otherwise, ``value`` is assigned to the target ``slot``
in the record.
When ``None`` is given as a value and the target ``slot`` exists in the record,
it will be deleted.
When the given ``value`` is a strict subset of the key-value pairs in the
existing record slot, no update is made.
The function returns a boolean flag indicating whether a record update
was made.
"""
# if no explicit valid owners are given, go with any id that this function
# would write
if valid_owner_ids is None:
valid_owner_ids = [owner_id]
if slot in rec and not matches_owner(rec[slot], valid_owner_ids):
# we must not touch this
return False
if slot in rec and value is None:
del rec[slot]
return True
if value is None:
return False
if slot in rec and is_subset_dict(value, rec[slot]):
# the info is already in, even if potentially from another owner
return False
update_with_ownership(value, owner_id, source_id)
rec[slot] = value
return True
def update_multivalued_object_property(
rec: dict[str, Any],
*,
slot: str,
values: list[dict[str, Any]] | None,
owner_id: str | None = None,
source_id: str | None = None,
valid_owner_ids: list[str | None] | None = None,
) -> bool:
"""Update a multi-valued object property.
This function behaves like :func:`update_object_property` and takes the
same arguments, except that it operates on multivalued slots and
accepts multiple ``values``.
Within the set of values considered for the given owner(s), any values
not part of the update are removed, any previously non-existing values
are appended. When no more values (objects) are present after an update
a present ``slot`` is removed from the record.
"""
modified = False
# if no explicit valid owners are given, go with any id that this function
# would write
if valid_owner_ids is None:
valid_owner_ids = [owner_id]
objs = rec.get(slot, [])
# remove all relevant obj matching any stated
# owner with any information NOT matching
# the given now ones
objs_minus_deletions = [
o
for o in objs
if not (
matches_owner(o, valid_owner_ids)
and not any(is_subset_dict(v, o) for v in (values or []))
)
]
if len(objs) > len(objs_minus_deletions):
modified = True
objs = objs_minus_deletions
for v in values or []:
objs, m = append_object(objs, v, owner_id=owner_id, source_id=source_id)
if m:
modified = True
if objs:
rec[slot] = objs
elif slot in rec:
del rec[slot]
return modified