Skip to content

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

TQDM(*args, **kwargs)

Bases: tqdm if TQDM_RICH else 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:

>>> from ultralytics.utils import TQDM
>>> for i in TQDM(range(100)):
...     # Your code here
...     pass
Source code in ultralytics/utils/__init__.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def __init__(self, *args, **kwargs):
    """
    Initializes a custom TQDM progress bar.

    This class extends the original tqdm class to provide customized behavior for Ultralytics projects.

    Args:
        *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:
        >>> from ultralytics.utils import TQDM
        >>> for i in TQDM(range(100)):
        ...     # Your code here
        ...     pass
    """
    warnings.filterwarnings("ignore", category=tqdm.TqdmExperimentalWarning)  # suppress tqdm.rich warning
    kwargs["disable"] = not VERBOSE or kwargs.get("disable", False)
    kwargs.setdefault("bar_format", TQDM_BAR_FORMAT)  # override default value if passed
    super().__init__(*args, **kwargs)





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__

__getattr__(attr)

Custom attribute access error message with helpful information.

Source code in ultralytics/utils/__init__.py
238
239
240
241
def __getattr__(self, attr):
    """Custom attribute access error message with helpful information."""
    name = self.__class__.__name__
    raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")

__repr__

__repr__()

Return a machine-readable string representation of the object.

Source code in ultralytics/utils/__init__.py
234
235
236
def __repr__(self):
    """Return a machine-readable string representation of the object."""
    return self.__str__()

__str__

__str__()

Return a human-readable string representation of the object.

Source code in ultralytics/utils/__init__.py
220
221
222
223
224
225
226
227
228
229
230
231
232
def __str__(self):
    """Return a human-readable string representation of the object."""
    attr = []
    for a in dir(self):
        v = getattr(self, a)
        if not callable(v) and not a.startswith("_"):
            if isinstance(v, SimpleClass):
                # Display only the module and class name for subclasses
                s = f"{a}: {v.__module__}.{v.__class__.__name__} object"
            else:
                s = f"{a}: {repr(v)}"
            attr.append(s)
    return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr)





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__

__getattr__(attr)

Custom attribute access error message with helpful information.

Source code in ultralytics/utils/__init__.py
287
288
289
290
291
292
293
294
295
296
297
def __getattr__(self, attr):
    """Custom attribute access error message with helpful information."""
    name = self.__class__.__name__
    raise AttributeError(
        f"""
        '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics
        'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace
        {DEFAULT_CFG_PATH} with the latest version from
        https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
        """
    )

__iter__

__iter__()

Return an iterator of key-value pairs from the namespace's attributes.

Source code in ultralytics/utils/__init__.py
279
280
281
def __iter__(self):
    """Return an iterator of key-value pairs from the namespace's attributes."""
    return iter(vars(self).items())

__str__

__str__()

Return a human-readable string representation of the object.

Source code in ultralytics/utils/__init__.py
283
284
285
def __str__(self):
    """Return a human-readable string representation of the object."""
    return "\n".join(f"{k}={v}" for k, v in vars(self).items())

get

get(key, default=None)

Return the value of the specified key if it exists; otherwise, return the default value.

Source code in ultralytics/utils/__init__.py
299
300
301
def get(self, key, default=None):
    """Return the value of the specified key if it exists; otherwise, return the default value."""
    return getattr(self, key, default)





ultralytics.utils.ThreadingLocked

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.

Examples:

>>> from ultralytics.utils import ThreadingLocked
>>> @ThreadingLocked()
>>> def my_function():
...    # Your code here
Source code in ultralytics/utils/__init__.py
456
457
458
def __init__(self):
    """Initialize the decorator class with a threading lock."""
    self.lock = threading.Lock()

__call__

__call__(f)

Run thread-safe execution of function or method.

Source code in ultralytics/utils/__init__.py
460
461
462
463
464
465
466
467
468
469
470
def __call__(self, f):
    """Run thread-safe execution of function or method."""
    from functools import wraps

    @wraps(f)
    def decorated(*args, **kwargs):
        """Applies thread-safety to the decorated function or method."""
        with self.lock:
            return f(*args, **kwargs)

    return decorated





ultralytics.utils.TryExcept

TryExcept(msg='', verbose=True)

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:

>>> with TryExcept(msg="Error occurred in block", verbose=True):
>>> # Code block here
>>>     pass
Source code in ultralytics/utils/__init__.py
946
947
948
949
def __init__(self, msg="", verbose=True):
    """Initialize TryExcept class with optional message and verbosity settings."""
    self.msg = msg
    self.verbose = verbose

