47 lines
1.3 KiB
Python
47 lines
1.3 KiB
Python
|
|
import hashlib
|
||
|
|
|
||
|
|
from rdflib import Graph
|
||
|
|
from rdflib.namespace import NamespaceManager
|
||
|
|
|
||
|
|
|
||
|
|
def iri2namespace(iri: str, ontology: bool = False) -> str:
|
||
|
|
"""Convert an IRI to a namespace string.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
iri: The IRI to convert.
|
||
|
|
ontology: If True, append '#' for ontology namespace, otherwise '/'.
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
str: The converted namespace string.
|
||
|
|
"""
|
||
|
|
iri = iri.rstrip("#")
|
||
|
|
return f"{iri}#" if ontology else f"{iri}/"
|
||
|
|
|
||
|
|
|
||
|
|
def get_rdflib_namespace_mappings() -> dict:
|
||
|
|
g = Graph()
|
||
|
|
ns_manager = NamespaceManager(g)
|
||
|
|
return {str(uri): prefix for prefix, uri in ns_manager.namespaces()}
|
||
|
|
|
||
|
|
|
||
|
|
CONVENTIONAL_MAPPINGS = get_rdflib_namespace_mappings()
|
||
|
|
|
||
|
|
|
||
|
|
def render_text_hash(text: str, digits: int | None = 12) -> str:
|
||
|
|
"""Generate a SHA-256 hash for the given text.
|
||
|
|
|
||
|
|
This is the single hashing entry point for the entire codebase.
|
||
|
|
All modules that need to derive a hash from text should use this function
|
||
|
|
instead of calling ``hashlib`` directly.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
text: The text to hash.
|
||
|
|
digits: Number of hex digits to return (default: 12).
|
||
|
|
Pass ``None`` to return the full 64-character hex digest.
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
A hex string hash of the text.
|
||
|
|
"""
|
||
|
|
digest = hashlib.sha256(text.encode()).hexdigest()
|
||
|
|
return digest[:digits] if digits is not None else digest
|