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
A custom TQDM progress bar class that extends the original tqdm functionality.
This class modifies the behavior of the original tqdm progress bar based on global settings and provides additional customization options.
Attributes:
Name | Type | Description |
---|---|---|
disable |
bool
|
Whether to disable the progress bar. Determined by the global VERBOSE setting and any passed 'disable' argument. |
bar_format |
str
|
The format string for the progress bar. Uses the global TQDM_BAR_FORMAT if not explicitly set. |
Methods:
Name | Description |
---|
Examples:
>>> from ultralytics.utils import TQDM
>>> for i in TQDM(range(100)):
... # Your processing code here
... pass
This class extends the original tqdm class to provide customized behavior for Ultralytics projects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
Variable length argument list to be passed to the original tqdm constructor. |
()
|
**kwargs
|
Any
|
Arbitrary keyword arguments to be passed to the original tqdm constructor. |
{}
|
Notes
- The progress bar is disabled if VERBOSE is False or if 'disable' is explicitly set to True in kwargs.
- The default bar format is set to TQDM_BAR_FORMAT unless overridden in kwargs.
Examples:
Source code in ultralytics/utils/__init__.py
ultralytics.utils.SimpleClass
A simple base class for creating objects with string representations of their attributes.
This class provides a foundation for creating objects that can be easily printed or represented as strings, showing all their non-callable attributes. It's useful for debugging and introspection of object states.
Methods:
Name | Description |
---|---|
__str__ |
Returns a human-readable string representation of the object. |
__repr__ |
Returns a machine-readable string representation of the object. |
__getattr__ |
Provides a custom attribute access error message with helpful information. |
Examples:
>>> class MyClass(SimpleClass):
... def __init__(self):
... self.x = 10
... self.y = "hello"
>>> obj = MyClass()
>>> print(obj)
__main__.MyClass object with attributes:
x: 10 y: 'hello'
Notes
- This class is designed to be subclassed. It provides a convenient way to inspect object attributes.
- The string representation includes the module and class name of the object.
- Callable attributes and attributes starting with an underscore are excluded from the string representation.
__getattr__
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
An iterable SimpleNamespace class that provides enhanced functionality for attribute access and iteration.
This class extends the SimpleNamespace class with additional methods for iteration, string representation, and attribute access. It is designed to be used as a convenient container for storing and accessing configuration parameters.
Methods:
Name | Description |
---|---|
__iter__ |
Returns an iterator of key-value pairs from the namespace's attributes. |
__str__ |
Returns a human-readable string representation of the object. |
__getattr__ |
Provides a custom attribute access error message with helpful information. |
get |
Retrieves the value of a specified key, or a default value if the key doesn't exist. |
Examples:
>>> cfg = IterableSimpleNamespace(a=1, b=2, c=3)
>>> for k, v in cfg:
... print(f"{k}: {v}")
a: 1
b: 2
c: 3
>>> print(cfg)
a=1
b=2
c=3
>>> cfg.get("b")
2
>>> cfg.get("d", "default")
'default'
Notes
This class is particularly useful for storing configuration parameters in a more accessible and iterable format compared to a standard dictionary.
__getattr__
Custom attribute access error message with helpful information.
Source code in ultralytics/utils/__init__.py
__iter__
__str__
get
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__
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__
Defines behavior when exiting a 'with' block, prints error message if necessary.
ultralytics.utils.Retry
Bases: ContextDecorator
Retry class for function execution with exponential backoff.
Can be used as a decorator to retry a function 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
Source code in ultralytics/utils/__init__.py
__call__
Decorator implementation for Retry with exponential backoff.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.JSONDict
Bases: dict
A dictionary-like class that provides JSON persistence for its contents.
This class extends the built-in dictionary to automatically save its contents to a JSON file whenever they are modified. It ensures thread-safe operations using a lock.
Attributes:
Name | Type | Description |
---|---|---|
file_path |
Path
|
The path to the JSON file used for persistence. |
lock |
Lock
|
A lock object to ensure thread-safe operations. |
Methods:
Name | Description |
---|---|
_load |
Loads the data from the JSON file into the dictionary. |
_save |
Saves the current state of the dictionary to the JSON file. |
__setitem__ |
Stores a key-value pair and persists it to disk. |
__delitem__ |
Removes an item and updates the persistent storage. |
update |
Updates the dictionary and persists changes. |
clear |
Clears all entries and updates the persistent storage. |
Examples:
>>> json_dict = JSONDict("data.json")
>>> json_dict["key"] = "value"
>>> print(json_dict["key"])
value
>>> del json_dict["key"]
>>> json_dict.update({"new_key": "new_value"})
>>> json_dict.clear()
Source code in ultralytics/utils/__init__.py
__delitem__
__setitem__
__str__
Return a pretty-printed JSON string representation of the dictionary.
clear
ultralytics.utils.SettingsManager
Bases: JSONDict
SettingsManager class for managing and persisting Ultralytics settings.
This class extends JSONDict to provide JSON persistence for settings, ensuring thread-safe operations and default values. It validates settings on initialization and provides methods to update or reset settings.
Attributes:
Name | Type | Description |
---|---|---|
file |
Path
|
The path to the JSON file used for persistence. |
version |
str
|
The version of the settings schema. |
defaults |
Dict
|
A dictionary containing default settings. |
help_msg |
str
|
A help message for users on how to view and update settings. |
Methods:
Name | Description |
---|---|
_validate_settings |
Validates the current settings and resets if necessary. |
update |
Updates settings, validating keys and types. |
reset |
Resets the settings to default and saves them. |
Examples:
Initialize and update settings:
>>> settings = SettingsManager()
>>> settings.update(runs_dir="/new/runs/dir")
>>> print(settings["runs_dir"])
/new/runs/dir
Source code in ultralytics/utils/__init__.py
reset
update
Updates settings, validating keys and types.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.plt_settings
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
Sets up logging with UTF-8 encoding and configurable verbosity.
This function configures logging for the Ultralytics library, setting the appropriate logging level and formatter based on the verbosity flag and the current process rank. It handles special cases for Windows environments where UTF-8 encoding might not be the default.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name of the logger. Defaults to "LOGGING_NAME". |
'LOGGING_NAME'
|
verbose
|
bool
|
Flag to set logging level to INFO if True, ERROR otherwise. Defaults to True. |
True
|
Examples:
>>> set_logging(name="ultralytics", verbose=True)
>>> logger = logging.getLogger("ultralytics")
>>> logger.info("This is an info message")
Notes
- On Windows, this function attempts to reconfigure stdout to use UTF-8 encoding if possible.
- If reconfiguration is not possible, it falls back to a custom formatter that handles non-UTF-8 environments.
- The function sets up a StreamHandler with the appropriate formatter and level.
- The logger's propagate flag is set to False to prevent duplicate logging in parent loggers.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.emojis
ultralytics.utils.yaml_save
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
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
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.
Returns:
Type | Description |
---|---|
bool
|
True if running inside a Jupyter Notebook, False otherwise. |
Note
- Only works on Colab and Kaggle, other environments like Jupyterlab and Paperspace are not reliably detectable.
- "get_ipython" in globals() method suffers false positives when IPython package installed manually.
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 an NVIDIA Jetson device by checking the device model information.
Returns:
Type | Description |
---|---|
bool
|
True if running on an NVIDIA Jetson device, 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
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
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
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
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
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 | Path
|
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
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
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.
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
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 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 |
|
ultralytics.utils.deprecation_warn
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
Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt.
Source code in ultralytics/utils/__init__.py
ultralytics.utils.url2file
Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt.
ultralytics.utils.vscode_msg
Display a message to install Ultralytics-Snippets for VS Code if not already installed.