Reference for ultralytics/utils/__init__.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/utils/init.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.utils.TQDM
Bases: tqdm
Custom Ultralytics tqdm class with different default arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args |
list
|
Positional arguments passed to original tqdm. |
()
|
**kwargs |
any
|
Keyword arguments, with custom defaults applied. |
{}
|
Source code in ultralytics/utils/__init__.py
__init__(*args, **kwargs)
Initialize custom Ultralytics tqdm class with different default arguments.
Note these can still be overridden when calling TQDM.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.SimpleClass
Ultralytics SimpleClass is a base class providing helpful string representation, error reporting, and attribute access methods for easier debugging and usage.
Source code in ultralytics/utils/__init__.py
__getattr__(attr)
Custom attribute access error message with helpful information.
Source code in ultralytics/utils/__init__.py
__repr__()
__str__()
Return a human-readable string representation of the object.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.IterableSimpleNamespace
Bases: SimpleNamespace
Ultralytics IterableSimpleNamespace is an extension class of SimpleNamespace that adds iterable functionality and enables usage with dict() and for loops.
Source code in ultralytics/utils/__init__.py
__getattr__(attr)
Custom attribute access error message with helpful information.
Source code in ultralytics/utils/__init__.py
__iter__()
__str__()
get(key, default=None)
Return the value of the specified key if it exists; otherwise, return the default value.
ultralytics.utils.ThreadingLocked
A decorator class for ensuring thread-safe execution of a function or method. This class can be used as a decorator to make sure that if the decorated function is called from multiple threads, only one thread at a time will be able to execute the function.
Attributes:
Name | Type | Description |
---|---|---|
lock |
Lock
|
A lock object used to manage access to the decorated function. |
Example
Source code in ultralytics/utils/__init__.py
__call__(f)
Run thread-safe execution of function or method.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.TryExcept
Bases: ContextDecorator
Ultralytics TryExcept class. Use as @TryExcept() decorator or 'with TryExcept():' context manager.
Examples:
As a decorator:
>>> @TryExcept(msg="Error occurred in func", verbose=True)
>>> def func():
>>> # Function logic here
>>> pass
As a context manager:
Source code in ultralytics/utils/__init__.py
__enter__()
__exit__(exc_type, value, traceback)
Defines behavior when exiting a 'with' block, prints error message if necessary.
__init__(msg='', verbose=True)
ultralytics.utils.Retry
Bases: ContextDecorator
Retry class for function execution with exponential backoff.
Can be used as a decorator or a context manager to retry a function or block of code on exceptions, up to a specified number of times with an exponentially increasing delay between retries.
Examples:
Example usage as a decorator:
>>> @Retry(times=3, delay=2)
>>> def test_func():
>>> # Replace with function logic that may raise exceptions
>>> return True
Example usage as a context manager:
Source code in ultralytics/utils/__init__.py
__call__(func)
Decorator implementation for Retry with exponential backoff.
Source code in ultralytics/utils/__init__.py
__enter__()
__exit__(exc_type, exc_value, traceback)
Exit the runtime context related to this object with exponential backoff.
Source code in ultralytics/utils/__init__.py
__init__(times=3, delay=2)
ultralytics.utils.SettingsManager
Bases: dict
Manages Ultralytics settings stored in a YAML file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file |
str | Path
|
Path to the Ultralytics settings YAML file. Default is USER_CONFIG_DIR / 'settings.yaml'. |
SETTINGS_YAML
|
version |
str
|
Settings version. In case of local version mismatch, new default settings will be saved. |
'0.0.4'
|
Source code in ultralytics/utils/__init__.py
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 |
|
__init__(file=SETTINGS_YAML, version='0.0.4')
Initialize the SettingsManager with default settings, load and validate current settings from the YAML file.
Source code in ultralytics/utils/__init__.py
load()
reset()
save()
ultralytics.utils.plt_settings(rcparams=None, backend='Agg')
Decorator to temporarily set rc parameters and the backend for a plotting function.
Example
decorator: @plt_settings({"font.size": 12}) context manager: with plt_settings({"font.size": 12}):
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rcparams |
dict
|
Dictionary of rc parameters to set. |
None
|
backend |
str
|
Name of the backend to use. Defaults to 'Agg'. |
'Agg'
|
Returns:
Type | Description |
---|---|
Callable
|
Decorated function with temporarily set rc parameters and backend. This decorator can be applied to any function that needs to have specific matplotlib rc parameters and backend for its execution. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.set_logging(name='LOGGING_NAME', verbose=True)
Sets up logging for the given name with UTF-8 encoding support, ensuring compatibility across different environments.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.emojis(string='')
ultralytics.utils.yaml_save(file='data.yaml', data=None, header='')
Save YAML data to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file |
str
|
File name. Default is 'data.yaml'. |
'data.yaml'
|
data |
dict
|
Data to save in YAML format. |
None
|
header |
str
|
YAML header to add. |
''
|
Returns:
Type | Description |
---|---|
None
|
Data is saved to the specified file. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.yaml_load(file='data.yaml', append_filename=False)
Load YAML data from a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file |
str
|
File name. Default is 'data.yaml'. |
'data.yaml'
|
append_filename |
bool
|
Add the YAML filename to the YAML dictionary. Default is False. |
False
|
Returns:
Type | Description |
---|---|
dict
|
YAML data and file name. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.yaml_print(yaml_file)
Pretty prints a YAML file or a YAML-formatted dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
yaml_file |
Union[str, Path, dict]
|
The file path of the YAML file or a YAML-formatted dictionary. |
required |
Returns:
Type | Description |
---|---|
None
|
(None) |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.read_device_model()
Reads the device model information from the system and caches it for quick access. Used by is_jetson() and is_raspberrypi().
Returns:
Type | Description |
---|---|
str
|
Model file contents if read successfully or empty string otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_ubuntu()
Check if the OS is Ubuntu.
Returns:
Type | Description |
---|---|
bool
|
True if OS is Ubuntu, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_colab()
Check if the current script is running inside a Google Colab notebook.
Returns:
Type | Description |
---|---|
bool
|
True if running inside a Colab notebook, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_kaggle()
Check if the current script is running inside a Kaggle kernel.
Returns:
Type | Description |
---|---|
bool
|
True if running inside a Kaggle kernel, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_jupyter()
Check if the current script is running inside a Jupyter Notebook. Verified on Colab, Jupyterlab, Kaggle, Paperspace.
Returns:
Type | Description |
---|---|
bool
|
True if running inside a Jupyter Notebook, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_docker()
Determine if the script is running inside a Docker container.
Returns:
Type | Description |
---|---|
bool
|
True if the script is running inside a Docker container, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_raspberrypi()
Determines if the Python environment is running on a Raspberry Pi by checking the device model information.
Returns:
Type | Description |
---|---|
bool
|
True if running on a Raspberry Pi, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_jetson()
Determines if the Python environment is running on a Jetson Nano or Jetson Orin device by checking the device model information.
Returns:
Type | Description |
---|---|
bool
|
True if running on a Jetson Nano or Jetson Orin, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_online()
Check internet connectivity by attempting to connect to a known online host.
Returns:
Type | Description |
---|---|
bool
|
True if connection is successful, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_pip_package(filepath=__name__)
Determines if the file at the given filepath is part of a pip package.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath |
str
|
The filepath to check. |
__name__
|
Returns:
Type | Description |
---|---|
bool
|
True if the file is part of a pip package, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_dir_writeable(dir_path)
Check if a directory is writeable.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dir_path |
str | Path
|
The path to the directory. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the directory is writeable, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_pytest_running()
Determines whether pytest is currently running or not.
Returns:
Type | Description |
---|---|
bool
|
True if pytest is running, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_github_action_running()
Determine if the current environment is a GitHub Actions runner.
Returns:
Type | Description |
---|---|
bool
|
True if the current environment is a GitHub Actions runner, False otherwise. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.get_git_dir()
Determines whether the current file is part of a git repository and if so, returns the repository root directory. If the current file is not part of a git repository, returns None.
Returns:
Type | Description |
---|---|
Path | None
|
Git root directory if found or None if not found. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.is_git_dir()
Determines whether the current file is part of a git repository. If the current file is not part of a git repository, returns None.
Returns:
Type | Description |
---|---|
bool
|
True if current file is part of a git repository. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.get_git_origin_url()
Retrieves the origin URL of a git repository.
Returns:
Type | Description |
---|---|
str | None
|
The origin URL of the git repository or None if not git directory. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.get_git_branch()
Returns the current git branch name. If not in a git repository, returns None.
Returns:
Type | Description |
---|---|
str | None
|
The current git branch name or None if not a git directory. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.get_default_args(func)
Returns a dictionary of default arguments for a function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func |
callable
|
The function to inspect. |
required |
Returns:
Type | Description |
---|---|
dict
|
A dictionary where each key is a parameter name, and each value is the default value of that parameter. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.get_ubuntu_version()
Retrieve the Ubuntu version if the OS is Ubuntu.
Returns:
Type | Description |
---|---|
str
|
Ubuntu version or None if not an Ubuntu OS. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.get_user_config_dir(sub_dir='Ultralytics')
Return the appropriate config directory based on the environment operating system.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sub_dir |
str
|
The name of the subdirectory to create. |
'Ultralytics'
|
Returns:
Type | Description |
---|---|
Path
|
The path to the user config directory. |
Source code in ultralytics/utils/__init__.py
ultralytics.utils.colorstr(*input)
Colors a string based on the provided color and style arguments. Utilizes ANSI escape codes. See https://en.wikipedia.org/wiki/ANSI_escape_code for more details.
This function can be called in two ways
- colorstr('color', 'style', 'your string')
- colorstr('your string')
In the second form, 'blue' and 'bold' will be applied by default.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*input |
str
|
A sequence of strings where the first n-1 strings are color and style arguments, and the last string is the one to be colored. |
()
|
Supported Colors and Styles
Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow', 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white' Misc: 'end', 'bold', 'underline'
Returns:
Type | Description |
---|---|
str
|
The input string wrapped with ANSI escape codes for the specified color and style. |
Examples:
Source code in ultralytics/utils/__init__.py
ultralytics.utils.remove_colorstr(input_string)
Removes ANSI escape codes from a string, effectively un-coloring it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_string |
str
|
The string to remove color and style from. |
required |
Returns:
Type | Description |
---|---|
str
|
A new string with all ANSI escape codes removed. |
Examples:
Source code in ultralytics/utils/__init__.py
ultralytics.utils.threaded(func)
Multi-threads a target function by default and returns the thread or function result.
Use as @threaded decorator. The function runs in a separate thread unless 'threaded=False' is passed.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.set_sentry()
Initialize the Sentry SDK for error tracking and reporting. Only used if sentry_sdk package is installed and sync=True in settings. Run 'yolo settings' to see and update settings YAML file.
Conditions required to send errors (ALL conditions must be met or no errors will be reported): - sentry_sdk package is installed - sync=True in YOLO settings - pytest is not running - running in a pip package installation - running in a non-git directory - running with rank -1 or 0 - online environment - CLI used to run package (checked with 'yolo' as the name of the main CLI command)
The function also configures Sentry SDK to ignore KeyboardInterrupt and FileNotFoundError exceptions and to exclude events with 'out of memory' in their exception message.
Additionally, the function sets custom tags and user information for Sentry events.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.deprecation_warn(arg, new_arg, version=None)
Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.clean_url(url)
Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt.