# Model Registry

{% hint style="info" %}
This API Reference is based on DeGirum Tools version 1.2.0.
{% endhint %}

### Model Registry Overview <a href="#model-registry-overview" id="model-registry-overview"></a>

Use this module when you want to use a working model without memorizing model details. `ModelRegistry` acts as a guided menu of DeGirum models, while `ModelSpec` captures the handful of settings required to load one of those choices. Together they help pick a model with confidence and launch inference in just a few lines of code.

Key Features

* Capture one model request with `ModelSpec` so it can be shared, reused, or versioned alongside your project.
* Browse curated registries to surface models by goal, compatible hardware, or descriptive metadata.
* Layer simple filters to shrink the catalog to only the options that fit your scenario.
* Keep common defaults (host, zoo, properties) in a single place so every run follows the same playbook.

Typical Usage

1. Point `ModelRegistry` at the YAML file or hosted URL that lists the models available to your team.
2. Narrow the registry with helpers such as `for_task` and `for_hardware` to focus on the models that match your intent.
3. Choose a remaining `ModelSpec` (or let ranking helpers do it) to represent the model you plan to run.
4. Call `ModelSpec.load_model()` to launch the model and start running inference.

Example:

{% code overflow="wrap" %}

```python
from degirum_tools import Display, ModelRegistry, ModelSpec, remote_assets

registry = ModelRegistry(
    config_file="https://assets.degirum.com/registry/models.yaml",
)

model_spec = (
    registry
    .for_task("coco_detection")
    .top_model_spec()
)

model = model_spec.load_model()
inference_result = model(remote_assets.three_persons)

print(inference_result)

with Display("Model Registry Demo") as output_display:
    output_display.show_image(inference_result.image_overlay)
```

{% endcode %}

Integration Notes

* Registry files can live in source control or be hosted online; point the constructor at whichever location you maintain.
* `ModelSpec.load_model()` opens the connection with `degirum.connect` on your behalf, so you do not have to manage sessions manually.
* Override defaults as needed when experimenting, without editing the shared registry catalog.

Key Functions

* `ModelSpec.load_model()` turns a saved specification into a ready-to-run model.
* `ModelSpec.ensure_local()` downloads the assets you need for offline use and returns a spec that targets `@local`.
* `ModelRegistry.all_model_specs()` lists the prepared specs that match the filters you have applied.
* `ModelRegistry.best_model_spec()` helps you pick a model based on ranking fields such as accuracy scores.

Configuration Options

* Registry defaults set shared values such as the inference host, zoo URL, tokens, and model properties.
* Metadata filters accept literal values or simple callables when you want to match custom fields in your catalog.

## Classes <a href="#classes" id="classes"></a>

## ModelSpec <a href="#modelspec" id="modelspec"></a>

`ModelSpec`

`dataclass`

Serializable description of a single model load request.

Attributes:

| Name                     | Type             | Description                                                                                                         |
| ------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------- |
| `model_name`             | `str`            | Exact model identifier expected by the zoo. Ignored when `model_url` is provided.                                   |
| `zoo_url`                | `str`            | Zoo location that hosts this model. When left empty, registry defaults or explicit overrides must supply the value. |
| `model_url`              | `str`            | Direct URL to the model file. When set, overrides `model_name` and `zoo_url`.                                       |
| `inference_host_address` | `str`            | Target inference host in PySDK locator format (for example `@cloud` or `@local`).                                   |
| `token`                  | `str \| None`    | Optional authentication token for the zoo.                                                                          |
| `model_properties`       | `dict[str, Any]` | Keyword arguments forwarded to `dg.ZooManager.load_model`.                                                          |
| `metadata`               | `dict \| None`   | Free-form informational payload, typically copied from the registry entry.                                          |

Examples:

{% code overflow="wrap" %}

```python
spec = ModelSpec(
    model_name="<model>",
    zoo_url="<zoo>",
    inference_host_address="@local",
)
spec.load_model()

spec = ModelSpec(model_url="<model_url>")
spec.load_model()
```

