Use Any type-hints for args and kwargs (#18372)

Signed-off-by: UltralyticsAssistant <web@ultralytics.com>
Co-authored-by: UltralyticsAssistant <web@ultralytics.com>
This commit is contained in:
Glenn Jocher 2024-12-24 20:32:59 +01:00 committed by GitHub
parent 51026a9a4a
commit 05323919b3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 26 additions and 25 deletions

View file

@ -45,7 +45,7 @@ Streamlit makes it simple to build and deploy interactive web applications. Comb
```bash ```bash
yolo solutions inference yolo solutions inference
yolo solutions inference model="path/to/model/file.pt" yolo solutions inference model="path/to/model.pt"
``` ```
=== "Python" === "Python"

View file

@ -2,7 +2,7 @@
import inspect import inspect
from pathlib import Path from pathlib import Path
from typing import Dict, List, Union from typing import Any, Dict, List, Union
import numpy as np import numpy as np
import torch import torch
@ -152,7 +152,7 @@ class Model(nn.Module):
self, self,
source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None, source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None,
stream: bool = False, stream: bool = False,
**kwargs, **kwargs: Any,
) -> list: ) -> list:
""" """
Alias for the predict method, enabling the model instance to be callable for predictions. Alias for the predict method, enabling the model instance to be callable for predictions.
@ -165,7 +165,7 @@ class Model(nn.Module):
the image(s) to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch the image(s) to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch
tensor, or a list/tuple of these. tensor, or a list/tuple of these.
stream (bool): If True, treat the input source as a continuous stream for predictions. stream (bool): If True, treat the input source as a continuous stream for predictions.
**kwargs (Any): Additional keyword arguments to configure the prediction process. **kwargs: Additional keyword arguments to configure the prediction process.
Returns: Returns:
(List[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a (List[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a
@ -466,7 +466,7 @@ class Model(nn.Module):
self, self,
source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None, source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
stream: bool = False, stream: bool = False,
**kwargs, **kwargs: Any,
) -> list: ) -> list:
""" """
Generates image embeddings based on the provided source. Generates image embeddings based on the provided source.
@ -478,7 +478,7 @@ class Model(nn.Module):
source (str | Path | int | List | Tuple | np.ndarray | torch.Tensor): The source of the image for source (str | Path | int | List | Tuple | np.ndarray | torch.Tensor): The source of the image for
generating embeddings. Can be a file path, URL, PIL image, numpy array, etc. generating embeddings. Can be a file path, URL, PIL image, numpy array, etc.
stream (bool): If True, predictions are streamed. stream (bool): If True, predictions are streamed.
**kwargs (Any): Additional keyword arguments for configuring the embedding process. **kwargs: Additional keyword arguments for configuring the embedding process.
Returns: Returns:
(List[torch.Tensor]): A list containing the image embeddings. (List[torch.Tensor]): A list containing the image embeddings.
@ -501,7 +501,7 @@ class Model(nn.Module):
source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None, source: Union[str, Path, int, Image.Image, list, tuple, np.ndarray, torch.Tensor] = None,
stream: bool = False, stream: bool = False,
predictor=None, predictor=None,
**kwargs, **kwargs: Any,
) -> List[Results]: ) -> List[Results]:
""" """
Performs predictions on the given image source using the YOLO model. Performs predictions on the given image source using the YOLO model.
@ -517,7 +517,7 @@ class Model(nn.Module):
stream (bool): If True, treats the input source as a continuous stream for predictions. stream (bool): If True, treats the input source as a continuous stream for predictions.
predictor (BasePredictor | None): An instance of a custom predictor class for making predictions. predictor (BasePredictor | None): An instance of a custom predictor class for making predictions.
If None, the method uses a default predictor. If None, the method uses a default predictor.
**kwargs (Any): Additional keyword arguments for configuring the prediction process. **kwargs: Additional keyword arguments for configuring the prediction process.
Returns: Returns:
(List[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a (List[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a
@ -562,7 +562,7 @@ class Model(nn.Module):
source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None, source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
stream: bool = False, stream: bool = False,
persist: bool = False, persist: bool = False,
**kwargs, **kwargs: Any,
) -> List[Results]: ) -> List[Results]:
""" """
Conducts object tracking on the specified input source using the registered trackers. Conducts object tracking on the specified input source using the registered trackers.
@ -576,7 +576,7 @@ class Model(nn.Module):
tracking. Can be a file path, URL, or video stream. tracking. Can be a file path, URL, or video stream.
stream (bool): If True, treats the input source as a continuous video stream. Defaults to False. stream (bool): If True, treats the input source as a continuous video stream. Defaults to False.
persist (bool): If True, persists trackers between different calls to this method. Defaults to False. persist (bool): If True, persists trackers between different calls to this method. Defaults to False.
**kwargs (Any): Additional keyword arguments for configuring the tracking process. **kwargs: Additional keyword arguments for configuring the tracking process.
Returns: Returns:
(List[ultralytics.engine.results.Results]): A list of tracking results, each a Results object. (List[ultralytics.engine.results.Results]): A list of tracking results, each a Results object.
@ -607,7 +607,7 @@ class Model(nn.Module):
def val( def val(
self, self,
validator=None, validator=None,
**kwargs, **kwargs: Any,
): ):
""" """
Validates the model using a specified dataset and validation configuration. Validates the model using a specified dataset and validation configuration.
@ -619,7 +619,7 @@ class Model(nn.Module):
Args: Args:
validator (ultralytics.engine.validator.BaseValidator | None): An instance of a custom validator class for validator (ultralytics.engine.validator.BaseValidator | None): An instance of a custom validator class for
validating the model. validating the model.
**kwargs (Any): Arbitrary keyword arguments for customizing the validation process. **kwargs: Arbitrary keyword arguments for customizing the validation process.
Returns: Returns:
(ultralytics.utils.metrics.DetMetrics): Validation metrics obtained from the validation process. (ultralytics.utils.metrics.DetMetrics): Validation metrics obtained from the validation process.
@ -642,7 +642,7 @@ class Model(nn.Module):
def benchmark( def benchmark(
self, self,
**kwargs, **kwargs: Any,
): ):
""" """
Benchmarks the model across various export formats to evaluate performance. Benchmarks the model across various export formats to evaluate performance.
@ -653,7 +653,7 @@ class Model(nn.Module):
defaults, and any additional user-provided keyword arguments. defaults, and any additional user-provided keyword arguments.
Args: Args:
**kwargs (Any): Arbitrary keyword arguments to customize the benchmarking process. These are combined with **kwargs: Arbitrary keyword arguments to customize the benchmarking process. These are combined with
default configurations, model-specific arguments, and method defaults. Common options include: default configurations, model-specific arguments, and method defaults. Common options include:
- data (str): Path to the dataset for benchmarking. - data (str): Path to the dataset for benchmarking.
- imgsz (int | List[int]): Image size for benchmarking. - imgsz (int | List[int]): Image size for benchmarking.
@ -691,7 +691,7 @@ class Model(nn.Module):
def export( def export(
self, self,
**kwargs, **kwargs: Any,
) -> str: ) -> str:
""" """
Exports the model to a different format suitable for deployment. Exports the model to a different format suitable for deployment.
@ -701,7 +701,7 @@ class Model(nn.Module):
defaults, and any additional arguments provided. defaults, and any additional arguments provided.
Args: Args:
**kwargs (Dict): Arbitrary keyword arguments to customize the export process. These are combined with **kwargs: Arbitrary keyword arguments to customize the export process. These are combined with
the model's overrides and method defaults. Common arguments include: the model's overrides and method defaults. Common arguments include:
format (str): Export format (e.g., 'onnx', 'engine', 'coreml'). format (str): Export format (e.g., 'onnx', 'engine', 'coreml').
half (bool): Export model in half-precision. half (bool): Export model in half-precision.
@ -740,7 +740,7 @@ class Model(nn.Module):
def train( def train(
self, self,
trainer=None, trainer=None,
**kwargs, **kwargs: Any,
): ):
""" """
Trains the model using the specified dataset and training configuration. Trains the model using the specified dataset and training configuration.
@ -755,7 +755,7 @@ class Model(nn.Module):
Args: Args:
trainer (BaseTrainer | None): Custom trainer instance for model training. If None, uses default. trainer (BaseTrainer | None): Custom trainer instance for model training. If None, uses default.
**kwargs (Any): Arbitrary keyword arguments for training configuration. Common options include: **kwargs: Arbitrary keyword arguments for training configuration. Common options include:
data (str): Path to dataset configuration file. data (str): Path to dataset configuration file.
epochs (int): Number of training epochs. epochs (int): Number of training epochs.
batch_size (int): Batch size for training. batch_size (int): Batch size for training.
@ -816,8 +816,8 @@ class Model(nn.Module):
self, self,
use_ray=False, use_ray=False,
iterations=10, iterations=10,
*args, *args: Any,
**kwargs, **kwargs: Any,
): ):
""" """
Conducts hyperparameter tuning for the model, with an option to use Ray Tune. Conducts hyperparameter tuning for the model, with an option to use Ray Tune.
@ -830,8 +830,8 @@ class Model(nn.Module):
Args: Args:
use_ray (bool): If True, uses Ray Tune for hyperparameter tuning. Defaults to False. use_ray (bool): If True, uses Ray Tune for hyperparameter tuning. Defaults to False.
iterations (int): The number of tuning iterations to perform. Defaults to 10. iterations (int): The number of tuning iterations to perform. Defaults to 10.
*args (List): Variable length argument list for additional arguments. *args: Variable length argument list for additional arguments.
**kwargs (Dict): Arbitrary keyword arguments. These are combined with the model's overrides and defaults. **kwargs: Arbitrary keyword arguments. These are combined with the model's overrides and defaults.
Returns: Returns:
(Dict): A dictionary containing the results of the hyperparameter search. (Dict): A dictionary containing the results of the hyperparameter search.

View file

@ -2,6 +2,7 @@
import io import io
import time import time
from typing import Any
import cv2 import cv2
@ -37,16 +38,16 @@ class Inference:
inference: Performs real-time object detection inference. inference: Performs real-time object detection inference.
Examples: Examples:
>>> inf = solutions.Inference(model="path/to/model/file.pt") # Model is not necessary argument. >>> inf = solutions.Inference(model="path/to/model.pt") # Model is not necessary argument.
>>> inf.inference() >>> inf.inference()
""" """
def __init__(self, **kwargs): def __init__(self, **kwargs: Any):
""" """
Initializes the Inference class, checking Streamlit requirements and setting up the model path. Initializes the Inference class, checking Streamlit requirements and setting up the model path.
Args: Args:
**kwargs (Dict): Additional keyword arguments for model configuration. **kwargs (Any): Additional keyword arguments for model configuration.
""" """
check_requirements("streamlit>=1.29.0") # scope imports for faster ultralytics package load speeds check_requirements("streamlit>=1.29.0") # scope imports for faster ultralytics package load speeds
import streamlit as st import streamlit as st