__init__.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import contextlib
  3. import inspect
  4. import logging.config
  5. import os
  6. import platform
  7. import re
  8. import subprocess
  9. import sys
  10. import threading
  11. import urllib
  12. import uuid
  13. from pathlib import Path
  14. from types import SimpleNamespace
  15. from typing import Union
  16. import cv2
  17. import matplotlib.pyplot as plt
  18. import numpy as np
  19. import torch
  20. import yaml
  21. from ultralytics import __version__
  22. # PyTorch Multi-GPU DDP Constants
  23. RANK = int(os.getenv('RANK', -1))
  24. LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
  25. # Other Constants
  26. FILE = Path(__file__).resolve()
  27. ROOT = FILE.parents[1] # YOLO
  28. ASSETS = ROOT / 'assets' # default images
  29. DEFAULT_CFG_PATH = ROOT / 'cfg/default.yaml'
  30. NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads
  31. AUTOINSTALL = str(os.getenv('YOLO_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode
  32. VERBOSE = str(os.getenv('YOLO_VERBOSE', True)).lower() == 'true' # global verbose mode
  33. TQDM_BAR_FORMAT = '{l_bar}{bar:10}{r_bar}' # tqdm bar format
  34. LOGGING_NAME = 'ultralytics'
  35. MACOS, LINUX, WINDOWS = (platform.system() == x for x in ['Darwin', 'Linux', 'Windows']) # environment booleans
  36. ARM64 = platform.machine() in ('arm64', 'aarch64') # ARM64 booleans
  37. HELP_MSG = \
  38. """
  39. Usage examples for running YOLOv8:
  40. 1. Install the ultralytics package:
  41. pip install ultralytics
  42. 2. Use the Python SDK:
  43. from ultralytics import YOLO
  44. # Load a model
  45. model = YOLO('yolov8n.yaml') # build a new model from scratch
  46. model = YOLO("yolov8n.pt") # load a pretrained model (recommended for training)
  47. # Use the model
  48. results = model.train(data="coco128.yaml", epochs=3) # train the model
  49. results = model.val() # evaluate model performance on the validation set
  50. results = model('https://ultralytics.com/images/bus.jpg') # predict on an image
  51. success = model.export(format='onnx') # export the model to ONNX format
  52. 3. Use the command line interface (CLI):
  53. YOLOv8 'yolo' CLI commands use the following syntax:
  54. yolo TASK MODE ARGS
  55. Where TASK (optional) is one of [detect, segment, classify]
  56. MODE (required) is one of [train, val, predict, export]
  57. ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.
  58. See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'
  59. - Train a detection model for 10 epochs with an initial learning_rate of 0.01
  60. yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01
  61. - Predict a YouTube video using a pretrained segmentation model at image size 320:
  62. yolo segment predict model=yolov8n-seg.pt source='https://youtu.be/Zgi9g1ksQHc' imgsz=320
  63. - Val a pretrained detection model at batch-size 1 and image size 640:
  64. yolo detect val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640
  65. - Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)
  66. yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128
  67. - Run special commands:
  68. yolo help
  69. yolo checks
  70. yolo version
  71. yolo settings
  72. yolo copy-cfg
  73. yolo cfg
  74. Docs: https://docs.ultralytics.com
  75. Community: https://community.ultralytics.com
  76. GitHub: https://github.com/ultralytics/ultralytics
  77. """
  78. # Settings
  79. torch.set_printoptions(linewidth=320, precision=4, profile='default')
  80. np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
  81. cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
  82. os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads
  83. os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # for deterministic training
  84. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # suppress verbose TF compiler warnings in Colab
  85. class SimpleClass:
  86. """
  87. Ultralytics SimpleClass is a base class providing helpful string representation, error reporting, and attribute
  88. access methods for easier debugging and usage.
  89. """
  90. def __str__(self):
  91. """Return a human-readable string representation of the object."""
  92. attr = []
  93. for a in dir(self):
  94. v = getattr(self, a)
  95. if not callable(v) and not a.startswith('_'):
  96. if isinstance(v, SimpleClass):
  97. # Display only the module and class name for subclasses
  98. s = f'{a}: {v.__module__}.{v.__class__.__name__} object'
  99. else:
  100. s = f'{a}: {repr(v)}'
  101. attr.append(s)
  102. return f'{self.__module__}.{self.__class__.__name__} object with attributes:\n\n' + '\n'.join(attr)
  103. def __repr__(self):
  104. """Return a machine-readable string representation of the object."""
  105. return self.__str__()
  106. def __getattr__(self, attr):
  107. """Custom attribute access error message with helpful information."""
  108. name = self.__class__.__name__
  109. raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
  110. class IterableSimpleNamespace(SimpleNamespace):
  111. """
  112. Ultralytics IterableSimpleNamespace is an extension class of SimpleNamespace that adds iterable functionality and
  113. enables usage with dict() and for loops.
  114. """
  115. def __iter__(self):
  116. """Return an iterator of key-value pairs from the namespace's attributes."""
  117. return iter(vars(self).items())
  118. def __str__(self):
  119. """Return a human-readable string representation of the object."""
  120. return '\n'.join(f'{k}={v}' for k, v in vars(self).items())
  121. def __getattr__(self, attr):
  122. """Custom attribute access error message with helpful information."""
  123. name = self.__class__.__name__
  124. raise AttributeError(f"""
  125. '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics
  126. 'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace
  127. {DEFAULT_CFG_PATH} with the latest version from
  128. https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
  129. """)
  130. def get(self, key, default=None):
  131. """Return the value of the specified key if it exists; otherwise, return the default value."""
  132. return getattr(self, key, default)
  133. def plt_settings(rcparams=None, backend='Agg'):
  134. """
  135. Decorator to temporarily set rc parameters and the backend for a plotting function.
  136. Example:
  137. decorator: @plt_settings({"font.size": 12})
  138. context manager: with plt_settings({"font.size": 12}):
  139. Args:
  140. rcparams (dict): Dictionary of rc parameters to set.
  141. backend (str, optional): Name of the backend to use. Defaults to 'Agg'.
  142. Returns:
  143. (Callable): Decorated function with temporarily set rc parameters and backend. This decorator can be
  144. applied to any function that needs to have specific matplotlib rc parameters and backend for its execution.
  145. """
  146. if rcparams is None:
  147. rcparams = {'font.size': 11}
  148. def decorator(func):
  149. """Decorator to apply temporary rc parameters and backend to a function."""
  150. def wrapper(*args, **kwargs):
  151. """Sets rc parameters and backend, calls the original function, and restores the settings."""
  152. original_backend = plt.get_backend()
  153. plt.switch_backend(backend)
  154. with plt.rc_context(rcparams):
  155. result = func(*args, **kwargs)
  156. plt.switch_backend(original_backend)
  157. return result
  158. return wrapper
  159. return decorator
  160. def set_logging(name=LOGGING_NAME, verbose=True):
  161. """Sets up logging for the given name."""
  162. rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings
  163. level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR
  164. logging.config.dictConfig({
  165. 'version': 1,
  166. 'disable_existing_loggers': False,
  167. 'formatters': {
  168. name: {
  169. 'format': '%(message)s'}},
  170. 'handlers': {
  171. name: {
  172. 'class': 'logging.StreamHandler',
  173. 'formatter': name,
  174. 'level': level}},
  175. 'loggers': {
  176. name: {
  177. 'level': level,
  178. 'handlers': [name],
  179. 'propagate': False}}})
  180. def emojis(string=''):
  181. """Return platform-dependent emoji-safe version of string."""
  182. return string.encode().decode('ascii', 'ignore') if WINDOWS else string
  183. class EmojiFilter(logging.Filter):
  184. """
  185. A custom logging filter class for removing emojis in log messages.
  186. This filter is particularly useful for ensuring compatibility with Windows terminals
  187. that may not support the display of emojis in log messages.
  188. """
  189. def filter(self, record):
  190. """Filter logs by emoji unicode characters on windows."""
  191. record.msg = emojis(record.msg)
  192. return super().filter(record)
  193. # Set logger
  194. set_logging(LOGGING_NAME, verbose=VERBOSE) # run before defining LOGGER
  195. LOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)
  196. if WINDOWS: # emoji-safe logging
  197. LOGGER.addFilter(EmojiFilter())
  198. class ThreadingLocked:
  199. """
  200. A decorator class for ensuring thread-safe execution of a function or method.
  201. This class can be used as a decorator to make sure that if the decorated function
  202. is called from multiple threads, only one thread at a time will be able to execute the function.
  203. Attributes:
  204. lock (threading.Lock): A lock object used to manage access to the decorated function.
  205. Example:
  206. ```python
  207. from ultralytics.utils import ThreadingLocked
  208. @ThreadingLocked()
  209. def my_function():
  210. # Your code here
  211. pass
  212. ```
  213. """
  214. def __init__(self):
  215. self.lock = threading.Lock()
  216. def __call__(self, f):
  217. from functools import wraps
  218. @wraps(f)
  219. def decorated(*args, **kwargs):
  220. with self.lock:
  221. return f(*args, **kwargs)
  222. return decorated
  223. def yaml_save(file='data.yaml', data=None):
  224. """
  225. Save YAML data to a file.
  226. Args:
  227. file (str, optional): File name. Default is 'data.yaml'.
  228. data (dict): Data to save in YAML format.
  229. Returns:
  230. (None): Data is saved to the specified file.
  231. """
  232. if data is None:
  233. data = {}
  234. file = Path(file)
  235. if not file.parent.exists():
  236. # Create parent directories if they don't exist
  237. file.parent.mkdir(parents=True, exist_ok=True)
  238. # Convert Path objects to strings
  239. for k, v in data.items():
  240. if isinstance(v, Path):
  241. data[k] = str(v)
  242. # Dump data to file in YAML format
  243. with open(file, 'w') as f:
  244. yaml.safe_dump(data, f, sort_keys=False, allow_unicode=True)
  245. def yaml_load(file='data.yaml', append_filename=False):
  246. """
  247. Load YAML data from a file.
  248. Args:
  249. file (str, optional): File name. Default is 'data.yaml'.
  250. append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.
  251. Returns:
  252. (dict): YAML data and file name.
  253. """
  254. with open(file, errors='ignore', encoding='utf-8') as f:
  255. s = f.read() # string
  256. # Remove special characters
  257. if not s.isprintable():
  258. s = re.sub(r'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+', '', s)
  259. # Add YAML filename to dict and return
  260. data = yaml.safe_load(s) or {} # always return a dict (yaml.safe_load() may return None for empty files)
  261. if append_filename:
  262. data['yaml_file'] = str(file)
  263. return data
  264. def yaml_print(yaml_file: Union[str, Path, dict]) -> None:
  265. """
  266. Pretty prints a YAML file or a YAML-formatted dictionary.
  267. Args:
  268. yaml_file: The file path of the YAML file or a YAML-formatted dictionary.
  269. Returns:
  270. None
  271. """
  272. yaml_dict = yaml_load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file
  273. dump = yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True)
  274. LOGGER.info(f"Printing '{colorstr('bold', 'black', yaml_file)}'\n\n{dump}")
  275. # Default configuration
  276. DEFAULT_CFG_DICT = yaml_load(DEFAULT_CFG_PATH)
  277. for k, v in DEFAULT_CFG_DICT.items():
  278. if isinstance(v, str) and v.lower() == 'none':
  279. DEFAULT_CFG_DICT[k] = None
  280. DEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys()
  281. DEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT)
  282. def is_ubuntu() -> bool:
  283. """
  284. Check if the OS is Ubuntu.
  285. Returns:
  286. (bool): True if OS is Ubuntu, False otherwise.
  287. """
  288. with contextlib.suppress(FileNotFoundError):
  289. with open('/etc/os-release') as f:
  290. return 'ID=ubuntu' in f.read()
  291. return False
  292. def is_colab():
  293. """
  294. Check if the current script is running inside a Google Colab notebook.
  295. Returns:
  296. (bool): True if running inside a Colab notebook, False otherwise.
  297. """
  298. return 'COLAB_RELEASE_TAG' in os.environ or 'COLAB_BACKEND_VERSION' in os.environ
  299. def is_kaggle():
  300. """
  301. Check if the current script is running inside a Kaggle kernel.
  302. Returns:
  303. (bool): True if running inside a Kaggle kernel, False otherwise.
  304. """
  305. return os.environ.get('PWD') == '/kaggle/working' and os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'
  306. def is_jupyter():
  307. """
  308. Check if the current script is running inside a Jupyter Notebook.
  309. Verified on Colab, Jupyterlab, Kaggle, Paperspace.
  310. Returns:
  311. (bool): True if running inside a Jupyter Notebook, False otherwise.
  312. """
  313. with contextlib.suppress(Exception):
  314. from IPython import get_ipython
  315. return get_ipython() is not None
  316. return False
  317. def is_docker() -> bool:
  318. """
  319. Determine if the script is running inside a Docker container.
  320. Returns:
  321. (bool): True if the script is running inside a Docker container, False otherwise.
  322. """
  323. file = Path('/proc/self/cgroup')
  324. if file.exists():
  325. with open(file) as f:
  326. return 'docker' in f.read()
  327. else:
  328. return False
  329. def is_online() -> bool:
  330. """
  331. Check internet connectivity by attempting to connect to a known online host.
  332. Returns:
  333. (bool): True if connection is successful, False otherwise.
  334. """
  335. import socket
  336. for host in '1.1.1.1', '8.8.8.8', '223.5.5.5': # Cloudflare, Google, AliDNS:
  337. try:
  338. test_connection = socket.create_connection(address=(host, 53), timeout=2)
  339. except (socket.timeout, socket.gaierror, OSError):
  340. continue
  341. else:
  342. # If the connection was successful, close it to avoid a ResourceWarning
  343. test_connection.close()
  344. return True
  345. return False
  346. ONLINE = is_online()
  347. def is_pip_package(filepath: str = __name__) -> bool:
  348. """
  349. Determines if the file at the given filepath is part of a pip package.
  350. Args:
  351. filepath (str): The filepath to check.
  352. Returns:
  353. (bool): True if the file is part of a pip package, False otherwise.
  354. """
  355. import importlib.util
  356. # Get the spec for the module
  357. spec = importlib.util.find_spec(filepath)
  358. # Return whether the spec is not None and the origin is not None (indicating it is a package)
  359. return spec is not None and spec.origin is not None
  360. def is_dir_writeable(dir_path: Union[str, Path]) -> bool:
  361. """
  362. Check if a directory is writeable.
  363. Args:
  364. dir_path (str | Path): The path to the directory.
  365. Returns:
  366. (bool): True if the directory is writeable, False otherwise.
  367. """
  368. return os.access(str(dir_path), os.W_OK)
  369. def is_pytest_running():
  370. """
  371. Determines whether pytest is currently running or not.
  372. Returns:
  373. (bool): True if pytest is running, False otherwise.
  374. """
  375. return ('PYTEST_CURRENT_TEST' in os.environ) or ('pytest' in sys.modules) or ('pytest' in Path(sys.argv[0]).stem)
  376. def is_github_actions_ci() -> bool:
  377. """
  378. Determine if the current environment is a GitHub Actions CI Python runner.
  379. Returns:
  380. (bool): True if the current environment is a GitHub Actions CI Python runner, False otherwise.
  381. """
  382. return 'GITHUB_ACTIONS' in os.environ and 'RUNNER_OS' in os.environ and 'RUNNER_TOOL_CACHE' in os.environ
  383. def is_git_dir():
  384. """
  385. Determines whether the current file is part of a git repository.
  386. If the current file is not part of a git repository, returns None.
  387. Returns:
  388. (bool): True if current file is part of a git repository.
  389. """
  390. return get_git_dir() is not None
  391. def get_git_dir():
  392. """
  393. Determines whether the current file is part of a git repository and if so, returns the repository root directory.
  394. If the current file is not part of a git repository, returns None.
  395. Returns:
  396. (Path | None): Git root directory if found or None if not found.
  397. """
  398. for d in Path(__file__).parents:
  399. if (d / '.git').is_dir():
  400. return d
  401. def get_git_origin_url():
  402. """
  403. Retrieves the origin URL of a git repository.
  404. Returns:
  405. (str | None): The origin URL of the git repository or None if not git directory.
  406. """
  407. if is_git_dir():
  408. with contextlib.suppress(subprocess.CalledProcessError):
  409. origin = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url'])
  410. return origin.decode().strip()
  411. def get_git_branch():
  412. """
  413. Returns the current git branch name. If not in a git repository, returns None.
  414. Returns:
  415. (str | None): The current git branch name or None if not a git directory.
  416. """
  417. if is_git_dir():
  418. with contextlib.suppress(subprocess.CalledProcessError):
  419. origin = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
  420. return origin.decode().strip()
  421. def get_default_args(func):
  422. """Returns a dictionary of default arguments for a function.
  423. Args:
  424. func (callable): The function to inspect.
  425. Returns:
  426. (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.
  427. """
  428. signature = inspect.signature(func)
  429. return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}
  430. def get_ubuntu_version():
  431. """
  432. Retrieve the Ubuntu version if the OS is Ubuntu.
  433. Returns:
  434. (str): Ubuntu version or None if not an Ubuntu OS.
  435. """
  436. if is_ubuntu():
  437. with contextlib.suppress(FileNotFoundError, AttributeError):
  438. with open('/etc/os-release') as f:
  439. return re.search(r'VERSION_ID="(\d+\.\d+)"', f.read())[1]
  440. def get_user_config_dir(sub_dir='Ultralytics'):
  441. """
  442. Get the user config directory.
  443. Args:
  444. sub_dir (str): The name of the subdirectory to create.
  445. Returns:
  446. (Path): The path to the user config directory.
  447. """
  448. # Return the appropriate config directory for each operating system
  449. if WINDOWS:
  450. path = Path.home() / 'AppData' / 'Roaming' / sub_dir
  451. elif MACOS: # macOS
  452. path = Path.home() / 'Library' / 'Application Support' / sub_dir
  453. elif LINUX:
  454. path = Path.home() / '.config' / sub_dir
  455. else:
  456. raise ValueError(f'Unsupported operating system: {platform.system()}')
  457. # GCP and AWS lambda fix, only /tmp is writeable
  458. if not is_dir_writeable(path.parent):
  459. LOGGER.warning(f"WARNING ⚠️ user config directory '{path}' is not writeable, defaulting to '/tmp' or CWD."
  460. 'Alternatively you can define a YOLO_CONFIG_DIR environment variable for this path.')
  461. path = Path('/tmp') / sub_dir if is_dir_writeable('/tmp') else Path().cwd() / sub_dir
  462. # Create the subdirectory if it does not exist
  463. path.mkdir(parents=True, exist_ok=True)
  464. return path
  465. USER_CONFIG_DIR = Path(os.getenv('YOLO_CONFIG_DIR') or get_user_config_dir()) # Ultralytics settings dir
  466. SETTINGS_YAML = USER_CONFIG_DIR / 'settings.yaml'
  467. def colorstr(*input):
  468. """Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')."""
  469. *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
  470. colors = {
  471. 'black': '\033[30m', # basic colors
  472. 'red': '\033[31m',
  473. 'green': '\033[32m',
  474. 'yellow': '\033[33m',
  475. 'blue': '\033[34m',
  476. 'magenta': '\033[35m',
  477. 'cyan': '\033[36m',
  478. 'white': '\033[37m',
  479. 'bright_black': '\033[90m', # bright colors
  480. 'bright_red': '\033[91m',
  481. 'bright_green': '\033[92m',
  482. 'bright_yellow': '\033[93m',
  483. 'bright_blue': '\033[94m',
  484. 'bright_magenta': '\033[95m',
  485. 'bright_cyan': '\033[96m',
  486. 'bright_white': '\033[97m',
  487. 'end': '\033[0m', # misc
  488. 'bold': '\033[1m',
  489. 'underline': '\033[4m'}
  490. return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
  491. class TryExcept(contextlib.ContextDecorator):
  492. """YOLOv8 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager."""
  493. def __init__(self, msg='', verbose=True):
  494. """Initialize TryExcept class with optional message and verbosity settings."""
  495. self.msg = msg
  496. self.verbose = verbose
  497. def __enter__(self):
  498. """Executes when entering TryExcept context, initializes instance."""
  499. pass
  500. def __exit__(self, exc_type, value, traceback):
  501. """Defines behavior when exiting a 'with' block, prints error message if necessary."""
  502. if self.verbose and value:
  503. print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
  504. return True
  505. def threaded(func):
  506. """Multi-threads a target function and returns thread. Usage: @threaded decorator."""
  507. def wrapper(*args, **kwargs):
  508. """Multi-threads a given function and returns the thread."""
  509. thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
  510. thread.start()
  511. return thread
  512. return wrapper
  513. def set_sentry():
  514. """
  515. Initialize the Sentry SDK for error tracking and reporting. Only used if sentry_sdk package is installed and
  516. sync=True in settings. Run 'yolo settings' to see and update settings YAML file.
  517. Conditions required to send errors (ALL conditions must be met or no errors will be reported):
  518. - sentry_sdk package is installed
  519. - sync=True in YOLO settings
  520. - pytest is not running
  521. - running in a pip package installation
  522. - running in a non-git directory
  523. - running with rank -1 or 0
  524. - online environment
  525. - CLI used to run package (checked with 'yolo' as the name of the main CLI command)
  526. The function also configures Sentry SDK to ignore KeyboardInterrupt and FileNotFoundError
  527. exceptions and to exclude events with 'out of memory' in their exception message.
  528. Additionally, the function sets custom tags and user information for Sentry events.
  529. """
  530. def before_send(event, hint):
  531. """
  532. Modify the event before sending it to Sentry based on specific exception types and messages.
  533. Args:
  534. event (dict): The event dictionary containing information about the error.
  535. hint (dict): A dictionary containing additional information about the error.
  536. Returns:
  537. dict: The modified event or None if the event should not be sent to Sentry.
  538. """
  539. if 'exc_info' in hint:
  540. exc_type, exc_value, tb = hint['exc_info']
  541. if exc_type in (KeyboardInterrupt, FileNotFoundError) \
  542. or 'out of memory' in str(exc_value):
  543. return None # do not send event
  544. event['tags'] = {
  545. 'sys_argv': sys.argv[0],
  546. 'sys_argv_name': Path(sys.argv[0]).name,
  547. 'install': 'git' if is_git_dir() else 'pip' if is_pip_package() else 'other',
  548. 'os': ENVIRONMENT}
  549. return event
  550. if SETTINGS['sync'] and \
  551. RANK in (-1, 0) and \
  552. Path(sys.argv[0]).name == 'yolo' and \
  553. not TESTS_RUNNING and \
  554. ONLINE and \
  555. is_pip_package() and \
  556. not is_git_dir():
  557. # If sentry_sdk package is not installed then return and do not use Sentry
  558. try:
  559. import sentry_sdk # noqa
  560. except ImportError:
  561. return
  562. sentry_sdk.init(
  563. dsn='https://5ff1556b71594bfea135ff0203a0d290@o4504521589325824.ingest.sentry.io/4504521592406016',
  564. debug=False,
  565. traces_sample_rate=1.0,
  566. release=__version__,
  567. environment='production', # 'dev' or 'production'
  568. before_send=before_send,
  569. ignore_errors=[KeyboardInterrupt, FileNotFoundError])
  570. sentry_sdk.set_user({'id': SETTINGS['uuid']}) # SHA-256 anonymized UUID hash
  571. # Disable all sentry logging
  572. for logger in 'sentry_sdk', 'sentry_sdk.errors':
  573. logging.getLogger(logger).setLevel(logging.CRITICAL)
  574. class SettingsManager(dict):
  575. """
  576. Manages Ultralytics settings stored in a YAML file.
  577. Args:
  578. file (str | Path): Path to the Ultralytics settings YAML file. Default is USER_CONFIG_DIR / 'settings.yaml'.
  579. version (str): Settings version. In case of local version mismatch, new default settings will be saved.
  580. """
  581. def __init__(self, file=SETTINGS_YAML, version='0.0.4'):
  582. import copy
  583. import hashlib
  584. from ultralytics.utils.checks import check_version
  585. from ultralytics.utils.torch_utils import torch_distributed_zero_first
  586. git_dir = get_git_dir()
  587. root = git_dir or Path()
  588. datasets_root = (root.parent if git_dir and is_dir_writeable(root.parent) else root).resolve()
  589. self.file = Path(file)
  590. self.version = version
  591. self.defaults = {
  592. 'settings_version': version,
  593. 'datasets_dir': str(datasets_root / 'datasets'),
  594. 'weights_dir': str(root / 'weights'),
  595. 'runs_dir': str(root / 'runs'),
  596. 'uuid': hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(),
  597. 'sync': True,
  598. 'api_key': '',
  599. 'clearml': True, # integrations
  600. 'comet': True,
  601. 'dvc': True,
  602. 'hub': True,
  603. 'mlflow': True,
  604. 'neptune': True,
  605. 'raytune': True,
  606. 'tensorboard': True,
  607. 'wandb': True}
  608. super().__init__(copy.deepcopy(self.defaults))
  609. with torch_distributed_zero_first(RANK):
  610. if not self.file.exists():
  611. self.save()
  612. self.load()
  613. correct_keys = self.keys() == self.defaults.keys()
  614. correct_types = all(type(a) is type(b) for a, b in zip(self.values(), self.defaults.values()))
  615. correct_version = check_version(self['settings_version'], self.version)
  616. if not (correct_keys and correct_types and correct_version):
  617. LOGGER.warning(
  618. 'WARNING ⚠️ Ultralytics settings reset to default values. This may be due to a possible problem '
  619. 'with your settings or a recent ultralytics package update. '
  620. f"\nView settings with 'yolo settings' or at '{self.file}'"
  621. "\nUpdate settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'.")
  622. self.reset()
  623. def load(self):
  624. """Loads settings from the YAML file."""
  625. super().update(yaml_load(self.file))
  626. def save(self):
  627. """Saves the current settings to the YAML file."""
  628. yaml_save(self.file, dict(self))
  629. def update(self, *args, **kwargs):
  630. """Updates a setting value in the current settings."""
  631. super().update(*args, **kwargs)
  632. self.save()
  633. def reset(self):
  634. """Resets the settings to default and saves them."""
  635. self.clear()
  636. self.update(self.defaults)
  637. self.save()
  638. def deprecation_warn(arg, new_arg, version=None):
  639. """Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument."""
  640. if not version:
  641. version = float(__version__[:3]) + 0.2 # deprecate after 2nd major release
  642. LOGGER.warning(f"WARNING ⚠️ '{arg}' is deprecated and will be removed in 'ultralytics {version}' in the future. "
  643. f"Please use '{new_arg}' instead.")
  644. def clean_url(url):
  645. """Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt."""
  646. url = Path(url).as_posix().replace(':/', '://') # Pathlib turns :// -> :/, as_posix() for Windows
  647. return urllib.parse.unquote(url).split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth
  648. def url2file(url):
  649. """Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt."""
  650. return Path(clean_url(url)).name
  651. # Run below code on utils init ------------------------------------------------------------------------------------
  652. # Check first-install steps
  653. PREFIX = colorstr('Ultralytics: ')
  654. SETTINGS = SettingsManager() # initialize settings
  655. DATASETS_DIR = Path(SETTINGS['datasets_dir']) # global datasets directory
  656. ENVIRONMENT = 'Colab' if is_colab() else 'Kaggle' if is_kaggle() else 'Jupyter' if is_jupyter() else \
  657. 'Docker' if is_docker() else platform.system()
  658. TESTS_RUNNING = is_pytest_running() or is_github_actions_ci()
  659. set_sentry()
  660. # Apply monkey patches
  661. from .patches import imread, imshow, imwrite, torch_save
  662. torch.save = torch_save
  663. if WINDOWS:
  664. # Apply cv2 patches for non-ASCII and non-UTF characters in image paths
  665. cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow