orinoco-snippets/recognize-orcid.py

89 lines
2.9 KiB
Python

import re
import curies
from rdflib import SKOS, Graph
def pid_of(x: str | dict) -> str:
return x.get("pid", "") if isinstance(x, dict) else x
def is_orcid(
record: dict,
converter: curies.Converter,
schema: Graph | None = None,
use_regex: bool = False,
):
orcid_org_curies = {
"ror:04fa4r544",
"grid:grid.455335.1",
"isni:0000000446638501",
"wikidata:Q19861084",
}
orcid_id_curie = "iao:0000708"
# based on creator pid
if (creator := record.get("creator")) is not None:
creator_curie = converter.compress_or_standardize(pid_of(creator))
if creator_curie in orcid_org_curies:
return True
# based on creator exact mappings (if inlined)
if isinstance(creator, dict):
for xm in creator.get("exact_mappings", []):
creator_curie = converter.compress_or_standardize(xm)
if creator_curie in orcid_org_curies:
return True
# based on schema type & knowing the schema
if (schema_type := record.get("schema_type")) is not None:
if converter.compress_or_standardize(schema_type) == orcid_id_curie:
return True
if schema is not None:
exact_matches = schema.objects(
subject=schema.namespace_manager.expand_curie(schema_type),
predicate=SKOS.exactMatch,
)
for m in exact_matches:
if converter.compress_or_standardize(str(m)) == orcid_id_curie:
return True
# based on regex (optional)
if (notation := record.get("notation")) is not None and use_regex:
pat = "0000-000(1-[5-9]|2-[0-9]|3-[0-4])[0-9]{3}-[0-9]{3}[0-9X]"
return re.match(pat, notation) is not None
return False
if __name__ == "__main__":
# load bioregistry curie converter
# having bioregistry package installed (not imported) avoids GitHub (re)download
converter = curies.get_bioregistry_converter()
# load schema (defines xyzri:ORCID)
g = Graph()
g.parse("https://concepts.datalad.org/s/demo-research-information/unreleased.owl.ttl")
for identifier in [
{"creator": "ror:04fa4r544", "notation": "...", "schema_type": "..."},
{"creator": "wikidata:Q19861084", "notation": "...", "schema_type": "..."},
{"creator": "example:orcid", "notation": "...", "schema_type": "xyzri:ORCID"}, # defined in schema
]:
assert is_orcid(identifier, converter, g)
assert is_orcid(
{"creator": "example:orcid", "notation": "0000-0002-2771-9344", "schema_type": "example:foo"},
converter,
schema = None,
use_regex=True,
)
for identifier in [
{"creator": "https://example.com/foo", "notation": "...", "schema_type": "xyzri:DOI"},
{"creator": "example:orcid", "notation": "foo"},
{"notation": "foo"},
{},
]:
assert not is_orcid(identifier, converter, g, use_regex=True)