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.DataExportMixin
Mixin class for exporting validation metrics or prediction results in various formats.
This class provides utilities to export performance metrics (e.g., mAP, precision, recall) or prediction results from classification, object detection, segmentation, or pose estimation tasks into various formats: Polars DataFrame, CSV and JSON.
Methods:
Name | Description |
---|---|
to_df |
Convert summary to a Polars DataFrame. |
to_csv |
Export results as a CSV string. |
to_json |
Export results as a JSON string. |
tojson |
Deprecated alias for |
Examples:
>>> model = YOLO("yolo11n.pt")
>>> results = model("image.jpg")
>>> df = results.to_df()
>>> print(df)
>>> csv_data = results.to_csv()
to_csv
to_csv(normalize=False, decimals=5)
Export results or metrics to CSV string format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
Normalize numeric values. |
False
|
decimals
|
int
|
Decimal precision. |
5
|
Returns:
Type | Description |
---|---|
str
|
CSV content as string. |
Source code in ultralytics/utils/__init__.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
|
to_df
to_df(normalize=False, decimals=5)
Create a polars DataFrame from the prediction results summary or validation metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
Normalize numerical values for easier comparison. |
False
|
decimals
|
int
|
Decimal places to round floats. |
5
|
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame containing the summary data. |
Source code in ultralytics/utils/__init__.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
|
to_json
to_json(normalize=False, decimals=5)
Export results to JSON format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
Normalize numeric values. |
False
|
decimals
|
int
|
Decimal precision. |
5
|
Returns:
Type | Description |
---|---|
str
|
JSON-formatted string of the results. |
Source code in ultralytics/utils/__init__.py
205 206 207 208 209 210 211 212 213 214 215 216 |
|
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__ |
Return a human-readable string representation of the object. |
__repr__ |
Return a machine-readable string representation of the object. |
__getattr__ |
Provide 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)
Provide a custom attribute access error message with helpful information.
Source code in ultralytics/utils/__init__.py
267 268 269 270 |
|
__repr__
__repr__()
Return a machine-readable string representation of the object.
Source code in ultralytics/utils/__init__.py
263 264 265 |
|
__str__
__str__()
Return a human-readable string representation of the object.
Source code in ultralytics/utils/__init__.py
249 250 251 252 253 254 255 256 257 258 259 260 261 |
|
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__ |
Return an iterator of key-value pairs from the namespace's attributes. |
__str__ |
Return a human-readable string representation of the object. |
__getattr__ |
Provide a custom attribute access error message with helpful information. |
get |
Retrieve 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)
Provide a custom attribute access error message with helpful information.
Source code in ultralytics/utils/__init__.py
316 317 318 319 320 321 322 323 324 325 326 |
|
__iter__
__iter__()
Return an iterator of key-value pairs from the namespace's attributes.
Source code in ultralytics/utils/__init__.py
308 309 310 |
|
__str__
__str__()
Return a human-readable string representation of the object.
Source code in ultralytics/utils/__init__.py
312 313 314 |
|
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
328 329 330 |
|
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
485 486 487 |
|
__call__
__call__(f)
Run thread-safe execution of function or method.
Source code in ultralytics/utils/__init__.py
489 490 491 492 493 494 495 496 497 498 499 |
|
ultralytics.utils.YAML
YAML()
YAML utility class for efficient file operations with automatic C-implementation detection.
This class provides optimized YAML loading and saving operations using PyYAML's fastest available implementation (C-based when possible). It implements a singleton pattern with lazy initialization, allowing direct class method usage without explicit instantiation. The class handles file path creation, validation, and character encoding issues automatically.
The implementation prioritizes performance through
- Automatic C-based loader/dumper selection when available
- Singleton pattern to reuse the same instance
- Lazy initialization to defer import costs until needed
- Fallback mechanisms for handling problematic YAML content
Attributes:
Name | Type | Description |
---|---|---|
_instance |
Internal singleton instance storage. |
|
yaml |
Reference to the PyYAML module. |
|
SafeLoader |
Best available YAML loader (CSafeLoader if available). |
|
SafeDumper |
Best available YAML dumper (CSafeDumper if available). |
Examples:
>>> data = YAML.load("config.yaml")
>>> data["new_value"] = 123
>>> YAML.save("updated_config.yaml", data)
>>> YAML.print(data)
Source code in ultralytics/utils/__init__.py
539 540 541 542 543 544 545 546 547 548 549 550 |
|
load
classmethod
load(file='data.yaml', append_filename=False)
Load YAML file to Python object with robust error handling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file
|
str | Path
|
Path to YAML file. |
'data.yaml'
|
append_filename
|
bool
|
Whether to add filename to returned dict. |
False
|
Returns:
Type | Description |
---|---|
dict
|
Loaded YAML content. |
Source code in ultralytics/utils/__init__.py
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 |
|
print
classmethod
print(yaml_file)
Pretty print YAML file or object to console.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
yaml_file
|
str | Path | dict
|
Path to YAML file or dict to print. |
required |
Source code in ultralytics/utils/__init__.py
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 |
|
save
classmethod
save(file='data.yaml', data=None, header='')
Save Python object as YAML file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file
|
str | Path
|
Path to save YAML file. |
'data.yaml'
|
data
|
dict | None
|
Dict or compatible object to save. |
None
|
header
|
str
|
Optional string to add at file beginning. |
''
|
Source code in ultralytics/utils/__init__.py
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 |
|
ultralytics.utils.TryExcept
TryExcept(msg='', verbose=True)
Bases: ContextDecorator
Ultralytics TryExcept class for handling exceptions gracefully.
This class can be used as a decorator or context manager to catch exceptions and optionally print warning messages. It allows code to continue execution even when exceptions occur, which is useful for non-critical operations.
Attributes:
Name | Type | Description |
---|---|---|
msg |
str
|
Optional message to display when an exception occurs. |
verbose |
bool
|
Whether to print the exception message. |
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
1001 1002 1003 1004 |
|
__enter__
__enter__()
Execute when entering TryExcept context, initialize instance.
Source code in ultralytics/utils/__init__.py
1006 1007 1008 |
|
__exit__
__exit__(exc_type, value, traceback)
Define behavior when exiting a 'with' block, print error message if necessary.
Source code in ultralytics/utils/__init__.py
1010 1011 1012 1013 1014 |
|
ultralytics.utils.Retry
Retry(times=3, delay=2)
Bases: ContextDecorator
Retry class for function execution with exponential backoff.
This decorator can be used to retry a function on exceptions, up to a specified number of times with an exponentially increasing delay between retries. It's useful for handling transient failures in network operations or other unreliable processes.
Attributes:
Name | Type | Description |
---|---|---|
times |
int
|
Maximum number of retry attempts. |
delay |
int
|
Initial delay between retries in seconds. |
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
1037 1038 1039 1040 1041 |
|
__call__
__call__(func)
Decorator implementation for Retry with exponential backoff.
Source code in ultralytics/utils/__init__.py
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 |
|
ultralytics.utils.JSONDict
JSONDict(file_path: 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 and handles JSON serialization of Path objects.
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 |
Load the data from the JSON file into the dictionary. |
_save |
Save the current state of the dictionary to the JSON file. |
__setitem__ |
Store a key-value pair and persist it to disk. |
__delitem__ |
Remove an item and update the persistent storage. |
update |
Update the dictionary and persist changes. |
clear |
Clear all entries and update 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
1196 1197 1198 1199 1200 1201 |
|
__delitem__
__delitem__(key)
Remove an item and update the persistent storage.
Source code in ultralytics/utils/__init__.py
1236 1237 1238 1239 1240 |
|
__setitem__
__setitem__(key, value)
Store a key-value pair and persist to disk.
Source code in ultralytics/utils/__init__.py
1230 1231 1232 1233 1234 |
|
__str__
__str__()
Return a pretty-printed JSON string representation of the dictionary.
Source code in ultralytics/utils/__init__.py
1242 1243 1244 1245 |
|
clear
clear()
Clear all entries and update the persistent storage.
Source code in ultralytics/utils/__init__.py
1253 1254 1255 1256 1257 |
|
update
update(*args, **kwargs)
Update the dictionary and persist changes.
Source code in ultralytics/utils/__init__.py
1247 1248 1249 1250 1251 |
|
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. The settings include directories for datasets, weights, and runs, as well as various integration flags.
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 |
Validate the current settings and reset if necessary. |
update |
Update settings, validating keys and types. |
reset |
Reset the settings to default and save 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
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 |
|
__setitem__
__setitem__(key, value)
Update one key: value pair.
Source code in ultralytics/utils/__init__.py
1356 1357 1358 |
|
reset
reset()
Reset the settings to default and save them.
Source code in ultralytics/utils/__init__.py
1375 1376 1377 1378 |
|
update
update(*args, **kwargs)
Update settings, validating keys and types.
Source code in ultralytics/utils/__init__.py
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 |
|
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. |
'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
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 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 |
|
ultralytics.utils.set_logging
set_logging(name='LOGGING_NAME', verbose=True)
Set 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. |
'LOGGING_NAME'
|
verbose
|
bool
|
Flag to set logging level to INFO if True, ERROR otherwise. |
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
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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
|
ultralytics.utils.emojis
emojis(string='')
Return platform-dependent emoji-safe version of string.
Source code in ultralytics/utils/__init__.py
463 464 465 |
|
ultralytics.utils.read_device_model
read_device_model() -> str
Read the device model information from the system and cache it for quick access.
Returns:
Type | Description |
---|---|
str
|
Kernel release information. |
Source code in ultralytics/utils/__init__.py
642 643 644 645 646 647 648 649 |
|
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
652 653 654 655 656 657 658 659 660 661 662 663 |
|
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
666 667 668 669 670 671 672 673 |
|
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
676 677 678 679 680 681 682 683 |
|
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. |
Notes
- 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
686 687 688 689 690 691 692 693 694 695 696 697 |
|
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
700 701 702 703 704 705 706 707 |
|
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
710 711 712 713 714 715 716 717 718 719 720 |
|
ultralytics.utils.is_raspberrypi
is_raspberrypi() -> bool
Determine 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
723 724 725 726 727 728 729 730 |
|
ultralytics.utils.is_jetson
cached
is_jetson(jetpack=None) -> bool
Determine if the Python environment is running on an NVIDIA Jetson device.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
jetpack
|
int | None
|
If specified, check for specific JetPack version (4, 5, 6). |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if running on an NVIDIA Jetson device, False otherwise. |
Source code in ultralytics/utils/__init__.py
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 |
|
ultralytics.utils.is_online
is_online() -> bool
Fast online check using DNS (v4/v6) resolution (Cloudflare + Google).
Returns:
Type | Description |
---|---|
bool
|
True if connection is successful, False otherwise. |
Source code in ultralytics/utils/__init__.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 |
|
ultralytics.utils.is_pip_package
is_pip_package(filepath: str = __name__) -> bool
Determine 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
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 |
|
ultralytics.utils.is_dir_writeable
is_dir_writeable(dir_path: 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
793 794 795 796 797 798 799 800 801 802 803 |
|
ultralytics.utils.is_pytest_running
is_pytest_running()
Determine 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
806 807 808 809 810 811 812 813 |
|
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
816 817 818 819 820 821 822 823 |
|
ultralytics.utils.get_default_args
get_default_args(func)
Return 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
826 827 828 829 830 831 832 833 834 835 836 837 |
|
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
840 841 842 843 844 845 846 847 848 849 850 851 852 |
|
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
855 856 857 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 |
|
ultralytics.utils.colorstr
colorstr(*input)
Color a string based on the provided color and style arguments using ANSI escape codes.
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. |
()
|
Returns:
Type | Description |
---|---|
str
|
The input string wrapped with ANSI escape codes for the specified color and style. |
Notes
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'
Examples:
>>> colorstr("blue", "bold", "hello world")
>>> "\033[34m\033[1mhello world\033[0m"
Source code in ultralytics/utils/__init__.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 |
|
ultralytics.utils.remove_colorstr
remove_colorstr(input_string)
Remove 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
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 |
|
ultralytics.utils.threaded
threaded(func)
Multi-thread a target function by default and return 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
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 |
|
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
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 |
|
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
1381 1382 1383 1384 1385 1386 |
|
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
1389 1390 1391 1392 |
|
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
1395 1396 1397 |
|
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
1400 1401 1402 1403 1404 1405 1406 |
|