Skip to content

Register now for

# Reference for `hub_sdk/modules/models.py`

Note

This file is available at https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/modules/models.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!

## `` hub_sdk.modules.models.Models

    Models(model_id: str | None = None, headers: dict[str, Any] | None = None)

Bases: `CRUDClient`

A class representing a client for interacting with Models through CRUD operations.

This class extends the CRUDClient class and provides specific methods for working with Models, including creating, retrieving, updating, and deleting model resources, as well as uploading model weights and metrics.

Attributes:

Name | Type | Description
--- | --- | ---
`base_endpoint` | `str` | The base endpoint URL for the API, set to "models".
`hub_client` | `ModelUpload` | An instance of ModelUpload used for interacting with model uploads.
`id` | `str | None` | The unique identifier of the model, if available.
`data` | `Dict` | A dictionary to store model data.
`metrics` | `List[Dict] | None` | Model metrics data, populated after retrieval.

Note

The 'id' attribute is set during initialization and can be used to uniquely identify a model. The 'data' attribute is used to store model data fetched from the API.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model_id` | `str` | The unique identifier of the model. | `None`
`headers` | `Dict[str, Any]` | Headers to be included in API requests. | `None`

Source code in `hub_sdk/modules/models.py`

    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    def __init__(self, model_id: str | None = None, headers: dict[str, Any] | None = None):
        """
        Initialize a Models instance.

        Args:
            model_id (str, optional): The unique identifier of the model.
            headers (Dict[str, Any], optional): Headers to be included in API requests.
        """
        self.base_endpoint = "models"
        super().__init__(self.base_endpoint, "model", headers)
        self.hub_client = ModelUpload(headers)
        self.id = model_id
        self.data = {}
        self.metrics = None
        if model_id:
            self.get_data()

### `` create_model

    create_model(model_data: dict) -> None

Create a new model with the provided data and set the model ID for the current instance.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model_data` | `Dict` | A dictionary containing the data for creating the model. | required

Source code in `hub_sdk/modules/models.py`

    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    def create_model(self, model_data: dict) -> None:
        """
        Create a new model with the provided data and set the model ID for the current instance.

        Args:
            model_data (Dict): A dictionary containing the data for creating the model.
        """
        try:
            response = super().create(model_data)

            if response is None:
                self.logger.error("Received no response from the server while creating the model.")
                return

            # Ensuring the response object has the .json() method
            if not hasattr(response, "json"):
                self.logger.error("Invalid response object received while creating the model.")
                return

            resp_data = response.json()
            if resp_data is None:
                self.logger.error("No data received in the response while creating the model.")
                return

            self.id = resp_data.get("data", {}).get("id")

            # Check if the ID was successfully retrieved
            if not self.id:
                self.logger.error("Model ID not found in the response data.")
                return

            self.get_data()

        except Exception as e:
            self.logger.error(f"An error occurred while creating the model: {str(e)}")

### `` delete

    delete(hard: bool = False) -> Response | None

Delete the model resource represented by this instance.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`hard` | `bool` | If True, perform a hard (permanent) delete. | `False`

Note

The 'hard' parameter determines whether to perform a soft delete (default) or a hard delete. In a soft delete, the model might be marked as deleted but retained in the system. In a hard delete, the model is permanently removed from the system.

Returns:

Type | Description
--- | ---
`Optional[Response]` | Response object from the delete request, or None if delete fails.

Source code in `hub_sdk/modules/models.py`

    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    def delete(self, hard: bool = False) -> Response | None:
        """
        Delete the model resource represented by this instance.

        Args:
            hard (bool, optional): If True, perform a hard (permanent) delete.

        Note:
            The 'hard' parameter determines whether to perform a soft delete (default) or a hard delete.
            In a soft delete, the model might be marked as deleted but retained in the system.
            In a hard delete, the model is permanently removed from the system.

        Returns:
            (Optional[Response]): Response object from the delete request, or None if delete fails.
        """
        return super().delete(self.id, hard)

### `` export

    export(format: str) -> Response | None

Export model to specified format via Ultralytics HUB.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`format` | `str` | Export format. Supported formats are available at https://docs.ultralytics.com/modes/export/#export-formats | required

Returns:

Type | Description
--- | ---
`Optional[Response]` | Response object from the export request, or None if export fails.

Source code in `hub_sdk/modules/models.py`

    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    def export(self, format: str) -> Response | None:
        """
        Export model to specified format via Ultralytics HUB.

        Args:
            format (str): Export format. Supported formats are available at
                https://docs.ultralytics.com/modes/export/#export-formats

        Returns:
            (Optional[Response]): Response object from the export request, or None if export fails.
        """
        return self.hub_client.export(self.id, format)  # response

### `` get_architecture

    get_architecture() -> str | None

Get the architecture name of the model.

Returns:

Type | Description
--- | ---
`Optional[str]` | The architecture configuration path or None if not available.

Source code in `hub_sdk/modules/models.py`

    167
    168
    169
    170
    171
    172
    173
    174
    def get_architecture(self) -> str | None:
        """
        Get the architecture name of the model.

        Returns:
            (Optional[str]): The architecture configuration path or None if not available.
        """
        return self.data.get("cfg")

### `` get_data

    get_data() -> None

Retrieve data for the current model instance.

Fetches model data from the API if a valid model ID has been set and stores it in the instance. Logs appropriate error messages if the retrieval fails at any step.

Source code in `hub_sdk/modules/models.py`

     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    def get_data(self) -> None:
        """
        Retrieve data for the current model instance.

        Fetches model data from the API if a valid model ID has been set and stores it in the instance. Logs appropriate
        error messages if the retrieval fails at any step.
        """
        if not self.id:
            self.logger.error("No model id has been set. Update the model id or create a model.")
            return

        try:
            response = super().read(self.id)

            if response is None:
                self.logger.error(f"Received no response from the server for model ID: {self.id}")
                return

            # Check if the response has a .json() method (it should if it's a response object)
            if not hasattr(response, "json"):
                self.logger.error(f"Invalid response object received for model ID: {self.id}")
                return

            resp_data = response.json()
            if resp_data is None:
                self.logger.error(f"No data received in the response for model ID: {self.id}")
                return

            data = resp_data.get("data", {})
            self.data = self._reconstruct_data(data)
            self.logger.debug(f"Model data retrieved for ID: {self.id}")

        except Exception as e:
            self.logger.error(f"An error occurred while retrieving data for model ID: {self.id}, {str(e)}")

### `` get_dataset_url

    get_dataset_url() -> str | None

Get the dataset URL associated with the model.

Returns:

Type | Description
--- | ---
`Optional[str]` | The URL of the dataset or None if not available.

Source code in `hub_sdk/modules/models.py`

    176
    177
    178
    179
    180
    181
    182
    183
    def get_dataset_url(self) -> str | None:
        """
        Get the dataset URL associated with the model.

        Returns:
            (Optional[str]): The URL of the dataset or None if not available.
        """
        return self.data.get("data")

### `` get_metrics

    get_metrics() -> list[dict[str, Any]] | None

Get metrics of the model.

Returns:

Type | Description
--- | ---
`Optional[List[Dict[str, Any]]]` | The list of metrics objects, or None if retrieval fails.

Source code in `hub_sdk/modules/models.py`

    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    def get_metrics(self) -> list[dict[str, Any]] | None:
        """
        Get metrics of the model.

        Returns:
            (Optional[List[Dict[str, Any]]]): The list of metrics objects, or None if retrieval fails.
        """
        if self.metrics:
            return self.metrics

        endpoint = f"{HUB_API_ROOT}/v1/{self.base_endpoint}/{self.id}/metrics"
        try:
            results = self.get(endpoint)
            self.metrics = results.json().get("data")
            return self.metrics
        except Exception as e:
            self.logger.error(f"Model Metrics not found: {e}")
            return None

### `` get_weights_url

    get_weights_url(weight: str = 'best') -> str | None

Get the URL of the model weights.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`weight` | `str` | Type of weights to retrieve, either "best" or "last". | `'best'`

Returns:

Type | Description
--- | ---
`Optional[str]` | The URL of the specified weights or None if not available.

Source code in `hub_sdk/modules/models.py`

    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    def get_weights_url(self, weight: str = "best") -> str | None:
        """
        Get the URL of the model weights.

        Args:
            weight (str, optional): Type of weights to retrieve, either "best" or "last".

        Returns:
            (Optional[str]): The URL of the specified weights or None if not available.
        """
        if weight == "last":
            return self.data.get("resume")

        return self.data.get("weights")

### `` has_best_weights

    has_best_weights() -> bool

Check if the model has best weights saved from previous training.

Source code in `hub_sdk/modules/models.py`

    151
    152
    153
    def has_best_weights(self) -> bool:
        """Check if the model has best weights saved from previous training."""
        return self.data.get("has_best_weights", False)

### `` is_custom

    is_custom() -> bool

Check if the model is a custom model rather than a standard one.

Source code in `hub_sdk/modules/models.py`

    163
    164
    165
    def is_custom(self) -> bool:
        """Check if the model is a custom model rather than a standard one."""
        return self.data.get("is_custom", False)

### `` is_pretrained

    is_pretrained() -> bool

Check if the model is pretrained with initial weights.

Source code in `hub_sdk/modules/models.py`

    155
    156
    157
    def is_pretrained(self) -> bool:
        """Check if the model is pretrained with initial weights."""
        return self.data.get("is_pretrained", False)

### `` is_resumable

    is_resumable() -> bool

Check if the model training can be resumed based on the presence of last weights.

Source code in `hub_sdk/modules/models.py`

    147
    148
    149
    def is_resumable(self) -> bool:
        """Check if the model training can be resumed based on the presence of last weights."""
        return self.data.get("has_last_weights", False)

### `` is_trained

    is_trained() -> bool

Check if the model has completed training and is in 'trained' status.

Source code in `hub_sdk/modules/models.py`

    159
    160
    161
    def is_trained(self) -> bool:
        """Check if the model has completed training and is in 'trained' status."""
        return self.data.get("status") == "trained"

### `` predict

    predict(image: str, config: dict[str, Any]) -> Response | None

Run prediction using the model via Ultralytics HUB.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`image` | `str` | The path to the image file. | required
`config` | `Dict[str, Any]` | A configuration dictionary for the prediction. | required

Returns:

Type | Description
--- | ---
`Optional[Response]` | Response object from the predict request, or None if prediction fails.

Source code in `hub_sdk/modules/models.py`

    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    def predict(self, image: str, config: dict[str, Any]) -> Response | None:
        """
        Run prediction using the model via Ultralytics HUB.

        Args:
            image (str): The path to the image file.
            config (Dict[str, Any]): A configuration dictionary for the prediction.

        Returns:
            (Optional[Response]): Response object from the predict request, or None if prediction fails.
        """
        return self.hub_client.predict(self.id, image, config)  # response

### `` start_heartbeat

    start_heartbeat(interval: int = 60)

Start sending heartbeat signals to a remote hub server.

This method initiates the sending of heartbeat signals to a hub server to indicate the continued availability and health of the client.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`interval` | `int` | The time interval, in seconds, between consecutive heartbeats. | `60`

Note

Heartbeats are essential for maintaining a connection with the hub server and ensuring that the client remains active and responsive.

Source code in `hub_sdk/modules/models.py`

    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    def start_heartbeat(self, interval: int = 60):
        """
        Start sending heartbeat signals to a remote hub server.

        This method initiates the sending of heartbeat signals to a hub server
        to indicate the continued availability and health of the client.

        Args:
            interval (int, optional): The time interval, in seconds, between consecutive heartbeats.

        Note:
            Heartbeats are essential for maintaining a connection with the hub server
            and ensuring that the client remains active and responsive.
        """
        self.hub_client._register_signal_handlers()
        self.hub_client._start_heartbeats(self.id, interval)

### `` stop_heartbeat

    stop_heartbeat() -> None

Stop sending heartbeat signals to a remote hub server.

This method terminates the sending of heartbeat signals to the hub server, effectively signaling that the client is no longer available or active.

Note

Stopping heartbeats should be done carefully, as it may result in the hub server considering the client as disconnected or unavailable.

