Metadata-Version: 2.5
Name: euler-dataset-contract
Version: 0.26.2
Summary: Versioned dataset-head contracts and extension validation for the Euler ecosystem
Project-URL: Homepage, https://github.com/d-rothen/euler-dataset-contract
Project-URL: Repository, https://github.com/d-rothen/euler-dataset-contract
Project-URL: Issues, https://github.com/d-rothen/euler-dataset-contract/issues
Project-URL: Documentation, https://github.com/d-rothen/euler-dataset-contract#readme
Project-URL: Changelog, https://github.com/d-rothen/euler-dataset-contract/blob/main/CHANGELOG.md
Author-email: Daniel Rothenpieler <rothenpielerdaniel@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: computer-vision,dataset,machine-learning,metadata,schema,validation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.9
Provides-Extra: dev
Requires-Dist: jsonschema>=4.18; extra == 'dev'
Requires-Dist: pytest>=7.4; extra == 'dev'
Requires-Dist: ruff>=0.12; extra == 'dev'
Provides-Extra: testing
Requires-Dist: pytest>=7.4; extra == 'testing'
Description-Content-Type: text/markdown

<!-- euler header — shared across the euler packages.
     Per package, change only: the <h1>, the tagline, and the badge URLs. -->
<p align="center">
  <img src="https://files.chronodle.com/icons/euler.svg" alt="euler" width="96" height="96">
</p>

<h1 align="center">euler-dataset-contract</h1>

<p align="center">
  <em>One small, versioned metadata boundary for Euler datasets.</em>
</p>

<p align="center">
  <a href="https://pypi.org/project/euler-dataset-contract/"><img alt="PyPI" src="https://img.shields.io/pypi/v/euler-dataset-contract.svg"></a>
  <a href="https://pypi.org/project/euler-dataset-contract/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/euler-dataset-contract.svg"></a>
  <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-blue.svg"></a>
  <a href="https://github.com/d-rothen/euler-dataset-contract/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/d-rothen/euler-dataset-contract/actions/workflows/ci.yml/badge.svg"></a>
</p>

---

`euler-dataset-contract` defines and validates the shared `dataset-head.json`
format used across the Euler data tooling. It keeps dataset identity, modality
semantics, and package-specific extensions in one dependency-free Python
package instead of duplicating those rules in every producer and consumer.

```mermaid
flowchart LR
    C["ds-crawler<br/><i>produces and persists</i>"] --> H["dataset-head.json<br/><b>euler-dataset-contract</b>"]
    H --> L["euler-loading<br/><i>selects loaders and exposes metadata</i>"]
    L --> E["euler-eval<br/><i>consumes loaded values</i>"]
    H --> X["other consumers<br/><i>register their addon validators</i>"]
```

The package intentionally does not crawl files, load arrays, or import NumPy or
PyTorch. Its core install has no runtime dependencies.

## Install

Phase 1 adds opt-in modality lookups, representation/source/calibration models,
planned resize/crop descriptors, generated addon schemas, and canonical hashes.
See [the wire format, public APIs, and compatibility rules](docs/phase1.md).
Core Contract 1.0 still requires `modality.key`; the package has no runtime
dependencies. Loading's paired implementation requires these source changes.

```bash
pip install euler-dataset-contract
```

Python 3.9 or newer is required.

## Quick start

A dataset head describes one logical dataset modality:

```python
from euler_dataset_contract import parse_dataset_head

head = {
    "contract": {"kind": "dataset_head", "version": "1.0"},
    "dataset": {
        "id": "foggy_depth",
        "name": "Foggy Drive Depth",
        "attributes": {"split_origin": "capture_2026"},
    },
    "modality": {
        "key": "depth",
        "meta": {
            "radial_depth": False,
            "scale_to_meters": 0.001,
            "range": [0, 80],
            "file_types": ["png"],
        },
    },
    "addons": {
        "euler_loading": {
            "version": "1.0",
            "loader": "generic_dense_depth",
            "function": "depth",
        }
    },
}

contract = parse_dataset_head(head)
contract.dataset_id                    # "foggy_depth"
contract.modality_key                  # "depth"
contract.meta["scale_to_meters"]       # 0.001
contract.get_addon("euler_loading")    # package-owned extension payload
contract.to_mapping()                  # canonical, detached mapping
```