__enter__

__enter__()

Executes when entering TryExcept context, initializes instance.

Source code in ultralytics/utils/__init__.py
951
952
953
def __enter__(self):
    """Executes when entering TryExcept context, initializes instance."""
    pass

__exit__

__exit__(exc_type, value, traceback)

Defines behavior when exiting a 'with' block, prints error message if necessary.

Source code in ultralytics/utils/__init__.py
955
956
957
958
959
def __exit__(self, exc_type, value, traceback):
    """Defines behavior when exiting a 'with' block, prints error message if necessary."""
    if self.verbose and value:
        LOGGER.warning(f"{self.msg}{': ' if self.msg else ''}{value}")
    return True





ultralytics.utils.Retry

Retry(times=3, delay=2)

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
977
978
979
980
981
def __init__(self, times=3, delay=2):
    """Initialize Retry class with specified number of retries and delay."""
    self.times = times
    self.delay = delay
    self._attempts = 0

__call__

__call__(func)

Decorator implementation for Retry with exponential backoff.

Source code in ultralytics/utils/__init__.py
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
def __call__(self, func):
    """Decorator implementation for Retry with exponential backoff."""

    def wrapped_func(*args, **kwargs):
        """Applies retries to the decorated function or method."""
        self._attempts = 0
        while self._attempts < self.times:
            try:
                return func(*args, **kwargs)
            except Exception as e:
                self._attempts += 1
                LOGGER.warning(f"Retry {self._attempts}/{self.times} failed: {e}")
                if self._attempts >= self.times:
                    raise e
                time.sleep(self.delay * (2**self._attempts))  # exponential backoff delay

    return wrapped_func





ultralytics.utils.JSONDict

JSONDict(file_path: Union[str, Path] = 'data.json')

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
1136
1137
1138
1139
1140
1141
def __init__(self, file_path: Union[str, Path] = "data.json"):
    """Initialize a JSONDict object with a specified file path for JSON persistence."""
    super().__init__()
    self.file_path = Path(file_path)
    self.lock = Lock()
    self._load()

__delitem__

__delitem__(key)

Remove an item and update the persistent storage.

Source code in ultralytics/utils/__init__.py
1176
1177
1178
1179
1180
def __delitem__(self, key):
    """Remove an item and update the persistent storage."""
    with self.lock:
        super().__delitem__(key)
        self._save()

__setitem__

__setitem__(key, value)

Store a key-value pair and persist to disk.

Source code in ultralytics/utils/__init__.py
1170
1171
1172
1173
1174
def __setitem__(self, key, value):
    """Store a key-value pair and persist to disk."""
    with self.lock:
        super().__setitem__(key, value)
        self._save()

__str__

__str__()

Return a pretty-printed JSON string representation of the dictionary.

Source code in ultralytics/utils/__init__.py
1182
1183
1184
1185
def __str__(self):
    """Return a pretty-printed JSON string representation of the dictionary."""
    contents = json.dumps(dict(self), indent=2, ensure_ascii=False, default=self._json_default)
    return f'JSONDict("{self.file_path}"):\n{contents}'

clear

clear()

Clear all entries and update the persistent storage.

Source code in ultralytics/utils/__init__.py
1193
1194
1195
1196
1197
def clear(self):
    """Clear all entries and update the persistent storage."""
    with self.lock:
        super().clear()
        self._save()

update

update(*args, **kwargs)

Update the dictionary and persist changes.

Source code in ultralytics/utils/__init__.py
1187
1188
1189
1190
1191
def update(self, *args, **kwargs):
    """Update the dictionary and persist changes."""
    with self.lock:
        super().update(*args, **kwargs)
        self._save()





ultralytics.utils.SettingsManager

SettingsManager(file=SETTINGS_FILE, version='0.0.6')

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
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
def __init__(self, file=SETTINGS_FILE, version="0.0.6"):
    """Initializes the SettingsManager with default settings and loads user settings."""
    import hashlib

    from ultralytics.utils.torch_utils import torch_distributed_zero_first

    root = GIT_DIR or Path()
    datasets_root = (root.parent if GIT_DIR and is_dir_writeable(root.parent) else root).resolve()

    self.file = Path(file)
    self.version = version
    self.defaults = {
        "settings_version": version,  # Settings schema version
        "datasets_dir": str(datasets_root / "datasets"),  # Datasets directory
        "weights_dir": str(root / "weights"),  # Model weights directory
        "runs_dir": str(root / "runs"),  # Experiment runs directory
        "uuid": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(),  # SHA-256 anonymized UUID hash
        "sync": True,  # Enable synchronization
        "api_key": "",  # Ultralytics API Key
        "openai_api_key": "",  # OpenAI API Key
        "clearml": True,  # ClearML integration
        "comet": True,  # Comet integration
        "dvc": True,  # DVC integration
        "hub": True,  # Ultralytics HUB integration
        "mlflow": True,  # MLflow integration
        "neptune": True,  # Neptune integration
        "raytune": True,  # Ray Tune integration
        "tensorboard": False,  # TensorBoard logging
        "wandb": False,  # Weights & Biases logging
        "vscode_msg": True,  # VSCode messaging
    }

    self.help_msg = (
        f"\nView Ultralytics Settings with 'yolo settings' or at '{self.file}'"
        "\nUpdate Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. "
        "For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings."
    )

    with torch_distributed_zero_first(LOCAL_RANK):
        super().__init__(self.file)

        if not self.file.exists() or not self:  # Check if file doesn't exist or is empty
            LOGGER.info(f"Creating new Ultralytics Settings v{version} file ✅ {self.help_msg}")
            self.reset()

        self._validate_settings()

__setitem__

__setitem__(key, value)

Updates one key: value pair.

Source code in ultralytics/utils/__init__.py
1293
1294
1295
def __setitem__(self, key, value):
    """Updates one key: value pair."""
    self.update({key: value})

reset

reset()

Resets the settings to default and saves them.

Source code in ultralytics/utils/__init__.py
1312
1313
1314
1315
def reset(self):
    """Resets the settings to default and saves them."""
    self.clear()
    self.update(self.defaults)

update

update(*args, **kwargs)

Updates settings, validating keys and types.

Source code in ultralytics/utils/__init__.py
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
def update(self, *args, **kwargs):
    """Updates settings, validating keys and types."""
    for arg in args:
        if isinstance(arg, dict):
            kwargs.update(arg)
    for k, v in kwargs.items():
        if k not in self.defaults:
            raise KeyError(f"No Ultralytics setting '{k}'. {self.help_msg}")
        t = type(self.defaults[k])
        if not isinstance(v, t):
            raise TypeError(
                f"Ultralytics setting '{k}' must be '{t.__name__}' type, not '{type(v).__name__}'. {self.help_msg}"
            )
    super().update(*args, **kwargs)





ultralytics.utils.plt_settings

plt_settings(rcparams=None, backend='Agg')

Decorator to temporarily set rc parameters and the backend for a plotting function.

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.

Examples:

>>> @plt_settings({"font.size": 12})
>>> def plot_function():
...     plt.figure()
...     plt.plot([1, 2, 3])
...     plt.show()
>>> with plt_settings({"font.size": 12}):
...     plt.figure()
...     plt.plot([1, 2, 3])
...     plt.show()
Source code in ultralytics/utils/__init__.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
def plt_settings(rcparams=None, backend="Agg"):
    """
    Decorator to temporarily set rc parameters and the backend for a plotting function.

    Args:
        rcparams (dict, optional): Dictionary of rc parameters to set.
        backend (str, optional): Name of the backend to use. Defaults to 'Agg'.

    Returns:
        (Callable): Decorated function with temporarily set rc parameters and backend.

    Examples:
        >>> @plt_settings({"font.size": 12})
        >>> def plot_function():
        ...     plt.figure()
        ...     plt.plot([1, 2, 3])
        ...     plt.show()

        >>> with plt_settings({"font.size": 12}):
        ...     plt.figure()
        ...     plt.plot([1, 2, 3])
        ...     plt.show()
    """
    if rcparams is None:
        rcparams = {"font.size": 11}

    def decorator(func):
        """Decorator to apply temporary rc parameters and backend to a function."""

        def wrapper(*args, **kwargs):
            """Sets rc parameters and backend, calls the original function, and restores the settings."""
            original_backend = plt.get_backend()
            switch = backend.lower() != original_backend.lower()
            if switch:
                plt.close("all")  # auto-close()ing of figures upon backend switching is deprecated since 3.8
                plt.switch_backend(backend)

            # Plot with backend and always revert to original backend
            try:
                with plt.rc_context(rcparams):
                    result = func(*args, **kwargs)
            finally:
                if switch:
                    plt.close("all")
                    plt.switch_backend(original_backend)
            return result

        return wrapper

    return decorator





ultralytics.utils.set_logging

set_logging(name='LOGGING_NAME', verbose=True)

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

Returns:

Type Description
Logger

Configured logger object.

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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
def set_logging(name="LOGGING_NAME", verbose=True):
    """
    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.

    Args:
        name (str): Name of the logger. Defaults to "LOGGING_NAME".
        verbose (bool): Flag to set logging level to INFO if True, ERROR otherwise. Defaults to True.

    Returns:
        (logging.Logger): Configured logger object.

    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.
    """
    level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR  # rank in world for Multi-GPU trainings

    class PrefixFormatter(logging.Formatter):
        def format(self, record):
            """Format log records with prefixes based on level."""
            # Apply prefixes based on log level
            if record.levelno == logging.WARNING:
                prefix = "WARNING ⚠️" if not WINDOWS else "WARNING"
                record.msg = f"{prefix} {record.msg}"
            elif record.levelno == logging.ERROR:
                prefix = "ERROR ❌" if not WINDOWS else "ERROR"
                record.msg = f"{prefix} {record.msg}"

            # Handle emojis in message based on platform
            formatted_message = super().format(record)
            return emojis(formatted_message)

    formatter = PrefixFormatter("%(message)s")

    # Handle Windows UTF-8 encoding issues
    if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8":
        try:
            # Attempt to reconfigure stdout to use UTF-8 encoding if possible
            if hasattr(sys.stdout, "reconfigure"):
                sys.stdout.reconfigure(encoding="utf-8")
            # For environments where reconfigure is not available, wrap stdout in a TextIOWrapper
            elif hasattr(sys.stdout, "buffer"):
                import io

                sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
        except Exception:
            pass

    # Create and configure the StreamHandler with the appropriate formatter and level
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(level)

    # Set up the logger
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(stream_handler)
    logger.propagate = False
    return logger





ultralytics.utils.emojis

emojis(string='')

Return platform-dependent emoji-safe version of string.

Source code in ultralytics/utils/__init__.py
434
435
436
def emojis(string=""):
    """Return platform-dependent emoji-safe version of string."""
    return string.encode().decode("ascii", "ignore") if WINDOWS else string





ultralytics.utils.yaml_save

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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
def yaml_save(file="data.yaml", data=None, header=""):
    """
    Save YAML data to a file.

    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        data (dict): Data to save in YAML format.
        header (str, optional): YAML header to add.

    Returns:
        (None): Data is saved to the specified file.
    """
    if data is None:
        data = {}
    file = Path(file)
    if not file.parent.exists():
        # Create parent directories if they don't exist
        file.parent.mkdir(parents=True, exist_ok=True)

    # Convert Path objects to strings
    valid_types = int, float, str, bool, list, tuple, dict, type(None)
    for k, v in data.items():
        if not isinstance(v, valid_types):
            data[k] = str(v)

    # Dump data to file in YAML format
    with open(file, "w", errors="ignore", encoding="utf-8") as f:
        if header:
            f.write(header)
        yaml.safe_dump(data, f, sort_keys=False, allow_unicode=True)





ultralytics.utils.yaml_load

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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
def yaml_load(file="data.yaml", append_filename=False):
    """
    Load YAML data from a file.

    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.

    Returns:
        (dict): YAML data and file name.
    """
    assert Path(file).suffix in {".yaml", ".yml"}, f"Attempting to load non-YAML file {file} with yaml_load()"
    with open(file, errors="ignore", encoding="utf-8") as f:
        s = f.read()  # string

        # Remove special characters
        if not s.isprintable():
            s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+", "", s)

        # Add YAML filename to dict and return
        data = yaml.safe_load(s) or {}  # always return a dict (yaml.safe_load() may return None for empty files)
        if append_filename:
            data["yaml_file"] = str(file)
        return data





ultralytics.utils.yaml_print

yaml_print(yaml_file: Union[str, Path, dict]) -> None

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
531
532
533
534
535
536
537
538
539
540
541
542
543
def yaml_print(yaml_file: Union[str, Path, dict]) -> None:
    """
    Pretty prints a YAML file or a YAML-formatted dictionary.

    Args:
        yaml_file: The file path of the YAML file or a YAML-formatted dictionary.

    Returns:
        (None)
    """
    yaml_dict = yaml_load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file
    dump = yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True, width=float("inf"))
    LOGGER.info(f"Printing '{colorstr('bold', 'black', yaml_file)}'\n\n{dump}")





ultralytics.utils.read_device_model

read_device_model() -> str

Reads the device model information from the system and caches it for quick access.

Returns:

Type Description
str

Kernel release information.

Source code in ultralytics/utils/__init__.py
556
557
558
559
560
561
562
563
def read_device_model() -> str:
    """
    Reads the device model information from the system and caches it for quick access.

    Returns:
        (str): Kernel release information.
    """
    return platform.release().lower()





ultralytics.utils.is_ubuntu

is_ubuntu() -> bool

Check if the OS is Ubuntu.

Returns:

Type Description
bool

True if OS is Ubuntu, False otherwise.

Source code in ultralytics/utils/__init__.py
566
567
568
569
570
571
572
573
574
575
576
577
def is_ubuntu() -> bool:
    """
    Check if the OS is Ubuntu.

    Returns:
        (bool): True if OS is Ubuntu, False otherwise.
    """
    try:
        with open("/etc/os-release") as f:
            return "ID=ubuntu" in f.read()
    except FileNotFoundError:
        return False





ultralytics.utils.is_colab

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
580
581
582
583
584
585
586
587
def is_colab():
    """
    Check if the current script is running inside a Google Colab notebook.

    Returns:
        (bool): True if running inside a Colab notebook, False otherwise.
    """
    return "COLAB_RELEASE_TAG" in os.environ or "COLAB_BACKEND_VERSION" in os.environ





ultralytics.utils.is_kaggle

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
590
591
592
593
594
595
596
597
def is_kaggle():
    """
    Check if the current script is running inside a Kaggle kernel.

    Returns:
        (bool): True if running inside a Kaggle kernel, False otherwise.
    """
    return os.environ.get("PWD") == "/kaggle/working" and os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com"





ultralytics.utils.is_jupyter

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
600
601
602
603
604
605
606
607
608
609
610
611
def is_jupyter():
    """
    Check if the current script is running inside a Jupyter Notebook.

    Returns:
        (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.
    """
    return IS_COLAB or IS_KAGGLE





ultralytics.utils.is_runpod

is_runpod()

Check if the current script is running inside a RunPod container.

Returns:

Type Description
bool

True if running in RunPod, False otherwise.

Source code in ultralytics/utils/__init__.py
614
615
616
617
618
619
620
621
def is_runpod():
    """
    Check if the current script is running inside a RunPod container.

    Returns:
        (bool): True if running in RunPod, False otherwise.
    """
    return "RUNPOD_POD_ID" in os.environ





ultralytics.utils.is_docker

is_docker() -> bool

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
624
625
626
627
628
629
630
631
632
633
634
635
def is_docker() -> bool:
    """
    Determine if the script is running inside a Docker container.

    Returns:
        (bool): True if the script is running inside a Docker container, False otherwise.
    """
    try:
        with open("/proc/self/cgroup") as f:
            return "docker" in f.read()
    except Exception:
        return False





ultralytics.utils.is_raspberrypi

is_raspberrypi() -> bool

Determines if the Python environment is running on a Raspberry Pi.

Returns:

Type Description
bool

True if running on a Raspberry Pi, False otherwise.

Source code in ultralytics/utils/__init__.py
638
639
640
641
642
643
644
645
def is_raspberrypi() -> bool:
    """
    Determines if the Python environment is running on a Raspberry Pi.

    Returns:
        (bool): True if running on a Raspberry Pi, False otherwise.
    """
    return "rpi" in DEVICE_MODEL





ultralytics.utils.is_jetson

is_jetson() -> bool

Determines if the Python environment is running on an NVIDIA Jetson device.

Returns:

Type Description
bool

True if running on an NVIDIA Jetson device, False otherwise.

Source code in ultralytics/utils/__init__.py
648
649
650
651
652
653
654
655
def is_jetson() -> bool:
    """
    Determines if the Python environment is running on an NVIDIA Jetson device.

    Returns:
        (bool): True if running on an NVIDIA Jetson device, False otherwise.
    """
    return "tegra" in DEVICE_MODEL





ultralytics.utils.is_online

is_online() -> bool

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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def is_online() -> bool:
    """
    Check internet connectivity by attempting to connect to a known online host.

    Returns:
        (bool): True if connection is successful, False otherwise.
    """
    try:
        assert str(os.getenv("YOLO_OFFLINE", "")).lower() != "true"  # check if ENV var YOLO_OFFLINE="True"
        import socket

        for dns in ("1.1.1.1", "8.8.8.8"):  # check Cloudflare and Google DNS
            socket.create_connection(address=(dns, 80), timeout=2.0).close()
            return True
    except Exception:
        return False





ultralytics.utils.is_pip_package

is_pip_package(filepath: str = __name__) -> bool

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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
def is_pip_package(filepath: str = __name__) -> bool:
    """
    Determines if the file at the given filepath is part of a pip package.

    Args:
        filepath (str): The filepath to check.

    Returns:
        (bool): True if the file is part of a pip package, False otherwise.
    """
    import importlib.util

    # Get the spec for the module
    spec = importlib.util.find_spec(filepath)

    # Return whether the spec is not None and the origin is not None (indicating it is a package)
    return spec is not None and spec.origin is not None





ultralytics.utils.is_dir_writeable

is_dir_writeable(dir_path: Union[str, Path]) -> bool

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
695
696
697
698
699
700
701
702
703
704
705
def is_dir_writeable(dir_path: Union[str, Path]) -> bool:
    """
    Check if a directory is writeable.

    Args:
        dir_path (str | Path): The path to the directory.

    Returns:
        (bool): True if the directory is writeable, False otherwise.
    """
    return os.access(str(dir_path), os.W_OK)





ultralytics.utils.is_pytest_running

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
708
709
710
711
712
713
714
715
def is_pytest_running():
    """
    Determines whether pytest is currently running or not.

    Returns:
        (bool): True if pytest is running, False otherwise.
    """
    return ("PYTEST_CURRENT_TEST" in os.environ) or ("pytest" in sys.modules) or ("pytest" in Path(ARGV[0]).stem)





ultralytics.utils.is_github_action_running

is_github_action_running() -> bool

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
718
719
720
721
722
723
724
725
def is_github_action_running() -> bool:
    """
    Determine if the current environment is a GitHub Actions runner.

    Returns:
        (bool): True if the current environment is a GitHub Actions runner, False otherwise.
    """
    return "GITHUB_ACTIONS" in os.environ and "GITHUB_WORKFLOW" in os.environ and "RUNNER_OS" in os.environ





ultralytics.utils.get_git_dir

get_git_dir()

Determines whether the current file is part of a git repository and if so, returns the repository root directory.

Returns:

Type Description
Path | None

Git root directory if found or None if not found.

Source code in ultralytics/utils/__init__.py
728
729
730
731
732
733
734
735
736
737
def get_git_dir():
    """
    Determines whether the current file is part of a git repository and if so, returns the repository root directory.

    Returns:
        (Path | None): Git root directory if found or None if not found.
    """
    for d in Path(__file__).parents:
        if (d / ".git").is_dir():
            return d





ultralytics.utils.is_git_dir

is_git_dir()

Determines whether the current file is part of a git repository.

Returns:

Type Description
bool

True if current file is part of a git repository.

Source code in ultralytics/utils/__init__.py
740
741
742
743
744
745
746
747
def is_git_dir():
    """
    Determines whether the current file is part of a git repository.

    Returns:
        (bool): True if current file is part of a git repository.
    """
    return GIT_DIR is not None





ultralytics.utils.get_git_origin_url

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
750
751
752
753
754
755
756
757
758
759
760
761
762
def get_git_origin_url():
    """
    Retrieves the origin URL of a git repository.

    Returns:
        (str | None): The origin URL of the git repository or None if not git directory.
    """
    if IS_GIT_DIR:
        try:
            origin = subprocess.check_output(["git", "config", "--get", "remote.origin.url"])
            return origin.decode().strip()
        except subprocess.CalledProcessError:
            return None





ultralytics.utils.get_git_branch

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
765
766
767
768
769
770
771
772
773
774
775
776
777
def get_git_branch():
    """
    Returns the current git branch name. If not in a git repository, returns None.

    Returns:
        (str | None): The current git branch name or None if not a git directory.
    """
    if IS_GIT_DIR:
        try:
            origin = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"])
            return origin.decode().strip()
        except subprocess.CalledProcessError:
            return None





ultralytics.utils.get_default_args

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
780
781
782
783
784
785
786
787
788
789
790
791
def get_default_args(func):
    """
    Returns a dictionary of default arguments for a function.

    Args:
        func (callable): The function to inspect.

    Returns:
        (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.
    """
    signature = inspect.signature(func)
    return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}





ultralytics.utils.get_ubuntu_version

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
794
795
796
797
798
799
800
801
802
803
804
805
806
def get_ubuntu_version():
    """
    Retrieve the Ubuntu version if the OS is Ubuntu.

    Returns:
        (str): Ubuntu version or None if not an Ubuntu OS.
    """
    if is_ubuntu():
        try:
            with open("/etc/os-release") as f:
                return re.search(r'VERSION_ID="(\d+\.\d+)"', f.read())[1]
        except (FileNotFoundError, AttributeError):
            return None





ultralytics.utils.get_user_config_dir

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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
def get_user_config_dir(sub_dir="Ultralytics"):
    """
    Return the appropriate config directory based on the environment operating system.

    Args:
        sub_dir (str): The name of the subdirectory to create.

    Returns:
        (Path): The path to the user config directory.
    """
    if WINDOWS:
        path = Path.home() / "AppData" / "Roaming" / sub_dir
    elif MACOS:  # macOS
        path = Path.home() / "Library" / "Application Support" / sub_dir
    elif LINUX:
        path = Path.home() / ".config" / sub_dir
    else:
        raise ValueError(f"Unsupported operating system: {platform.system()}")

    # GCP and AWS lambda fix, only /tmp is writeable
    if not is_dir_writeable(path.parent):
        LOGGER.warning(
            f"user config directory '{path}' is not writeable, defaulting to '/tmp' or CWD."
            "Alternatively you can define a YOLO_CONFIG_DIR environment variable for this path."
        )
        path = Path("/tmp") / sub_dir if is_dir_writeable("/tmp") else Path().cwd() / sub_dir

    # Create the subdirectory if it does not exist
    path.mkdir(parents=True, exist_ok=True)

    return path





ultralytics.utils.colorstr

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 | 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:

>>> colorstr("blue", "bold", "hello world")
>>> "\033[34m\033[1mhello world\033[0m"
Source code in ultralytics/utils/__init__.py
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
def colorstr(*input):
    r"""
    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.

    Args:
        *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:
        (str): The input string wrapped with ANSI escape codes for the specified color and style.

    Examples:
        >>> colorstr("blue", "bold", "hello world")
        >>> "\033[34m\033[1mhello world\033[0m"
    """
    *args, string = input if len(input) > 1 else ("blue", "bold", input[0])  # color arguments, string
    colors = {
        "black": "\033[30m",  # basic colors
        "red": "\033[31m",
        "green": "\033[32m",
        "yellow": "\033[33m",
        "blue": "\033[34m",
        "magenta": "\033[35m",
        "cyan": "\033[36m",
        "white": "\033[37m",
        "bright_black": "\033[90m",  # bright colors
        "bright_red": "\033[91m",
        "bright_green": "\033[92m",
        "bright_yellow": "\033[93m",
        "bright_blue": "\033[94m",
        "bright_magenta": "\033[95m",
        "bright_cyan": "\033[96m",
        "bright_white": "\033[97m",
        "end": "\033[0m",  # misc
        "bold": "\033[1m",
        "underline": "\033[4m",
    }
    return "".join(colors[x] for x in args) + f"{string}" + colors["end"]





ultralytics.utils.remove_colorstr

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:

>>> remove_colorstr(colorstr("blue", "bold", "hello world"))
>>> "hello world"
Source code in ultralytics/utils/__init__.py
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
def remove_colorstr(input_string):
    """
    Removes ANSI escape codes from a string, effectively un-coloring it.

    Args:
        input_string (str): The string to remove color and style from.

    Returns:
        (str): A new string with all ANSI escape codes removed.

    Examples:
        >>> remove_colorstr(colorstr("blue", "bold", "hello world"))
        >>> "hello world"
    """
    ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
    return ansi_escape.sub("", input_string)





ultralytics.utils.threaded

threaded(func)

Multi-threads a target function by default and returns the thread or function result.

This decorator provides flexible execution of the target function, either in a separate thread or synchronously. By default, the function runs in a thread, but this can be controlled via the 'threaded=False' keyword argument which is removed from kwargs before calling the function.

Parameters:

Name Type Description Default
func callable

The function to be potentially executed in a separate thread.

required

Returns:

Type Description
callable

A wrapper function that either returns a daemon thread or the direct function result.

Examples:

>>> @threaded
... def process_data(data):
...     return data
>>>
>>> thread = process_data(my_data)  # Runs in background thread
>>> result = process_data(my_data, threaded=False)  # Runs synchronously, returns function result
Source code in ultralytics/utils/__init__.py
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
def threaded(func):
    """
    Multi-threads a target function by default and returns the thread or function result.

    This decorator provides flexible execution of the target function, either in a separate thread or synchronously.
    By default, the function runs in a thread, but this can be controlled via the 'threaded=False' keyword argument
    which is removed from kwargs before calling the function.

    Args:
        func (callable): The function to be potentially executed in a separate thread.

    Returns:
        (callable): A wrapper function that either returns a daemon thread or the direct function result.

    Examples:
        >>> @threaded
        ... def process_data(data):
        ...     return data
        >>>
        >>> thread = process_data(my_data)  # Runs in background thread
        >>> result = process_data(my_data, threaded=False)  # Runs synchronously, returns function result
    """

    def wrapper(*args, **kwargs):
        """Multi-threads a given function based on 'threaded' kwarg and returns the thread or function result."""
        if kwargs.pop("threaded", True):  # run in thread
            thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
            thread.start()
            return thread
        else:
            return func(*args, **kwargs)

    return wrapper





ultralytics.utils.set_sentry

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)

Source code in ultralytics/utils/__init__.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
def 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)
    """
    if (
        not SETTINGS["sync"]
        or RANK not in {-1, 0}
        or Path(ARGV[0]).name != "yolo"
        or TESTS_RUNNING
        or not ONLINE
        or not IS_PIP_PACKAGE
        or IS_GIT_DIR
    ):
        return
    # If sentry_sdk package is not installed then return and do not use Sentry
    try:
        import sentry_sdk  # noqa
    except ImportError:
        return

    def before_send(event, hint):
        """
        Modify the event before sending it to Sentry based on specific exception types and messages.

        Args:
            event (dict): The event dictionary containing information about the error.
            hint (dict): A dictionary containing additional information about the error.

        Returns:
            dict: The modified event or None if the event should not be sent to Sentry.
        """
        if "exc_info" in hint:
            exc_type, exc_value, _ = hint["exc_info"]
            if exc_type in {KeyboardInterrupt, FileNotFoundError} or "out of memory" in str(exc_value):
                return None  # do not send event

        event["tags"] = {
            "sys_argv": ARGV[0],
            "sys_argv_name": Path(ARGV[0]).name,
            "install": "git" if IS_GIT_DIR else "pip" if IS_PIP_PACKAGE else "other",
            "os": ENVIRONMENT,
        }
        return event

    sentry_sdk.init(
        dsn="https://888e5a0778212e1d0314c37d4b9aae5d@o4504521589325824.ingest.us.sentry.io/4504521592406016",
        debug=False,
        auto_enabling_integrations=False,
        traces_sample_rate=1.0,
        release=__version__,
        environment="runpod" if is_runpod() else "production",
        before_send=before_send,
        ignore_errors=[KeyboardInterrupt, FileNotFoundError],
    )
    sentry_sdk.set_user({"id": SETTINGS["uuid"]})  # SHA-256 anonymized UUID hash





ultralytics.utils.deprecation_warn

deprecation_warn(arg, new_arg=None)

Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument.

Source code in ultralytics/utils/__init__.py
1318
1319
1320
1321
1322
1323
def deprecation_warn(arg, new_arg=None):
    """Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument."""
    msg = f"'{arg}' is deprecated and will be removed in in the future."
    if new_arg is not None:
        msg += f" Use '{new_arg}' instead."
    LOGGER.warning(msg)





ultralytics.utils.clean_url

clean_url(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
1326
1327
1328
1329
def clean_url(url):
    """Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt."""
    url = Path(url).as_posix().replace(":/", "://")  # Pathlib turns :// -> :/, as_posix() for Windows
    return unquote(url).split("?")[0]  # '%2F' to '/', split https://url.com/file.txt?auth





ultralytics.utils.url2file

url2file(url)

Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt.

Source code in ultralytics/utils/__init__.py
1332
1333
1334
def url2file(url):
    """Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt."""
    return Path(clean_url(url)).name





ultralytics.utils.vscode_msg

vscode_msg(ext='ultralytics.ultralytics-snippets') -> str

Display a message to install Ultralytics-Snippets for VS Code if not already installed.

Source code in ultralytics/utils/__init__.py
1337
1338
1339
1340
1341
1342
1343
def vscode_msg(ext="ultralytics.ultralytics-snippets") -> str:
    """Display a message to install Ultralytics-Snippets for VS Code if not already installed."""
    path = (USER_CONFIG_DIR.parents[2] if WINDOWS else USER_CONFIG_DIR.parents[1]) / ".vscode/extensions"
    obs_file = path / ".obsolete"  # file tracks uninstalled extensions, while source directory remains
    installed = any(path.glob(f"{ext}*")) and ext not in (obs_file.read_text("utf-8") if obs_file.exists() else "")
    url = "https://docs.ultralytics.com/integrations/vscode"
    return "" if installed else f"{colorstr('VS Code:')} view Ultralytics VS Code Extension ⚡ at {url}"





📅 Created 1 year ago ✏️ Updated 3 months ago