{% endcode %}

### ModelSpec Methods <a href="#modelspec-methods" id="modelspec-methods"></a>

#### \_\_post\_init\_\_ <a href="#post_init" id="post_init"></a>

`__post_init__()`

Validate required fields, support `model_url`, and normalize values.

Raises:

| Type         | Description                                          |
| ------------ | ---------------------------------------------------- |
| `ValueError` | If mandatory attributes are missing or inconsistent. |

#### download\_model(destination=None, ...) <a href="#download_model" id="download_model"></a>

`download_model(destination=None, *, cloud_sync=False)`

Download the model file to a local directory.

Parameters:

| Name          | Type                  | Description                                                                                                                                                                           | Default |
| ------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `destination` | `str \| Path \| None` | Destination directory or path. If a directory is provided, the model is saved into a subdirectory named after the model. When `None`, the default application data directory is used. | `None`  |
| `cloud_sync`  | `bool`                | When `True`, checks the cloud zoo for an updated model version and downloads it if the local copy is missing or out of date.                                                          | `False` |

Returns:

| Name         | Type   | Description                                    |
| ------------ | ------ | ---------------------------------------------- |
| `local_path` | `Path` | Path to the downloaded model assets directory. |

#### ensure\_local(cloud\_sync=False) <a href="#ensure_local" id="ensure_local"></a>

`ensure_local(cloud_sync=False)`

Ensures the model is present locally; downloads if needed. Returns a **new** ModelSpec with zoo\_url set to local path and inference\_host\_address to '@local'.

Parameters:

| Name         | Type   | Description                                                                                                                  | Default |
| ------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------- | ------- |
| `cloud_sync` | `bool` | When `True`, checks the cloud zoo for an updated model version and downloads it if the local copy is missing or out of date. | `False` |

Returns:

| Name         | Type        | Description                                         |
| ------------ | ----------- | --------------------------------------------------- |
| `local_spec` | `ModelSpec` | New specification pointing to the local model copy. |

#### load\_model(zoo=None) <a href="#load_model" id="load_model"></a>

`load_model(zoo=None)`

Resolve the specification into a ready-to-use model instance.

Parameters:

| Name  | Type                 | Description                                                                                   | Default |
| ----- | -------------------- | --------------------------------------------------------------------------------------------- | ------- |
| `zoo` | `ZooManager \| None` | Optional pre-connected inference manager. When `None`, `zoo_connect` is called automatically. | `None`  |

Returns:

| Name    | Type    | Description                         |
| ------- | ------- | ----------------------------------- |
| `model` | `Model` | Loaded model returned by the PySDK. |

#### zoo\_connect <a href="#zoo_connect" id="zoo_connect"></a>

`zoo_connect()`

Create a connection to the configured model zoo.

Returns:

| Name                | Type         | Description                                                             |
| ------------------- | ------------ | ----------------------------------------------------------------------- |
| `inference_manager` | `ZooManager` | Reusable inference manager suitable for repeated calls to `load_model`. |

## ModelRegistry <a href="#modelregistry" id="modelregistry"></a>

`ModelRegistry`

Queryable collection of `ModelSpec` entries.

Registry data is sourced from structured YAML files that describe the available models, their target tasks, and compatible hardware. Instances remain immutable, and filtering methods return new copies so intermediate views can be chained without side effects.

Examples:

{% code overflow="wrap" %}

```python
registry = ModelRegistry(
    config_file="https://assets.degirum.com/registry/models.yaml",
)
filtered = registry.for_task("coco_detection")
first_spec = filtered.top_model_spec()
print(first_spec.model_name)
```

{% endcode %}

### ModelRegistry Methods <a href="#modelregistry-methods" id="modelregistry-methods"></a>

#### \_\_init\_\_(\*, ...) <a href="#init" id="init"></a>

`__init__(*, config=None, config_file=None)`

Create a registry from a configuration dictionary or YAML file.

Parameters:

| Name          | Type                      | Description                                                                                                                                                                                             | Default |
| ------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `config`      | `dict[str, dict] \| None` | Parsed registry configuration. If provided, `config_file` is ignored.                                                                                                                                   | `None`  |
| `config_file` | `Path \| str \| None`     | Path or URL to a YAML registry document. Defaults to `models.yaml` located alongside this module. The latest DeGirum-managed catalog is published at <https://assets.degirum.com/registry/models.yaml>. | `None`  |

Raises:

| Type              | Description                                                          |
| ----------------- | -------------------------------------------------------------------- |
| `RuntimeError`    | If a remote registry cannot be retrieved.                            |
| `ValidationError` | When the configuration does not satisfy `ModelRegistry.schema_text`. |

#### all\_model\_specs(\*, ...) <a href="#all_model_specs" id="all_model_specs"></a>

`all_model_specs(*, inference_host_address=None, zoo_url=None, token=None, model_properties=None)`

Create `ModelSpec` objects for every model in the registry.

Parameters:

| Name                     | Type           | Description                                                                                         | Default |
| ------------------------ | -------------- | --------------------------------------------------------------------------------------------------- | ------- |
| `inference_host_address` | `str \| None`  | Destination inference host. If omitted, the registry defaults are used.                             | `None`  |
| `zoo_url`                | `str \| None`  | Override for the zoo URL. A common use case is redirecting all specs to a local zoo during testing. | `None`  |
| `token`                  | `str \| None`  | Authentication token to apply to each spec.                                                         | `None`  |
| `model_properties`       | `dict \| None` | Keyword arguments merged into the default properties and applied to every resulting spec.           | `None`  |

Returns:

| Name    | Type              | Description                                        |
| ------- | ----------------- | -------------------------------------------------- |
| `specs` | `list[ModelSpec]` | Specifications matching the current filtered view. |

#### best\_model\_spec(key, ...) <a href="#best_model_spec" id="best_model_spec"></a>

`best_model_spec(key, compare='max', **kwargs)`

Select the model with the best numeric metadata value.

Parameters:

| Name       | Type             | Description                                                                 | Default    |
| ---------- | ---------------- | --------------------------------------------------------------------------- | ---------- |
| `key`      | `str`            | Metadata field to inspect.                                                  | *required* |
| `compare`  | `str`            | Either `"max"` (default) for the largest value or `"min"` for the smallest. | `'max'`    |
| `**kwargs` | `dict[str, Any]` | Overrides forwarded to `all_model_specs`.                                   | `{}`       |

Returns:

| Name        | Type        | Description                                          |
| ----------- | ----------- | ---------------------------------------------------- |
| `best_spec` | `ModelSpec` | Model whose metadata matches the requested criteria. |

Raises:

| Type           | Description                                                               |
| -------------- | ------------------------------------------------------------------------- |
| `RuntimeError` | If the registry contains no models.                                       |
| `ValueError`   | If none of the models expose the requested key or provide numeric values. |

#### for\_alias(alias) <a href="#for_alias" id="for_alias"></a>

`for_alias(alias)`

Filter models by alias.

Parameters:

| Name    | Type  | Description                      | Default    |
| ------- | ----- | -------------------------------- | ---------- |
| `alias` | `str` | Registry alias to match exactly. | *required* |

Returns:

| Name       | Type            | Description                                        |
| ---------- | --------------- | -------------------------------------------------- |
| `registry` | `ModelRegistry` | Filtered registry containing only matching models. |

#### for\_hardware(hardware) <a href="#for_hardware" id="for_hardware"></a>

`for_hardware(hardware)`

Filter models to those compatible with a specific hardware target.

Parameters:

| Name       | Type  | Description                                                              | Default    |
| ---------- | ----- | ------------------------------------------------------------------------ | ---------- |
| `hardware` | `str` | Hardware identifier in `RUNTIME/DEVICE` format, for example `N2X/ORCA1`. | *required* |

Returns:

| Name       | Type            | Description                                        |
| ---------- | --------------- | -------------------------------------------------- |
| `registry` | `ModelRegistry` | Filtered registry containing only matching models. |

#### for\_meta(meta) <a href="#for_meta" id="for_meta"></a>

`for_meta(meta)`

Filter models by metadata key/value pairs.

Parameters:

| Name   | Type             | Description                                                                                                                                                                                      | Default    |
| ------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
| `meta` | `dict[str, Any]` | Dictionary describing metadata criteria. Values may be callables that receive a metadata dictionary and return `True` when the model should be included. Non-callable values must match exactly. | *required* |

Returns:

| Name       | Type            | Description                                        |
| ---------- | --------------- | -------------------------------------------------- |
| `registry` | `ModelRegistry` | Filtered registry containing only matching models. |

#### for\_task(task) <a href="#for_task" id="for_task"></a>

`for_task(task)`

Filter models by the task label declared in the registry.

Parameters:

| Name   | Type  | Description                                                 | Default    |
| ------ | ----- | ----------------------------------------------------------- | ---------- |
| `task` | `str` | Task identifier such as `face_detection` or `segmentation`. | *required* |

Returns:

| Name       | Type            | Description                                        |
| ---------- | --------------- | -------------------------------------------------- |
| `registry` | `ModelRegistry` | Filtered registry containing only matching models. |

#### get\_aliases <a href="#get_aliases" id="get_aliases"></a>

`get_aliases()`

Return every unique alias present in the registry.

Returns:

| Name      | Type        | Description             |
| --------- | ----------- | ----------------------- |
| `aliases` | `list[str]` | Sorted list of aliases. |

#### get\_hardware <a href="#get_hardware" id="get_hardware"></a>

`get_hardware()`

Return every unique hardware target present in the registry.

Returns:

| Name       | Type        | Description                          |
| ---------- | ----------- | ------------------------------------ |
| `hardware` | `list[str]` | Sorted list of hardware identifiers. |

#### get\_tasks <a href="#get_tasks" id="get_tasks"></a>

`get_tasks()`

Return every unique task label present in the registry.

Returns:

| Name    | Type        | Description                |
| ------- | ----------- | -------------------------- |
| `tasks` | `list[str]` | Sorted list of task names. |

#### top\_model\_spec(\*\*kwargs) <a href="#top_model_spec" id="top_model_spec"></a>

`top_model_spec(**kwargs)`

Return the first model listed in the current registry view.

Parameters:

| Name       | Type             | Description                               | Default |
| ---------- | ---------------- | ----------------------------------------- | ------- |
| `**kwargs` | `dict[str, Any]` | Overrides forwarded to `all_model_specs`. | `{}`    |

Returns:

| Name       | Type        | Description                           |
| ---------- | ----------- | ------------------------------------- |
| `top_spec` | `ModelSpec` | Specification for the top-most entry. |

Raises:

| Type           | Description                        |
| -------------- | ---------------------------------- |
| `RuntimeError` | If the filtered registry is empty. |

#### with\_defaults(\*, ...) <a href="#with_defaults" id="with_defaults"></a>

`with_defaults(*, inference_host_address=None, zoo_url=None, token=None, model_properties=None)`

Return a copy of the registry with overridden default settings.

Parameters:

| Name                     | Type           | Description                                                                   | Default |
| ------------------------ | -------------- | ----------------------------------------------------------------------------- | ------- |
| `inference_host_address` | `str \| None`  | Override for the default inference target.                                    | `None`  |
| `zoo_url`                | `str \| None`  | Fallback zoo URL applied when entries omit an explicit value.                 | `None`  |
| `token`                  | `str \| None`  | Token injected into downstream connections.                                   | `None`  |
| `model_properties`       | `dict \| None` | Base keyword arguments merged into every `ModelSpec` emitted by the registry. | `None`  |

Returns:

| Name       | Type            | Description                                 |
| ---------- | --------------- | ------------------------------------------- |
| `registry` | `ModelRegistry` | New registry with updated defaults applied. |