Invalid structural fields, missing modality metadata, malformed versions, and
registered addon violations raise `ValueError` with a field-qualified message.
Unknown modality keys remain valid and may carry arbitrary metadata, allowing
the ecosystem to add modalities without first releasing this package.

## Extending the suite without a pull request

Every extensible Euler package reads its extensions through one protocol,
`euler_dataset_contract.extensions`: installed **entry points** in groups
named `euler.<kind>`. Your own package joins the suite by declaring them:

```toml
# your lab's pyproject.toml: the entire integration
[project.entry-points."euler.modalities"]
my_lab = "my_lab.euler:MODALITIES"
```

```python
# my_lab/euler.py
MODALITIES = {
    "api_version": "1.0",
    "modalities": {
        "appearance.camera.thermal_intensity": {
            "description": "Long-wave infrared intensity per pixel.",
            "aliases": ["thermal"],
            "semantics": {"value_kind": "scalar_field", "components": 1},
        }
    },
}
```

After `pip install my-lab`, every process resolves `thermal`
(`resolve_modality("thermal").modality_id == "appearance.camera.thermal_intensity"`):
CLIs, DataLoader workers and SLURM jobs alike, because extensions come from
the installed environment, not from process state. `EULER_MODALITY_PATH`
(JSON files, `os.pathsep`-separated) does the same without packaging.

| Group | Read by | What a value is |
|---|---|---|
| `euler.capabilities` | `euler-suite report` | a callable returning the package's versioned capability report |
| `euler.modalities` | this package | modality definitions merged into `inventory()` |
| `euler.loaders` | euler-loading | loader modules dataset heads can name |
| `euler.vocabularies` | euler-metric-naming | metric vocabularies |
| `euler.metric_sets` | euler-eval | domain metric sets |
| `euler.transforms` | euler-preprocess | preprocessing transforms |
| `euler.recipes` | euler-known-datasets | dataset preparation recipes |

The rules hold for every group: deterministic order; two packages claiming
the same name is a *conflict* (neither loads, the conflict is reported, no
silent first-import-wins); a broken extension never breaks the rest of the
suite but its error is kept and reported; every value carries the
distribution and version that provided it. `EULER_EXTENSIONS_STRICT=1` turns
problems into errors. Modality definitions are validated against the
built-in inventory and rejected whole, with a reason, when they break a rule
(see `euler_dataset_contract.modality_extensions`).

## Checking an environment: `euler-suite doctor`

```console
$ euler-suite doctor
Euler suite in /cluster/envs/depth (Python 3.11.2)

Installed packages:
  euler-dataset-contract  0.23.0
  euler-eval              3.3.0
  euler-loading           2.15.0
  my-lab-thermal          0.1.0

Extensions:
  euler.modalities: my_lab_thermal (my-lab-thermal)

Findings:
  [error] euler-eval 3.3.0 needs euler-loading>=2.36, but euler-loading 2.15.0 is installed. ...
      fix: pip install -U "euler-loading>=2.36"

Not healthy: fix the errors above first.
```

`euler-suite report` (or `python -m euler_dataset_contract suite`) prints the
same as one JSON document (`euler_suite_report` 1.0): installed suite
packages and their requirements on each other, installed extensions, every
package's capability report (`euler.capabilities`), and the findings.
euler-view runs it per cluster environment. `euler-suite extensions` lists the
extension points and what is installed for each.

## Start a new model project: `euler-suite init`

```console
$ euler-suite init my-depth-model --task depth
```

writes a project in which **you only write the model**. You edit one file,
`model.py` (`Model(config)`, `forward(batch)`, `loss(predictions, batch)`,
starting as a tiny working baseline), and point `experiment.toml` at your data;
every other file works unchanged:

```text
my-depth-model/
├── launch/                 euler-view launch configs
│   ├── train/              run.sh, euler-view.json
│   ├── infer/              run.sh, pipeline.json, euler-view.json
│   ├── evaluate/           run.sh, euler-view.json
│   └── README.md
├── model.py                the model: the one file you edit
├── experiment.toml         data per modality and split, [model], [train], [eval] task, output root
├── train.py                euler-loading datasets and batches, a standard loop (AMP optional, CPU
│                           fallback), validation every epoch with euler-eval's metric code of the
│                           [eval] task, run and checkpoints logged with euler-train
├── infer.py                euler_inference.infer(): a predictions dataset with pipeline_outputs.json,
│                           each target in its key's default storage format
├── inference_model.py      the adapter to euler-inference's Model(config, device).predict(inputs)
├── evaluate.py             fills eval.json and runs euler_eval.evaluate(); results in the predictions' .eval/
├── eval.json               the euler-eval config of the [eval] task
├── euler_project.py        the plumbing the scripts share (experiment.toml, datasets, validation set)
├── pyproject.toml          euler-train>=2.17, euler-loading>=2.49, euler-inference>=2.17, euler-eval>=3.5, torch
├── README.md               for newcomers: what each file does, `euler-suite doctor` first
└── .gitignore
```

Then:

```console
$ cd my-depth-model
$ euler-suite doctor            # is this environment's suite consistent?
$ $EDITOR experiment.toml       # dataset paths, e.g. "/data/vkitti2.zip:train#scope=rgb"
$ python train.py               # outputs/runs/<id>/: meta.json (euler_train_run 1.0), metrics, checkpoints
$ python infer.py               # outputs/predictions/<run>_<ckpt>/: pipeline_outputs.json 1.1
$ python evaluate.py            # euler-eval results in each prediction dataset's .eval/
```

`--task` chooses the starting point: `depth` (rgb in, metric depth out, scored
with euler-eval's `depth.dense`), `rgb` (a degraded image in, the clear image
out, `rgb.restoration`) or `generic` (any inputs to any targets, named in
`experiment.toml`). Data is declared by modality name, contract key and
euler-loading path per split; the evaluation by euler-eval task id. Any value
of `experiment.toml` can be overridden for one run (`python train.py --set
train.epochs=2`), which is how the `launch/` scripts pass the datasets and the
checkpoint euler-view resolves. Inside an euler-view launch, euler-train and
euler-inference record the launch and experiment (`EULER_LAUNCH_ID`,
`EULER_EXPERIMENT_ID`) by themselves, so runs and predictions join their
experiment without arguments.

`euler-suite init` refuses a non-empty directory unless `--force` is given
(it then replaces the files it writes and keeps the others). The templates are
package data (`euler_dataset_contract/data/scaffold`, listed in its
`manifest.json`), so the package still has no dependencies; the generated
project depends on the suite packages and torch.

## Storage formats and valid pixels

Two facts about every modality key live in the modality inventory, next to
the key's meaning, instead of in each package:

```python
from euler_dataset_contract import storage_format, storage_formats, valid_mask

storage_format("depth")
# {'key': 'depth', 'modality_id': 'geometry.camera.depth', 'file_type': 'npy',
#  'dtype': 'float32', 'encoding': 'linear', 'scale': 1.0, 'range': None}
storage_format("rgb")      # png, uint8, linear, scale 1/255, range [0, 255]
storage_formats()          # every key with a default (the report's storage_formats)

valid_mask("depth", target)   # finite and > 0: the pixels with a measurement
valid_mask("rgb", image)      # finite
valid_mask("depth", target, invalid={"non_finite": False, "sentinel": 65535})
```

- **`storage`**: a key's default storage format: the file a writer writes
  (`file_type`: npy, npz, png, jpg, exr), the stored array (`dtype`), how
  stored numbers relate to the values (`encoding`: `linear` with a `scale`,
  `label` ids or `mask`) and the stored range (`range`; `null` when it depends
  on the data, and a writer records the range it wrote). euler-inference
  writes an output without a type in this format.
- **`validity`**: which values are measurements: `positive` (finite and above
  0: depth, disparity), `finite` (the default) or `any` (labels, masks).
  `valid_mask(key, values, invalid=None)` applies it elementwise, plus a
  dataset's declared `invalid` sentinel. It uses only comparisons, so it works
  on numpy arrays and torch tensors (on any device) and the package stays
  dependency-free.

Both are validated like the rest of the vocabulary
(`check_storage_format`), also in `euler.modalities` extension definitions,
which may declare `storage` and `validity` for their modalities. The
`modality_vocabulary_report` (1.1) carries them per modality and as a
`storage_formats` section per key, for euler-view.

## Addon validators


The shared contract requires every addon payload to be an object with its own
version. A consuming package can register the rest of its validation rules:

```python
from euler_dataset_contract import (
    register_addon_validator,
    validate_slot,
)

def validate_training_addon(value, context):
    validate_slot(value.get("slot"), f"{context}.slot")

register_addon_validator("euler_train", validate_training_addon)
```

Addon validators are process-wide. Register them during package import or
application startup, and pass `overwrite=True` only when intentionally
replacing an existing validator.

The ecosystem's own `euler_loading` addon, which names a dataset's decoder,
ships its rules here. Call `register_euler_loading_addon_validator()` to apply
them; ds-crawler and euler-loading do so on import. See the
[contract reference](docs/contract-reference.md#the-euler_loading-addon).

## JSON Schema

Generate Draft 2020-12 schemas from the same registry used by runtime
validation:

```python
from euler_dataset_contract import (
    build_dataset_head_schema,
    build_meta_schema,
)

dataset_head_schema = build_dataset_head_schema()
modality_catalog_schema = build_meta_schema()
```

The repository also publishes generated schemas under [`schemas/`](schemas/).
`build_dataset_head_schema()` selects the appropriate metadata rules from the
sibling `modality.key`; custom modality keys accept optional custom metadata.

## Built-in modality metadata

| Modality key | Required metadata |
|---|---|
| `rgb` | `range` |
| `depth` | `radial_depth`, `scale_to_meters`, `range` |
| `segmentation` | `skyclass` |
| `semantic_segmentation` | `skyclass` |

All registered modalities may additionally use the shared `dimensions`,
`file_types`, `invalid`, `sparse` and `source_grid` fields. `invalid` says how
pixels without a valid value are marked (a sentinel, non-finite values);
`sparse` marks rasters such as lidar depth that hold measurements at only some
pixels; `source_grid` records how a dataset's
pixel grid was cropped or resized from the images it was computed from (see
the [contract reference](docs/contract-reference.md#shared-metadata)). `build_default_meta(key)` returns authoring defaults;
parsing never silently fills missing required fields. Producer tooling such as
`ds-crawler` may merge defaults before it validates and writes a head.

See [the contract reference](docs/contract-reference.md) for field semantics,
normalization, versioning, and the public API.

## Conformance fixtures

The [`fixtures/`](fixtures/) directory holds the shared ecosystem corpus:
valid dataset heads with their canonical parsed
form, and invalid heads with the error each must produce. They are JSON, so
non-Python consumers read them directly.

Python consumers install the `testing` extra and get them as pytest fixtures
through an entry point, with no `conftest.py`:

```bash
pip install "euler-dataset-contract[testing]"
```

```python
def test_contract_heads_parse(golden_head, assert_head_roundtrip):
    assert_head_roundtrip(golden_head.head)
```

That single function runs once per head in the corpus. The extra carries only
`pytest`; the core install stays dependency-free and never imports it.

See [Conformance fixtures](docs/conformance-fixtures.md) for the full fixture
list, the shipped modality inventory, and the rule that a contract change is
proven against the corpus in every repository before it ships.

[Phase 0 evidence](docs/phase0-evidence.md) adds the current dataset vocabulary,
90 loader declarations, shared resize/crop and projection examples, and opt-in
checks against ds-crawler, loading, preprocess, and eval. The report separates
reference results from reproduced legacy failures and includes a local test
driver. Contract 1.0 runtime behavior is unchanged.

## Ecosystem boundary

The current 1.0 contract describes persisted dataset metadata. It does not yet
guarantee the exact decoded tensor layout, dtype, coordinate frame, or value
domain returned by a loader. In practice, `euler-loading` owns those decoding
rules and downstream packages normalize its outputs.

The observed gaps and a staged, backwards-compatible route toward canonical
modality names and enforceable decoded-output contracts are documented in
[Future contract directions](docs/future-directions.md). The
[Ecosystem streamlining plan](docs/ecosystem-streamlining-plan.md) turns that
direction into a concrete design and rollout.

## Development

```bash
git clone https://github.com/d-rothen/euler-dataset-contract.git
cd euler-dataset-contract
uv sync --extra dev
uv run ruff check .
uv run pytest
uv build
uv run python scripts/verify_distribution.py dist/*
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for schema changes and release checks,
and [SECURITY.md](SECURITY.md) for private vulnerability reporting.

## License

[MIT](LICENSE) © Daniel Rothenpieler

Phase 2 adds opt-in [captured spatial exports and validated materialization](docs/phase2.md),
with [verification and source installation details](docs/phase2-verification.md).