Source code in `hub_sdk/modules/models.py`

    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    def stop_heartbeat(self) -> None:
        """
        Stop sending heartbeat signals to a remote hub server.

        This method terminates the sending of heartbeat signals to the hub server,
        effectively signaling that the client is no longer available or active.

        Note:
            Stopping heartbeats should be done carefully, as it may result in the hub server
            considering the client as disconnected or unavailable.
        """
        self.hub_client._stop_heartbeats()

### `` update

    update(data: dict) -> Response | None

Update the model resource represented by this instance.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`data` | `Dict` | The updated data for the model resource. | required

Returns:

Type | Description
--- | ---
`Optional[Response]` | Response object from the update request, or None if update fails.

Source code in `hub_sdk/modules/models.py`

    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    def update(self, data: dict) -> Response | None:
        """
        Update the model resource represented by this instance.

        Args:
            data (Dict): The updated data for the model resource.

        Returns:
            (Optional[Response]): Response object from the update request, or None if update fails.
        """
        return super().update(self.id, data)

### `` upload_metrics

    upload_metrics(metrics: dict) -> Response | None

Upload model metrics to Ultralytics HUB.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`metrics` | `Dict` | Dictionary containing model metrics data. | required

Returns:

Type | Description
--- | ---
`Optional[Response]` | Response object from the upload metrics request, or None if it fails.

Source code in `hub_sdk/modules/models.py`

    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    def upload_metrics(self, metrics: dict) -> Response | None:
        """
        Upload model metrics to Ultralytics HUB.

        Args:
            metrics (Dict): Dictionary containing model metrics data.

        Returns:
            (Optional[Response]): Response object from the upload metrics request, or None if it fails.
        """
        return self.hub_client.upload_metrics(self.id, metrics)  # response

### `` upload_model

    upload_model(
        epoch: int,
        weights: str,
        is_best: bool = False,
        map: float = 0.0,
        final: bool = False,
    ) -> Response | None

Upload a model checkpoint to Ultralytics HUB.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`epoch` | `int` | The current training epoch. | required
`weights` | `str` | Path to the model weights file. | required
`is_best` | `bool` | Indicates if the current model is the best one so far. | `False`
`map` | `float` | Mean average precision of the model. | `0.0`
`final` | `bool` | Indicates if the model is the final model after training. | `False`

Returns:

Type | Description
--- | ---
`Optional[Response]` | Response object from the upload request, or None if upload fails.

Source code in `hub_sdk/modules/models.py`

    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    def upload_model(
        self,
        epoch: int,
        weights: str,
        is_best: bool = False,
        map: float = 0.0,
        final: bool = False,
    ) -> Response | None:
        """
        Upload a model checkpoint to Ultralytics HUB.

        Args:
            epoch (int): The current training epoch.
            weights (str): Path to the model weights file.
            is_best (bool, optional): Indicates if the current model is the best one so far.
            map (float, optional): Mean average precision of the model.
            final (bool, optional): Indicates if the model is the final model after training.

        Returns:
            (Optional[Response]): Response object from the upload request, or None if upload fails.
        """
        return self.hub_client.upload_model(self.id, epoch, weights, is_best=is_best, map=map, final=final)

## `` hub_sdk.modules.models.ModelList

    ModelList(page_size=None, public=None, headers=None)

Bases: `PaginatedList`

Provides a paginated list interface for managing and querying models from the Ultralytics HUB API.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`page_size` | `int` | The number of items to request per page. | `None`
`public` | `bool` | Whether the items should be publicly accessible. | `None`
`headers` | `Dict` | Headers to be included in API requests. | `None`

Source code in `hub_sdk/modules/models.py`

    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    def __init__(self, page_size=None, public=None, headers=None):
        """
        Initialize a ModelList instance.

        Args:
            page_size (int, optional): The number of items to request per page.
            public (bool, optional): Whether the items should be publicly accessible.
            headers (Dict, optional): Headers to be included in API requests.
        """
        base_endpoint = "models"
        super().__init__(base_endpoint, "model", page_size, public, headers)

📅 Created 1 year ago ✏️ Updated 1 month ago