Skip to content

About

No description, website, or topics provided.

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

RDF Toolkit

Development Status Documentation Ask DeepWiki Python 3.12+ Package Status CI Code style: Ruff pre-commit License: MIT Contributor Covenant

Overview

This toolkit provides type-safe Pydantic models for standard vocabularies and enables round-trip serialization to and from RDF formats.

Installation

PyPI Release

Once stable, this package will be officially released and distributed through PyPI. Stay tuned for updates!

Local Installation

In the meantime, you can install the package locally by following these steps:

  1. Clone the Repository:

    First, clone the repository to your local machine:

    git clone https://github.com/DataArtifex/rdf-toolkit.git
    cd rdf-toolkit
  2. Install the Package:

    From the project's home directory, run the following command to install the package:

    uv pip install -e .

Using as a Dependency

If you want to use this package as a dependency in another project (via requirements.txt or pyproject.toml) without waiting for the PyPI release, you can use the following methods:

Using uv (Recommended)

uv handles git dependencies and lock files securely and is the preferred tool for this project:

uv add git+https://github.com/DataArtifex/rdf-toolkit.git

Using pip with Hash Verification (e.g. for Docker)

If you are using pip install --require-hashes (common in Docker environments), pip cannot verify hashes for Git repositories. You must use the GitHub archive URL instead:

dartfx-rdf @ https://github.com/DataArtifex/rdf-toolkit/archive/MAIN_OR_COMMIT.tar.gz#sha256=HASH

Example for a specific commit:

dartfx-rdf @ https://github.com/DataArtifex/rdf-toolkit/archive/8e6d67ae093eb9321a5d8865d04d833de62ec95c.tar.gz#sha256=445e186c5b158ceb42d1406a762c8c9b728648c76fa047209ac391d24dd34b38

How to find the commit URL and Hash

  1. Find the Commit Hash: On the GitHub repository page, click on "Commits" or look at the short hash near the code. Copy the full 40-character SHA.
  2. Form the Archive URL: Use the format https://github.com/DataArtifex/rdf-toolkit/archive/COMMIT_SHA.tar.gz.
  3. Calculate the SHA256: If you need the hash for verification, run:
    curl -L https://github.com/DataArtifex/rdf-toolkit/archive/COMMIT_SHA.tar.gz -o temp.tar.gz
    sha256sum temp.tar.gz

Usage

Serialising Pydantic models to RDF

The toolkit ships with a lightweight integration that lets you decorate Pydantic models with RDF metadata and convert them directly to and from rdflib graphs. The integration is provided by the dartfx.rdf.pydantic module.

from typing import Annotated

from rdflib import Namespace, URIRef

from dartfx.rdf.pydantic import RdfBaseModel, RdfProperty

EX = Namespace("https://example.com/ns/")


class Project(RdfBaseModel):
    rdf_type = EX.Project
    rdf_namespace = EX
    rdf_prefixes = {"ex": EX}

    id: str
    name: Annotated[str, RdfProperty(EX.name)]
    homepage: Annotated[str, RdfProperty(EX.homepage)]


project = Project(id="rdftoolkit", name="RDF Toolkit", homepage="https://example.com/toolkit")

turtle = project.to_rdf(format="turtle")
print(turtle)

The RdfProperty metadata describes which predicate should be used for each field. When rdf_namespace is supplied the toolkit automatically builds URIs for identifiers that are not already absolute. The resulting RDF graph is a standard rdflib.Graph instance, so you can serialise it to any format that rdflib supports by switching the format argument.

Deserialising RDF into models

The same annotations are used to parse RDF back into Pydantic models. When a model specifies rdf_type the deserialiser will look for a matching subject and populate the fields from the graph.

loaded = Project.from_rdf(turtle, format="turtle")
assert loaded == project

Nested models and multi-valued properties are also supported. Declare lists of annotated fields, or embed other RdfBaseModel subclasses, and the toolkit will recursively serialise and deserialise them.

Working with URIs and Datatypes

The toolkit provides several ways to handle URIs and specific XSD datatypes:

  • Resource Identifiers: Use rdflib.URIRef as a type hint for fields that should be serialized as RDF resources.
  • XSD Datatypes: Specify the datatype in RdfProperty to force a literal value to a specific XSD type (e.g., XSD.anyURI, XSD.integer).
  • Localized Strings: Use LocalizedStr for automatic handling of language tags. Input can be a plain string, a LangString, a dictionary language map, or a mixed list — the value is always stored as a LangStringList with convenience query methods (has_language, get_by_language, count_by_lang, languages, etc.) and built-in (value, lang) deduplication.
  • Validation: Combine with Pydantic's built-in types like AnyUrl for strict input validation.
  • Multiple RDF Types: Specify multiple RDF types as a list or set in rdf_type (e.g., rdf_type = [SCHEMA.PropertyValue, CDI.InstanceVariable]). Unmodeled incoming types from graphs are automatically preserved on round-trip.
from typing import Annotated, Optional
from pydantic import AnyUrl
from rdflib import XSD, SCHEMA, SKOS, URIRef
from dartfx.rdf.pydantic import RdfBaseModel, RdfProperty, LocalizedStr, LangString

class WebResource(RdfBaseModel):
    # Serialized as an RDF resource (URIRef)
    see_also: Annotated[Optional[URIRef], RdfProperty(SCHEMA.seeAlso)] = None

    # Validated by Pydantic, serialized as "..."^^xsd:anyURI literal
    url: Annotated[AnyUrl, RdfProperty(SCHEMA.url, datatype=XSD.anyURI)]

class Concept(RdfBaseModel):
    rdf_type = SKOS.Concept
    rdf_namespace = EX

    id: str
    pref_label: Annotated[LocalizedStr | None, RdfProperty(SKOS.prefLabel)] = None

c = Concept(id="c1", pref_label={"en": "World", "es": "Mundo"})
c.pref_label.has_language("en")       # True
c.pref_label.get_by_language("es")    # LangStringList([LangString("Mundo","es")])
c.pref_label += LangString("Welt", "de")  # add with dedup
str(c.pref_label)                     # str-like when one untagged entry exists

See the Pydantic RDF integration guide for a deeper walk-through including the full LangStringList API, language-tagged strings, custom datatypes and subject selection.

Supported Vocabularies

The toolkit provides Pydantic models for the following vocabularies:

  • DCTERMS: Dublin Core Metadata Initiative Terms
  • FOAF: Friend of a Friend
  • ODRL: Open Digital Rights Language
  • PROV: PROV Ontology
  • SKOS: Simple Knowledge Organization System (including SKOS-XL)
  • SPDX: Software Package Data Exchange
  • VCARD: vCard / Virtual Contact File
  • XKOS: Extended Knowledge Organization System

Testing

# Run all tests
uv run pytest tests/ -v

# Run only vocabulary tests
uv run pytest tests/test_vocabularies_*.py -v

# Run benchmarks only
uv run pytest tests/test_benchmarks_serialization.py --benchmark-only

Roadmap

  • Migrate model from Python @dataclass to Pydantic
  • Explore transitioning into RDF annotation and serializer from DCAT SeMPyRO project
  • RDF deserializer (from graph to Python)
  • Peer testing and validation
  • Expand vocabulary coverage
  • Improve documentation

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

About

No description, website, or topics provided.

Resources

Code of conduct

Stars

0 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages