Metadata-Version: 2.5
Name: oatschema
Version: 0.9.0.0
Summary: OATS (Open Annotation Task Schemas) JSON schemas, bundled for Python.
Project-URL: Homepage, https://oatschema.org
Project-URL: Repository, https://github.com/oatschema/oatschema-py
Author-email: OATS maintainers <maintainers@oatschema.org>
License-Expression: Apache-2.0
License-File: AUTHORS
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
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: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: all
Requires-Dist: jsonschema-rs>=0.58; extra == 'all'
Provides-Extra: validate
Requires-Dist: jsonschema-rs>=0.58; extra == 'validate'
Description-Content-Type: text/markdown

# oatschema

[![PyPI](https://img.shields.io/pypi/v/oatschema.svg)](https://pypi.org/project/oatschema/)
[![Python versions](https://img.shields.io/pypi/pyversions/oatschema.svg)](https://pypi.org/project/oatschema/)
[![CI](https://github.com/oatschema/oatschema-py/actions/workflows/ci.yml/badge.svg)](https://github.com/oatschema/oatschema-py/actions/workflows/ci.yml)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://github.com/oatschema/oatschema-py/blob/main/LICENSE)

The [OATS](https://oatschema.org) (Open Annotation Task Schemas) JSON schemas for Python.

OATS is a collection of strict, versioned JSON Schema 2020-12 schemas, defining and validating the structured outputs of machine learning models, workflow steps and annotation. Models, pipelines and people write the same JSON for each task, so a classification, a transcription or a set of detected objects has one shape, whatever produced it. This package bundles the schemas so you can validate those records anywhere. (OATS is unrelated to the W3C Web Annotation data model, formerly Open Annotation.)

- **No dependencies, no network.** The core uses only the standard library and reads schemas from the installed package. Validation is an optional extra built on [jsonschema-rs](https://github.com/Stranger6667/jsonschema).
- **Exactly as released.** Each schema is byte-identical to its [oatschema/oats](https://github.com/oatschema/oats) release, and a checksum manifest ships with every version.
- **Every version.** Each release bundles every schema version from 0.4.0 on, so records keep validating against the version they were written for.
- **Typed.** Ships `py.typed`. Schema names are a `Literal`, so mypy and pyright catch typos.

## Quick start

```
pip install 'oatschema[validate]'
```

```python
import oatschema

oatschema.validate({"labels": [{"label": "cat", "score": 0.92}]}, "classification")  # passes
oatschema.validate({"labels": [{"label": "cat", "score": 1.5}]}, "classification")
# oatschema.ValidationError: classification 0.9.0 at /labels/0/score: … is greater than the maximum of 1

schema = oatschema.get_schema("classification")  # a fresh dict, safe to modify
schema["$id"]  # "https://oatschema.org/0.9.0/classification"
oatschema.SCHEMA_VERSION  # "0.9.0", used when you don't pass a version
```

Requires Python 3.11 or later. `pip install oatschema` installs the schemas alone, with no dependencies; `get_schema` works without the extra. `oatschema[all]` installs every optional feature.

## Schemas

| Name | Holds | Since |
| :--- | :--- | :--- |
| `audio-transcription` | Transcribed speech, with timed segments, speakers and non-verbal events | 0.4.0 |
| `classification` | Predicted labels with scores and an optional vocabulary | 0.4.0 |
| `document-extraction` | Document layout and content: text blocks, coordinates and pages | 0.4.0 |
| `embedding` | A dense or sparse vector and the model that produced it | 0.4.0 |
| `entity-extraction` | Entities linked to their evidence, and relations between them | 0.4.0 |
| `generic` | Arbitrary key-value data | 0.4.0 |
| `geolocation` | A geographic feature, as a strict subset of GeoJSON | 0.4.0 |
| `llm-output` | One prompt and response, with generation parameters and usage | 0.4.0 |
| `object-detection` | Boxes, polygons and their hierarchy within a source | 0.4.0 |
| `ranking` | Ranked results for a query, such as search or retrieval hits | 0.8.0 |
| `regression` | Numeric predictions, intervals and forecasts | 0.4.0 |
| `temporal-segmentation` | Labelled time intervals, such as chapters, scenes or speaker turns | 0.7.0 |

Browse every schema, its fields and the changelog at [oatschema.org](https://oatschema.org).

## Validating records

`validate` raises `oatschema.ValidationError`, `is_valid` returns a bool, and `iter_errors` returns every error. All three use a cached [jsonschema-rs](https://github.com/Stranger6667/jsonschema) validator that also checks formats such as `uri` and `date-time`. You never need jsonschema-rs's own API or types.

```python
try:
    oatschema.validate(record, "classification")
except oatschema.ValidationError as error:
    error.path  # ("labels", 0, "score"): where in the record
    error.schema_path  # ("properties", "labels", ..., "maximum"): which rule failed
    error.keyword  # "maximum": the last keyword in schema_path
    error.schema_name, error.schema_version  # "classification", "0.9.0"
    error.message  # "… is greater than the maximum of 1"

for error in oatschema.iter_errors(record, "classification"):
    print(error)
```

`ValidationError` is a `ValueError`. `validate` raises the first error it finds, and stops there. `iter_errors` yields every error as a `ValidationError`.

- jsonschema-rs finds every error before `iter_errors` yields the first, so use `validate` when one error is enough.
- The order of errors is jsonschema-rs's: a record gives the same order each time with the same jsonschema-rs version, but the order may change between versions. The error `validate` raises is not always the first one `iter_errors` yields.

**Errors stay small, however large the record.** Messages show values from the record as `…` (`… is longer than 128 characters`), and are at most about 1 KB. Only property names are quoted, and cut to fit. `error.path` says where the value is. `str()` also shortens long property names in the path, but `error.path` keeps them in full. The jsonschema-rs error is not attached, nor is the failing value, so logging or printing a traceback never dumps the record.

**One validator, many records.** `get_validator` returns a cached `oatschema.Validator`, with the same `validate`, `is_valid` and `iter_errors` methods, without a schema name or version on every call:

```python
validator = oatschema.get_validator("classification", "0.7.0")
validator.schema_name, validator.schema_version  # "classification", "0.7.0"
validator.schema  # the schema, as a new dict
errors = list(validator.iter_errors(record))
```

**Format checking.** By default, a `uri` that isn't a URI, or a `date-time` that isn't an RFC 3339 timestamp, is an error. JSON Schema 2020-12 treats `format` as an annotation unless format checking is turned on, so other validators may accept records that oatschema rejects. To match them, or to keep accepting records you've accepted before, pass `check_formats=False` to `validate`, `is_valid`, `iter_errors` or `get_validator`:

```python
oatschema.is_valid(record, "classification", version="0.5.0", check_formats=False)
```

**Bring your own validator.** `get_schema` returns a plain dict for any JSON Schema 2020-12 validator. `x-license` and `x-version` are the only non-standard keywords, and 2020-12 validators ignore them. With [jsonschema](https://python-jsonschema.readthedocs.io):

```python
from jsonschema import Draft202012Validator

schema = oatschema.get_schema("classification")
validator = Draft202012Validator(schema, format_checker=Draft202012Validator.FORMAT_CHECKER)
validator.is_valid({"labels": [{"label": "cat", "score": 0.92}]})  # True
```

## Checking numbers before you write a record

Every number in OATS 0.9.0 is bounded within ±9,007,199,254,740,991, so every JSON implementation reads each integer the same way. `check_numbers` gets a record there before it is written. It never rounds, and it reports everything it changes:

```python
checked = oatschema.check_numbers(record, "classification")
checked.record  # a new record; the one you passed is not modified
checked.dropped  # (DroppedNumber(path, value, reason), ...)
checked.converted  # (ConvertedNumber(path, before, after), ...)
```

**Conversions keep the value exactly:** numpy values and arrays become Python ones, `-0.0` becomes `0.0`, a whole float in an `integer` field becomes an int, and, from schema version 0.9.0, an int `seed` becomes its string form. A float `seed` is not converted, and a fractional number in an `integer` field fails validation. A value with no exact JSON form, such as a `Decimal`, a numpy `datetime64` or a `longdouble`, raises `TypeError`.

**A bad number** is NaN, ±infinity, beyond the range above in any schema version, or outside its field's own bounds, such as a `score` of 1.5:

- under a property, it is removed, listed in `dropped`, and reported with a `DroppedNumberWarning`. The record is then validated, so if the property was required, the record is rejected;
- in a list, or at the top level, it rejects the record, because removing it would change what the list says;
- with `on_bad_number="raise"`, any bad number rejects the record. Conversions still happen.

A rejected record raises `oatschema.ValidationError`. The result is always valid against the schema version you pass, and dropping one of a pair, such as `interval_lower` without `interval_upper`, can leave a valid record that says less, so read `dropped`.

**Strings.** RFC 7493 forbids unpaired surrogates (`"\ud800"`), so `validate`, `is_valid`, `iter_errors` and `check_numbers` treat a string or property name containing one as invalid, in every schema version. This check is in this package, not the schemas, so other JSON Schema validators accept them.

## API

| Name | Description |
| :--- | :--- |
| `get_schema(name, version=None)` | The schema as a new dict on every call |
| `get_schema(name, version=None, mode="json")` | The schema file's text, exactly as released |
| `available_versions()` | Every bundled schema version, oldest first |
| `SCHEMA_VERSION` | The default schema version, the newest bundled |
| `LEGACY_VERSIONS` | The bundled versions from before OATS: 0.4.0 to 0.6.0 |
| `SchemaName` | The schema names, as a `Literal` |
| `validate(record, name, version=None, *, check_formats=True)` | Raises `ValidationError` for the first error found. Needs `[validate]` |
| `is_valid(record, name, version=None, *, check_formats=True)` | `True` or `False`. Needs `[validate]` |
| `iter_errors(record, name, version=None, *, check_formats=True)` | An iterator over every error, as `ValidationError`s. Needs `[validate]` |
| `get_validator(name, version=None, *, check_formats=True)` | The cached `Validator`. Needs `[validate]` |
| `Validator` | `validate(record)`, `is_valid(record)` and `iter_errors(record)`, plus read-only `schema_name`, `schema_version`, `schema` and `check_formats` |
| `check_numbers(record, name, version=None, *, on_bad_number="drop", check_formats=True)` | A `CheckedRecord(record, dropped, converted)`. See [Checking numbers](#checking-numbers-before-you-write-a-record) |
| `ValidationError` | A `ValueError` with `message`, `schema_name`, `schema_version`, `path`, `schema_path` and `keyword` |

- `version` must be exact: `"0.9.0"`, never `"0.8"` or `"latest"`.
- A name that exists in no bundled version raises `ValueError`. A version that isn't bundled, or that lacks the schema, raises `LookupError`.
- `check_formats=False` turns off checking of `format` (`date-time`, `uri`). It is keyword-only, and must be `True` or `False`.
- Arguments of the wrong type raise `TypeError`, naming the expected call: a name that isn't a str, a version that is neither a str nor `None`, or a record that isn't JSON data (a set, an arbitrary object, a dict with non-str keys). So does a record passed after the schema name, as in `validate(name, record)`, which should be `validate(record, name)`. A record that is JSON data but not an object, such as a list or `None`, is reported as invalid, not as a `TypeError`.
- Without the `validate` extra, the validation functions raise `ImportError`, naming the extra to install.

## Versions

**Schema versions.** Before OATS 1.0, a new release may reject records an older one accepted, or the reverse, so pass the version a record was written for:

```python
oatschema.is_valid({"labels": []}, "classification", version="0.7.0")  # False: 0.7.0 needed a vocabulary or producer
oatschema.is_valid({"labels": []}, "classification")  # True: from 0.8.0 an empty list means "checked, found nothing"
```

- From 0.7.0, each `$id` includes its version (`https://oatschema.org/0.9.0/classification`), so several versions can share one registry.
- Each schema states its own version: in `x-version` from 0.8.0, and in `version` up to 0.7.0.
- **Legacy versions.** 0.4.0 to 0.6.0 predate OATS and are listed in `LEGACY_VERSIONS`. All three use the same `$id` for each schema (`https://dorsalhub.com/schemas/open/<name>`). Build each validator from a single schema, and never load two of these versions into one registry.

**Package versions.** The package version is `a.b.c.d`:

- `a.b.c` is the newest bundled schema version, equal to `SCHEMA_VERSION`;
- `d` is the package's own revision, for fixes and features that add no schema version: `0.9.0.0`, then `0.9.0.1`, and so on. The first release, `0.8.0`, left it out.

Upgrading never removes a schema version, but a new schema version moves the default `SCHEMA_VERSION`.

**API changes.**

- Before OATS 1.0, breaking API changes come only with a new schema minor version, such as `0.9.0.0`. Releases that change only `d` are for fixes and additions. This is a goal rather than a guarantee: if a `d` release ever has to break something, its CHANGELOG entry says so.
- From OATS 1.0, breaking API changes wait for a new schema major version, `2.0.0.0`.

**Pinning.** Allow every release up to the next schema minor version, from the release whose features you use:

```
oatschema[validate]>=0.9.0.0,<0.10
```

From OATS 1.0, allow every release up to the next major version instead, for example `oatschema[validate]>=1.3,<2`.

## Contributing

Schema changes belong in [oatschema/oats](https://github.com/oatschema/oats). For this package, see [CONTRIBUTING.md](https://github.com/oatschema/oatschema-py/blob/main/CONTRIBUTING.md). Commits need a DCO sign-off (`git commit -s`).

## License

Apache-2.0. Copyright [The OATS Authors](https://github.com/oatschema/oatschema-py/blob/main/AUTHORS).
