__init__.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import contextlib
  3. import importlib.metadata
  4. import inspect
  5. import json
  6. import logging.config
  7. import os
  8. import platform
  9. import re
  10. import subprocess
  11. import sys
  12. import threading
  13. import time
  14. import uuid
  15. from pathlib import Path
  16. from threading import Lock
  17. from types import SimpleNamespace
  18. from typing import Union
  19. from urllib.parse import unquote
  20. import cv2
  21. import matplotlib.pyplot as plt
  22. import numpy as np
  23. import torch
  24. import yaml
  25. from tqdm import tqdm as tqdm_original
  26. from ultralytics import __version__
  27. # PyTorch Multi-GPU DDP Constants
  28. RANK = int(os.getenv("RANK", -1))
  29. LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
  30. # Other Constants
  31. ARGV = sys.argv or ["", ""] # sometimes sys.argv = []
  32. FILE = Path(__file__).resolve()
  33. ROOT = FILE.parents[1] # YOLO
  34. ASSETS = ROOT / "assets" # default images
  35. ASSETS_URL = "https://github.com/ultralytics/assets/releases/download/v0.0.0" # assets GitHub URL
  36. DEFAULT_CFG_PATH = ROOT / "cfg/default.yaml"
  37. DEFAULT_SOL_CFG_PATH = ROOT / "cfg/solutions/default.yaml" # Ultralytics solutions yaml path
  38. NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLO multiprocessing threads
  39. AUTOINSTALL = str(os.getenv("YOLO_AUTOINSTALL", True)).lower() == "true" # global auto-install mode
  40. VERBOSE = str(os.getenv("YOLO_VERBOSE", True)).lower() == "true" # global verbose mode
  41. TQDM_BAR_FORMAT = "{l_bar}{bar:10}{r_bar}" if VERBOSE else None # tqdm bar format
  42. LOGGING_NAME = "ultralytics"
  43. MACOS, LINUX, WINDOWS = (platform.system() == x for x in ["Darwin", "Linux", "Windows"]) # environment booleans
  44. ARM64 = platform.machine() in {"arm64", "aarch64"} # ARM64 booleans
  45. PYTHON_VERSION = platform.python_version()
  46. TORCH_VERSION = torch.__version__
  47. TORCHVISION_VERSION = importlib.metadata.version("torchvision") # faster than importing torchvision
  48. IS_VSCODE = os.environ.get("TERM_PROGRAM", False) == "vscode"
  49. HELP_MSG = """
  50. Examples for running Ultralytics:
  51. 1. Install the ultralytics package:
  52. pip install ultralytics
  53. 2. Use the Python SDK:
  54. from ultralytics import YOLO
  55. # Load a model
  56. model = YOLO("yolo11n.yaml") # build a new model from scratch
  57. model = YOLO("yolo11n.pt") # load a pretrained model (recommended for training)
  58. # Use the model
  59. results = model.train(data="coco8.yaml", epochs=3) # train the model
  60. results = model.val() # evaluate model performance on the validation set
  61. results = model("https://ultralytics.com/images/bus.jpg") # predict on an image
  62. success = model.export(format="onnx") # export the model to ONNX format
  63. 3. Use the command line interface (CLI):
  64. Ultralytics 'yolo' CLI commands use the following syntax:
  65. yolo TASK MODE ARGS
  66. Where TASK (optional) is one of [detect, segment, classify, pose, obb]
  67. MODE (required) is one of [train, val, predict, export, track, benchmark]
  68. ARGS (optional) are any number of custom "arg=value" pairs like "imgsz=320" that override defaults.
  69. See all ARGS at https://docs.ultralytics.com/usage/cfg or with "yolo cfg"
  70. - Train a detection model for 10 epochs with an initial learning_rate of 0.01
  71. yolo detect train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01
  72. - Predict a YouTube video using a pretrained segmentation model at image size 320:
  73. yolo segment predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320
  74. - Val a pretrained detection model at batch-size 1 and image size 640:
  75. yolo detect val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640
  76. - Export a YOLO11n classification model to ONNX format at image size 224 by 128 (no TASK required)
  77. yolo export model=yolo11n-cls.pt format=onnx imgsz=224,128
  78. - Run special commands:
  79. yolo help
  80. yolo checks
  81. yolo version
  82. yolo settings
  83. yolo copy-cfg
  84. yolo cfg
  85. Docs: https://docs.ultralytics.com
  86. Community: https://community.ultralytics.com
  87. GitHub: https://github.com/ultralytics/ultralytics
  88. """
  89. # Settings and Environment Variables
  90. torch.set_printoptions(linewidth=320, precision=4, profile="default")
  91. np.set_printoptions(linewidth=320, formatter={"float_kind": "{:11.5g}".format}) # format short g, %precision=5
  92. cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
  93. os.environ["NUMEXPR_MAX_THREADS"] = str(NUM_THREADS) # NumExpr max threads
  94. os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" # for deterministic training to avoid CUDA warning
  95. os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # suppress verbose TF compiler warnings in Colab
  96. os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR" # suppress "NNPACK.cpp could not initialize NNPACK" warnings
  97. os.environ["KINETO_LOG_LEVEL"] = "5" # suppress verbose PyTorch profiler output when computing FLOPs
  98. class TQDM(tqdm_original):
  99. """
  100. A custom TQDM progress bar class that extends the original tqdm functionality.
  101. This class modifies the behavior of the original tqdm progress bar based on global settings and provides
  102. additional customization options.
  103. Attributes:
  104. disable (bool): Whether to disable the progress bar. Determined by the global VERBOSE setting and
  105. any passed 'disable' argument.
  106. bar_format (str): The format string for the progress bar. Uses the global TQDM_BAR_FORMAT if not
  107. explicitly set.
  108. Methods:
  109. __init__: Initializes the TQDM object with custom settings.
  110. Examples:
  111. >>> from ultralytics.utils import TQDM
  112. >>> for i in TQDM(range(100)):
  113. ... # Your processing code here
  114. ... pass
  115. """
  116. def __init__(self, *args, **kwargs):
  117. """
  118. Initializes a custom TQDM progress bar.
  119. This class extends the original tqdm class to provide customized behavior for Ultralytics projects.
  120. Args:
  121. *args (Any): Variable length argument list to be passed to the original tqdm constructor.
  122. **kwargs (Any): Arbitrary keyword arguments to be passed to the original tqdm constructor.
  123. Notes:
  124. - The progress bar is disabled if VERBOSE is False or if 'disable' is explicitly set to True in kwargs.
  125. - The default bar format is set to TQDM_BAR_FORMAT unless overridden in kwargs.
  126. Examples:
  127. >>> from ultralytics.utils import TQDM
  128. >>> for i in TQDM(range(100)):
  129. ... # Your code here
  130. ... pass
  131. """
  132. kwargs["disable"] = not VERBOSE or kwargs.get("disable", False) # logical 'and' with default value if passed
  133. kwargs.setdefault("bar_format", TQDM_BAR_FORMAT) # override default value if passed
  134. super().__init__(*args, **kwargs)
  135. class SimpleClass:
  136. """
  137. A simple base class for creating objects with string representations of their attributes.
  138. This class provides a foundation for creating objects that can be easily printed or represented as strings,
  139. showing all their non-callable attributes. It's useful for debugging and introspection of object states.
  140. Methods:
  141. __str__: Returns a human-readable string representation of the object.
  142. __repr__: Returns a machine-readable string representation of the object.
  143. __getattr__: Provides a custom attribute access error message with helpful information.
  144. Examples:
  145. >>> class MyClass(SimpleClass):
  146. ... def __init__(self):
  147. ... self.x = 10
  148. ... self.y = "hello"
  149. >>> obj = MyClass()
  150. >>> print(obj)
  151. __main__.MyClass object with attributes:
  152. x: 10
  153. y: 'hello'
  154. Notes:
  155. - This class is designed to be subclassed. It provides a convenient way to inspect object attributes.
  156. - The string representation includes the module and class name of the object.
  157. - Callable attributes and attributes starting with an underscore are excluded from the string representation.
  158. """
  159. def __str__(self):
  160. """Return a human-readable string representation of the object."""
  161. attr = []
  162. for a in dir(self):
  163. v = getattr(self, a)
  164. if not callable(v) and not a.startswith("_"):
  165. if isinstance(v, SimpleClass):
  166. # Display only the module and class name for subclasses
  167. s = f"{a}: {v.__module__}.{v.__class__.__name__} object"
  168. else:
  169. s = f"{a}: {repr(v)}"
  170. attr.append(s)
  171. return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr)
  172. def __repr__(self):
  173. """Return a machine-readable string representation of the object."""
  174. return self.__str__()
  175. def __getattr__(self, attr):
  176. """Custom attribute access error message with helpful information."""
  177. name = self.__class__.__name__
  178. raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
  179. class IterableSimpleNamespace(SimpleNamespace):
  180. """
  181. An iterable SimpleNamespace class that provides enhanced functionality for attribute access and iteration.
  182. This class extends the SimpleNamespace class with additional methods for iteration, string representation,
  183. and attribute access. It is designed to be used as a convenient container for storing and accessing
  184. configuration parameters.
  185. Methods:
  186. __iter__: Returns an iterator of key-value pairs from the namespace's attributes.
  187. __str__: Returns a human-readable string representation of the object.
  188. __getattr__: Provides a custom attribute access error message with helpful information.
  189. get: Retrieves the value of a specified key, or a default value if the key doesn't exist.
  190. Examples:
  191. >>> cfg = IterableSimpleNamespace(a=1, b=2, c=3)
  192. >>> for k, v in cfg:
  193. ... print(f"{k}: {v}")
  194. a: 1
  195. b: 2
  196. c: 3
  197. >>> print(cfg)
  198. a=1
  199. b=2
  200. c=3
  201. >>> cfg.get("b")
  202. 2
  203. >>> cfg.get("d", "default")
  204. 'default'
  205. Notes:
  206. This class is particularly useful for storing configuration parameters in a more accessible
  207. and iterable format compared to a standard dictionary.
  208. """
  209. def __iter__(self):
  210. """Return an iterator of key-value pairs from the namespace's attributes."""
  211. return iter(vars(self).items())
  212. def __str__(self):
  213. """Return a human-readable string representation of the object."""
  214. return "\n".join(f"{k}={v}" for k, v in vars(self).items())
  215. def __getattr__(self, attr):
  216. """Custom attribute access error message with helpful information."""
  217. name = self.__class__.__name__
  218. raise AttributeError(
  219. f"""
  220. '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics
  221. 'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace
  222. {DEFAULT_CFG_PATH} with the latest version from
  223. https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
  224. """
  225. )
  226. def get(self, key, default=None):
  227. """Return the value of the specified key if it exists; otherwise, return the default value."""
  228. return getattr(self, key, default)
  229. def plt_settings(rcparams=None, backend="Agg"):
  230. """
  231. Decorator to temporarily set rc parameters and the backend for a plotting function.
  232. Example:
  233. decorator: @plt_settings({"font.size": 12})
  234. context manager: with plt_settings({"font.size": 12}):
  235. Args:
  236. rcparams (dict): Dictionary of rc parameters to set.
  237. backend (str, optional): Name of the backend to use. Defaults to 'Agg'.
  238. Returns:
  239. (Callable): Decorated function with temporarily set rc parameters and backend. This decorator can be
  240. applied to any function that needs to have specific matplotlib rc parameters and backend for its execution.
  241. """
  242. if rcparams is None:
  243. rcparams = {"font.size": 11}
  244. def decorator(func):
  245. """Decorator to apply temporary rc parameters and backend to a function."""
  246. def wrapper(*args, **kwargs):
  247. """Sets rc parameters and backend, calls the original function, and restores the settings."""
  248. original_backend = plt.get_backend()
  249. switch = backend.lower() != original_backend.lower()
  250. if switch:
  251. plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8
  252. plt.switch_backend(backend)
  253. # Plot with backend and always revert to original backend
  254. try:
  255. with plt.rc_context(rcparams):
  256. result = func(*args, **kwargs)
  257. finally:
  258. if switch:
  259. plt.close("all")
  260. plt.switch_backend(original_backend)
  261. return result
  262. return wrapper
  263. return decorator
  264. def set_logging(name="LOGGING_NAME", verbose=True):
  265. """
  266. Sets up logging with UTF-8 encoding and configurable verbosity.
  267. This function configures logging for the Ultralytics library, setting the appropriate logging level and
  268. formatter based on the verbosity flag and the current process rank. It handles special cases for Windows
  269. environments where UTF-8 encoding might not be the default.
  270. Args:
  271. name (str): Name of the logger. Defaults to "LOGGING_NAME".
  272. verbose (bool): Flag to set logging level to INFO if True, ERROR otherwise. Defaults to True.
  273. Examples:
  274. >>> set_logging(name="ultralytics", verbose=True)
  275. >>> logger = logging.getLogger("ultralytics")
  276. >>> logger.info("This is an info message")
  277. Notes:
  278. - On Windows, this function attempts to reconfigure stdout to use UTF-8 encoding if possible.
  279. - If reconfiguration is not possible, it falls back to a custom formatter that handles non-UTF-8 environments.
  280. - The function sets up a StreamHandler with the appropriate formatter and level.
  281. - The logger's propagate flag is set to False to prevent duplicate logging in parent loggers.
  282. """
  283. level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR # rank in world for Multi-GPU trainings
  284. # Configure the console (stdout) encoding to UTF-8, with checks for compatibility
  285. formatter = logging.Formatter("%(message)s") # Default formatter
  286. if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8":
  287. class CustomFormatter(logging.Formatter):
  288. def format(self, record):
  289. """Sets up logging with UTF-8 encoding and configurable verbosity."""
  290. return emojis(super().format(record))
  291. try:
  292. # Attempt to reconfigure stdout to use UTF-8 encoding if possible
  293. if hasattr(sys.stdout, "reconfigure"):
  294. sys.stdout.reconfigure(encoding="utf-8")
  295. # For environments where reconfigure is not available, wrap stdout in a TextIOWrapper
  296. elif hasattr(sys.stdout, "buffer"):
  297. import io
  298. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
  299. else:
  300. formatter = CustomFormatter("%(message)s")
  301. except Exception as e:
  302. print(f"Creating custom formatter for non UTF-8 environments due to {e}")
  303. formatter = CustomFormatter("%(message)s")
  304. # Create and configure the StreamHandler with the appropriate formatter and level
  305. stream_handler = logging.StreamHandler(sys.stdout)
  306. stream_handler.setFormatter(formatter)
  307. stream_handler.setLevel(level)
  308. # Set up the logger
  309. logger = logging.getLogger(name)
  310. logger.setLevel(level)
  311. logger.addHandler(stream_handler)
  312. logger.propagate = False
  313. return logger
  314. # Set logger
  315. LOGGER = set_logging(LOGGING_NAME, verbose=VERBOSE) # define globally (used in train.py, val.py, predict.py, etc.)
  316. for logger in "sentry_sdk", "urllib3.connectionpool":
  317. logging.getLogger(logger).setLevel(logging.CRITICAL + 1)
  318. def emojis(string=""):
  319. """Return platform-dependent emoji-safe version of string."""
  320. return string.encode().decode("ascii", "ignore") if WINDOWS else string
  321. class ThreadingLocked:
  322. """
  323. A decorator class for ensuring thread-safe execution of a function or method. This class can be used as a decorator
  324. to make sure that if the decorated function is called from multiple threads, only one thread at a time will be able
  325. to execute the function.
  326. Attributes:
  327. lock (threading.Lock): A lock object used to manage access to the decorated function.
  328. Example:
  329. ```python
  330. from ultralytics.utils import ThreadingLocked
  331. @ThreadingLocked()
  332. def my_function():
  333. # Your code here
  334. ```
  335. """
  336. def __init__(self):
  337. """Initializes the decorator class for thread-safe execution of a function or method."""
  338. self.lock = threading.Lock()
  339. def __call__(self, f):
  340. """Run thread-safe execution of function or method."""
  341. from functools import wraps
  342. @wraps(f)
  343. def decorated(*args, **kwargs):
  344. """Applies thread-safety to the decorated function or method."""
  345. with self.lock:
  346. return f(*args, **kwargs)
  347. return decorated
  348. def yaml_save(file="data.yaml", data=None, header=""):
  349. """
  350. Save YAML data to a file.
  351. Args:
  352. file (str, optional): File name. Default is 'data.yaml'.
  353. data (dict): Data to save in YAML format.
  354. header (str, optional): YAML header to add.
  355. Returns:
  356. (None): Data is saved to the specified file.
  357. """
  358. if data is None:
  359. data = {}
  360. file = Path(file)
  361. if not file.parent.exists():
  362. # Create parent directories if they don't exist
  363. file.parent.mkdir(parents=True, exist_ok=True)
  364. # Convert Path objects to strings
  365. valid_types = int, float, str, bool, list, tuple, dict, type(None)
  366. for k, v in data.items():
  367. if not isinstance(v, valid_types):
  368. data[k] = str(v)
  369. # Dump data to file in YAML format
  370. with open(file, "w", errors="ignore", encoding="utf-8") as f:
  371. if header:
  372. f.write(header)
  373. yaml.safe_dump(data, f, sort_keys=False, allow_unicode=True)
  374. def yaml_load(file="data.yaml", append_filename=False):
  375. """
  376. Load YAML data from a file.
  377. Args:
  378. file (str, optional): File name. Default is 'data.yaml'.
  379. append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.
  380. Returns:
  381. (dict): YAML data and file name.
  382. """
  383. assert Path(file).suffix in {".yaml", ".yml"}, f"Attempting to load non-YAML file {file} with yaml_load()"
  384. with open(file, errors="ignore", encoding="utf-8") as f:
  385. s = f.read() # string
  386. # Remove special characters
  387. if not s.isprintable():
  388. s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+", "", s)
  389. # Add YAML filename to dict and return
  390. data = yaml.safe_load(s) or {} # always return a dict (yaml.safe_load() may return None for empty files)
  391. if append_filename:
  392. data["yaml_file"] = str(file)
  393. return data
  394. def yaml_print(yaml_file: Union[str, Path, dict]) -> None:
  395. """
  396. Pretty prints a YAML file or a YAML-formatted dictionary.
  397. Args:
  398. yaml_file: The file path of the YAML file or a YAML-formatted dictionary.
  399. Returns:
  400. (None)
  401. """
  402. yaml_dict = yaml_load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file
  403. dump = yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True, width=float("inf"))
  404. LOGGER.info(f"Printing '{colorstr('bold', 'black', yaml_file)}'\n\n{dump}")
  405. # Default configuration
  406. DEFAULT_CFG_DICT = yaml_load(DEFAULT_CFG_PATH)
  407. DEFAULT_SOL_DICT = yaml_load(DEFAULT_SOL_CFG_PATH) # Ultralytics solutions configuration
  408. for k, v in DEFAULT_CFG_DICT.items():
  409. if isinstance(v, str) and v.lower() == "none":
  410. DEFAULT_CFG_DICT[k] = None
  411. DEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys()
  412. DEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT)
  413. def read_device_model() -> str:
  414. """
  415. Reads the device model information from the system and caches it for quick access. Used by is_jetson() and
  416. is_raspberrypi().
  417. Returns:
  418. (str): Kernel release information.
  419. """
  420. return platform.release().lower()
  421. def is_ubuntu() -> bool:
  422. """
  423. Check if the OS is Ubuntu.
  424. Returns:
  425. (bool): True if OS is Ubuntu, False otherwise.
  426. """
  427. try:
  428. with open("/etc/os-release") as f:
  429. return "ID=ubuntu" in f.read()
  430. except FileNotFoundError:
  431. return False
  432. def is_colab():
  433. """
  434. Check if the current script is running inside a Google Colab notebook.
  435. Returns:
  436. (bool): True if running inside a Colab notebook, False otherwise.
  437. """
  438. return "COLAB_RELEASE_TAG" in os.environ or "COLAB_BACKEND_VERSION" in os.environ
  439. def is_kaggle():
  440. """
  441. Check if the current script is running inside a Kaggle kernel.
  442. Returns:
  443. (bool): True if running inside a Kaggle kernel, False otherwise.
  444. """
  445. return os.environ.get("PWD") == "/kaggle/working" and os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com"
  446. def is_jupyter():
  447. """
  448. Check if the current script is running inside a Jupyter Notebook.
  449. Returns:
  450. (bool): True if running inside a Jupyter Notebook, False otherwise.
  451. Note:
  452. - Only works on Colab and Kaggle, other environments like Jupyterlab and Paperspace are not reliably detectable.
  453. - "get_ipython" in globals() method suffers false positives when IPython package installed manually.
  454. """
  455. return IS_COLAB or IS_KAGGLE
  456. def is_runpod():
  457. """
  458. Check if the current script is running inside a RunPod container.
  459. Returns:
  460. (bool): True if running in RunPod, False otherwise.
  461. """
  462. return "RUNPOD_POD_ID" in os.environ
  463. def is_docker() -> bool:
  464. """
  465. Determine if the script is running inside a Docker container.
  466. Returns:
  467. (bool): True if the script is running inside a Docker container, False otherwise.
  468. """
  469. try:
  470. with open("/proc/self/cgroup") as f:
  471. return "docker" in f.read()
  472. except Exception:
  473. return False
  474. def is_raspberrypi() -> bool:
  475. """
  476. Determines if the Python environment is running on a Raspberry Pi by checking the device model information.
  477. Returns:
  478. (bool): True if running on a Raspberry Pi, False otherwise.
  479. """
  480. return "rpi" in DEVICE_MODEL
  481. def is_jetson() -> bool:
  482. """
  483. Determines if the Python environment is running on an NVIDIA Jetson device by checking the device model information.
  484. Returns:
  485. (bool): True if running on an NVIDIA Jetson device, False otherwise.
  486. """
  487. return "tegra" in DEVICE_MODEL
  488. def is_online() -> bool:
  489. """
  490. Check internet connectivity by attempting to connect to a known online host.
  491. Returns:
  492. (bool): True if connection is successful, False otherwise.
  493. """
  494. try:
  495. assert str(os.getenv("YOLO_OFFLINE", "")).lower() != "true" # check if ENV var YOLO_OFFLINE="True"
  496. import socket
  497. for dns in ("1.1.1.1", "8.8.8.8"): # check Cloudflare and Google DNS
  498. socket.create_connection(address=(dns, 80), timeout=2.0).close()
  499. return True
  500. except Exception:
  501. return False
  502. def is_pip_package(filepath: str = __name__) -> bool:
  503. """
  504. Determines if the file at the given filepath is part of a pip package.
  505. Args:
  506. filepath (str): The filepath to check.
  507. Returns:
  508. (bool): True if the file is part of a pip package, False otherwise.
  509. """
  510. import importlib.util
  511. # Get the spec for the module
  512. spec = importlib.util.find_spec(filepath)
  513. # Return whether the spec is not None and the origin is not None (indicating it is a package)
  514. return spec is not None and spec.origin is not None
  515. def is_dir_writeable(dir_path: Union[str, Path]) -> bool:
  516. """
  517. Check if a directory is writeable.
  518. Args:
  519. dir_path (str | Path): The path to the directory.
  520. Returns:
  521. (bool): True if the directory is writeable, False otherwise.
  522. """
  523. return os.access(str(dir_path), os.W_OK)
  524. def is_pytest_running():
  525. """
  526. Determines whether pytest is currently running or not.
  527. Returns:
  528. (bool): True if pytest is running, False otherwise.
  529. """
  530. return ("PYTEST_CURRENT_TEST" in os.environ) or ("pytest" in sys.modules) or ("pytest" in Path(ARGV[0]).stem)
  531. def is_github_action_running() -> bool:
  532. """
  533. Determine if the current environment is a GitHub Actions runner.
  534. Returns:
  535. (bool): True if the current environment is a GitHub Actions runner, False otherwise.
  536. """
  537. return "GITHUB_ACTIONS" in os.environ and "GITHUB_WORKFLOW" in os.environ and "RUNNER_OS" in os.environ
  538. def get_git_dir():
  539. """
  540. Determines whether the current file is part of a git repository and if so, returns the repository root directory. If
  541. the current file is not part of a git repository, returns None.
  542. Returns:
  543. (Path | None): Git root directory if found or None if not found.
  544. """
  545. for d in Path(__file__).parents:
  546. if (d / ".git").is_dir():
  547. return d
  548. def is_git_dir():
  549. """
  550. Determines whether the current file is part of a git repository. If the current file is not part of a git
  551. repository, returns None.
  552. Returns:
  553. (bool): True if current file is part of a git repository.
  554. """
  555. return GIT_DIR is not None
  556. def get_git_origin_url():
  557. """
  558. Retrieves the origin URL of a git repository.
  559. Returns:
  560. (str | None): The origin URL of the git repository or None if not git directory.
  561. """
  562. if IS_GIT_DIR:
  563. try:
  564. origin = subprocess.check_output(["git", "config", "--get", "remote.origin.url"])
  565. return origin.decode().strip()
  566. except subprocess.CalledProcessError:
  567. return None
  568. def get_git_branch():
  569. """
  570. Returns the current git branch name. If not in a git repository, returns None.
  571. Returns:
  572. (str | None): The current git branch name or None if not a git directory.
  573. """
  574. if IS_GIT_DIR:
  575. try:
  576. origin = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"])
  577. return origin.decode().strip()
  578. except subprocess.CalledProcessError:
  579. return None
  580. def get_default_args(func):
  581. """
  582. Returns a dictionary of default arguments for a function.
  583. Args:
  584. func (callable): The function to inspect.
  585. Returns:
  586. (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.
  587. """
  588. signature = inspect.signature(func)
  589. return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}
  590. def get_ubuntu_version():
  591. """
  592. Retrieve the Ubuntu version if the OS is Ubuntu.
  593. Returns:
  594. (str): Ubuntu version or None if not an Ubuntu OS.
  595. """
  596. if is_ubuntu():
  597. try:
  598. with open("/etc/os-release") as f:
  599. return re.search(r'VERSION_ID="(\d+\.\d+)"', f.read())[1]
  600. except (FileNotFoundError, AttributeError):
  601. return None
  602. def get_user_config_dir(sub_dir="yolov13"):
  603. """
  604. Return the appropriate config directory based on the environment operating system.
  605. Args:
  606. sub_dir (str): The name of the subdirectory to create.
  607. Returns:
  608. (Path): The path to the user config directory.
  609. """
  610. if WINDOWS:
  611. path = Path.home() / "AppData" / "Roaming" / sub_dir
  612. elif MACOS: # macOS
  613. path = Path.home() / "Library" / "Application Support" / sub_dir
  614. elif LINUX:
  615. path = Path.home() / ".config" / sub_dir
  616. else:
  617. raise ValueError(f"Unsupported operating system: {platform.system()}")
  618. # GCP and AWS lambda fix, only /tmp is writeable
  619. if not is_dir_writeable(path.parent):
  620. LOGGER.warning(
  621. f"WARNING ⚠️ user config directory '{path}' is not writeable, defaulting to '/tmp' or CWD."
  622. "Alternatively you can define a YOLO_CONFIG_DIR environment variable for this path."
  623. )
  624. path = Path("/tmp") / sub_dir if is_dir_writeable("/tmp") else Path().cwd() / sub_dir
  625. # Create the subdirectory if it does not exist
  626. path.mkdir(parents=True, exist_ok=True)
  627. return path
  628. # Define constants (required below)
  629. DEVICE_MODEL = read_device_model() # is_jetson() and is_raspberrypi() depend on this constant
  630. ONLINE = is_online()
  631. IS_COLAB = is_colab()
  632. IS_KAGGLE = is_kaggle()
  633. IS_DOCKER = is_docker()
  634. IS_JETSON = is_jetson()
  635. IS_JUPYTER = is_jupyter()
  636. IS_PIP_PACKAGE = is_pip_package()
  637. IS_RASPBERRYPI = is_raspberrypi()
  638. GIT_DIR = get_git_dir()
  639. IS_GIT_DIR = is_git_dir()
  640. USER_CONFIG_DIR = Path(os.getenv("YOLO_CONFIG_DIR") or get_user_config_dir()) # Ultralytics settings dir
  641. SETTINGS_FILE = USER_CONFIG_DIR / "settings.json"
  642. def colorstr(*input):
  643. r"""
  644. Colors a string based on the provided color and style arguments. Utilizes ANSI escape codes.
  645. See https://en.wikipedia.org/wiki/ANSI_escape_code for more details.
  646. This function can be called in two ways:
  647. - colorstr('color', 'style', 'your string')
  648. - colorstr('your string')
  649. In the second form, 'blue' and 'bold' will be applied by default.
  650. Args:
  651. *input (str | Path): A sequence of strings where the first n-1 strings are color and style arguments,
  652. and the last string is the one to be colored.
  653. Supported Colors and Styles:
  654. Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
  655. Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow',
  656. 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white'
  657. Misc: 'end', 'bold', 'underline'
  658. Returns:
  659. (str): The input string wrapped with ANSI escape codes for the specified color and style.
  660. Examples:
  661. >>> colorstr("blue", "bold", "hello world")
  662. >>> "\033[34m\033[1mhello world\033[0m"
  663. """
  664. *args, string = input if len(input) > 1 else ("blue", "bold", input[0]) # color arguments, string
  665. colors = {
  666. "black": "\033[30m", # basic colors
  667. "red": "\033[31m",
  668. "green": "\033[32m",
  669. "yellow": "\033[33m",
  670. "blue": "\033[34m",
  671. "magenta": "\033[35m",
  672. "cyan": "\033[36m",
  673. "white": "\033[37m",
  674. "bright_black": "\033[90m", # bright colors
  675. "bright_red": "\033[91m",
  676. "bright_green": "\033[92m",
  677. "bright_yellow": "\033[93m",
  678. "bright_blue": "\033[94m",
  679. "bright_magenta": "\033[95m",
  680. "bright_cyan": "\033[96m",
  681. "bright_white": "\033[97m",
  682. "end": "\033[0m", # misc
  683. "bold": "\033[1m",
  684. "underline": "\033[4m",
  685. }
  686. return "".join(colors[x] for x in args) + f"{string}" + colors["end"]
  687. def remove_colorstr(input_string):
  688. """
  689. Removes ANSI escape codes from a string, effectively un-coloring it.
  690. Args:
  691. input_string (str): The string to remove color and style from.
  692. Returns:
  693. (str): A new string with all ANSI escape codes removed.
  694. Examples:
  695. >>> remove_colorstr(colorstr("blue", "bold", "hello world"))
  696. >>> "hello world"
  697. """
  698. ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
  699. return ansi_escape.sub("", input_string)
  700. class TryExcept(contextlib.ContextDecorator):
  701. """
  702. Ultralytics TryExcept class. Use as @TryExcept() decorator or 'with TryExcept():' context manager.
  703. Examples:
  704. As a decorator:
  705. >>> @TryExcept(msg="Error occurred in func", verbose=True)
  706. >>> def func():
  707. >>> # Function logic here
  708. >>> pass
  709. As a context manager:
  710. >>> with TryExcept(msg="Error occurred in block", verbose=True):
  711. >>> # Code block here
  712. >>> pass
  713. """
  714. def __init__(self, msg="", verbose=True):
  715. """Initialize TryExcept class with optional message and verbosity settings."""
  716. self.msg = msg
  717. self.verbose = verbose
  718. def __enter__(self):
  719. """Executes when entering TryExcept context, initializes instance."""
  720. pass
  721. def __exit__(self, exc_type, value, traceback):
  722. """Defines behavior when exiting a 'with' block, prints error message if necessary."""
  723. if self.verbose and value:
  724. print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
  725. return True
  726. class Retry(contextlib.ContextDecorator):
  727. """
  728. Retry class for function execution with exponential backoff.
  729. Can be used as a decorator to retry a function on exceptions, up to a specified number of times with an
  730. exponentially increasing delay between retries.
  731. Examples:
  732. Example usage as a decorator:
  733. >>> @Retry(times=3, delay=2)
  734. >>> def test_func():
  735. >>> # Replace with function logic that may raise exceptions
  736. >>> return True
  737. """
  738. def __init__(self, times=3, delay=2):
  739. """Initialize Retry class with specified number of retries and delay."""
  740. self.times = times
  741. self.delay = delay
  742. self._attempts = 0
  743. def __call__(self, func):
  744. """Decorator implementation for Retry with exponential backoff."""
  745. def wrapped_func(*args, **kwargs):
  746. """Applies retries to the decorated function or method."""
  747. self._attempts = 0
  748. while self._attempts < self.times:
  749. try:
  750. return func(*args, **kwargs)
  751. except Exception as e:
  752. self._attempts += 1
  753. print(f"Retry {self._attempts}/{self.times} failed: {e}")
  754. if self._attempts >= self.times:
  755. raise e
  756. time.sleep(self.delay * (2**self._attempts)) # exponential backoff delay
  757. return wrapped_func
  758. def threaded(func):
  759. """
  760. Multi-threads a target function by default and returns the thread or function result.
  761. Use as @threaded decorator. The function runs in a separate thread unless 'threaded=False' is passed.
  762. """
  763. def wrapper(*args, **kwargs):
  764. """Multi-threads a given function based on 'threaded' kwarg and returns the thread or function result."""
  765. if kwargs.pop("threaded", True): # run in thread
  766. thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
  767. thread.start()
  768. return thread
  769. else:
  770. return func(*args, **kwargs)
  771. return wrapper
  772. def set_sentry():
  773. """
  774. Initialize the Sentry SDK for error tracking and reporting. Only used if sentry_sdk package is installed and
  775. sync=True in settings. Run 'yolo settings' to see and update settings.
  776. Conditions required to send errors (ALL conditions must be met or no errors will be reported):
  777. - sentry_sdk package is installed
  778. - sync=True in YOLO settings
  779. - pytest is not running
  780. - running in a pip package installation
  781. - running in a non-git directory
  782. - running with rank -1 or 0
  783. - online environment
  784. - CLI used to run package (checked with 'yolo' as the name of the main CLI command)
  785. The function also configures Sentry SDK to ignore KeyboardInterrupt and FileNotFoundError exceptions and to exclude
  786. events with 'out of memory' in their exception message.
  787. Additionally, the function sets custom tags and user information for Sentry events.
  788. """
  789. if (
  790. not SETTINGS["sync"]
  791. or RANK not in {-1, 0}
  792. or Path(ARGV[0]).name != "yolo"
  793. or TESTS_RUNNING
  794. or not ONLINE
  795. or not IS_PIP_PACKAGE
  796. or IS_GIT_DIR
  797. ):
  798. return
  799. # If sentry_sdk package is not installed then return and do not use Sentry
  800. try:
  801. import sentry_sdk # noqa
  802. except ImportError:
  803. return
  804. def before_send(event, hint):
  805. """
  806. Modify the event before sending it to Sentry based on specific exception types and messages.
  807. Args:
  808. event (dict): The event dictionary containing information about the error.
  809. hint (dict): A dictionary containing additional information about the error.
  810. Returns:
  811. dict: The modified event or None if the event should not be sent to Sentry.
  812. """
  813. if "exc_info" in hint:
  814. exc_type, exc_value, _ = hint["exc_info"]
  815. if exc_type in {KeyboardInterrupt, FileNotFoundError} or "out of memory" in str(exc_value):
  816. return None # do not send event
  817. event["tags"] = {
  818. "sys_argv": ARGV[0],
  819. "sys_argv_name": Path(ARGV[0]).name,
  820. "install": "git" if IS_GIT_DIR else "pip" if IS_PIP_PACKAGE else "other",
  821. "os": ENVIRONMENT,
  822. }
  823. return event
  824. sentry_sdk.init(
  825. dsn="https://888e5a0778212e1d0314c37d4b9aae5d@o4504521589325824.ingest.us.sentry.io/4504521592406016",
  826. debug=False,
  827. auto_enabling_integrations=False,
  828. traces_sample_rate=1.0,
  829. release=__version__,
  830. environment="runpod" if is_runpod() else "production",
  831. before_send=before_send,
  832. ignore_errors=[KeyboardInterrupt, FileNotFoundError],
  833. )
  834. sentry_sdk.set_user({"id": SETTINGS["uuid"]}) # SHA-256 anonymized UUID hash
  835. class JSONDict(dict):
  836. """
  837. A dictionary-like class that provides JSON persistence for its contents.
  838. This class extends the built-in dictionary to automatically save its contents to a JSON file whenever they are
  839. modified. It ensures thread-safe operations using a lock.
  840. Attributes:
  841. file_path (Path): The path to the JSON file used for persistence.
  842. lock (threading.Lock): A lock object to ensure thread-safe operations.
  843. Methods:
  844. _load: Loads the data from the JSON file into the dictionary.
  845. _save: Saves the current state of the dictionary to the JSON file.
  846. __setitem__: Stores a key-value pair and persists it to disk.
  847. __delitem__: Removes an item and updates the persistent storage.
  848. update: Updates the dictionary and persists changes.
  849. clear: Clears all entries and updates the persistent storage.
  850. Examples:
  851. >>> json_dict = JSONDict("data.json")
  852. >>> json_dict["key"] = "value"
  853. >>> print(json_dict["key"])
  854. value
  855. >>> del json_dict["key"]
  856. >>> json_dict.update({"new_key": "new_value"})
  857. >>> json_dict.clear()
  858. """
  859. def __init__(self, file_path: Union[str, Path] = "data.json"):
  860. """Initialize a JSONDict object with a specified file path for JSON persistence."""
  861. super().__init__()
  862. self.file_path = Path(file_path)
  863. self.lock = Lock()
  864. self._load()
  865. def _load(self):
  866. """Load the data from the JSON file into the dictionary."""
  867. try:
  868. if self.file_path.exists():
  869. with open(self.file_path) as f:
  870. self.update(json.load(f))
  871. except json.JSONDecodeError:
  872. print(f"Error decoding JSON from {self.file_path}. Starting with an empty dictionary.")
  873. except Exception as e:
  874. print(f"Error reading from {self.file_path}: {e}")
  875. def _save(self):
  876. """Save the current state of the dictionary to the JSON file."""
  877. try:
  878. self.file_path.parent.mkdir(parents=True, exist_ok=True)
  879. with open(self.file_path, "w") as f:
  880. json.dump(dict(self), f, indent=2, default=self._json_default)
  881. except Exception as e:
  882. print(f"Error writing to {self.file_path}: {e}")
  883. @staticmethod
  884. def _json_default(obj):
  885. """Handle JSON serialization of Path objects."""
  886. if isinstance(obj, Path):
  887. return str(obj)
  888. raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
  889. def __setitem__(self, key, value):
  890. """Store a key-value pair and persist to disk."""
  891. with self.lock:
  892. super().__setitem__(key, value)
  893. self._save()
  894. def __delitem__(self, key):
  895. """Remove an item and update the persistent storage."""
  896. with self.lock:
  897. super().__delitem__(key)
  898. self._save()
  899. def __str__(self):
  900. """Return a pretty-printed JSON string representation of the dictionary."""
  901. contents = json.dumps(dict(self), indent=2, ensure_ascii=False, default=self._json_default)
  902. return f'JSONDict("{self.file_path}"):\n{contents}'
  903. def update(self, *args, **kwargs):
  904. """Update the dictionary and persist changes."""
  905. with self.lock:
  906. super().update(*args, **kwargs)
  907. self._save()
  908. def clear(self):
  909. """Clear all entries and update the persistent storage."""
  910. with self.lock:
  911. super().clear()
  912. self._save()
  913. class SettingsManager(JSONDict):
  914. """
  915. SettingsManager class for managing and persisting Ultralytics settings.
  916. This class extends JSONDict to provide JSON persistence for settings, ensuring thread-safe operations and default
  917. values. It validates settings on initialization and provides methods to update or reset settings.
  918. Attributes:
  919. file (Path): The path to the JSON file used for persistence.
  920. version (str): The version of the settings schema.
  921. defaults (Dict): A dictionary containing default settings.
  922. help_msg (str): A help message for users on how to view and update settings.
  923. Methods:
  924. _validate_settings: Validates the current settings and resets if necessary.
  925. update: Updates settings, validating keys and types.
  926. reset: Resets the settings to default and saves them.
  927. Examples:
  928. Initialize and update settings:
  929. >>> settings = SettingsManager()
  930. >>> settings.update(runs_dir="/new/runs/dir")
  931. >>> print(settings["runs_dir"])
  932. /new/runs/dir
  933. """
  934. def __init__(self, file=SETTINGS_FILE, version="0.0.6"):
  935. """Initializes the SettingsManager with default settings and loads user settings."""
  936. import hashlib
  937. from ultralytics.utils.torch_utils import torch_distributed_zero_first
  938. root = GIT_DIR or Path()
  939. datasets_root = (root.parent if GIT_DIR and is_dir_writeable(root.parent) else root).resolve()
  940. self.file = Path(file)
  941. self.version = version
  942. self.defaults = {
  943. "settings_version": version, # Settings schema version
  944. "datasets_dir": str(datasets_root / "datasets"), # Datasets directory
  945. "weights_dir": str(root / "weights"), # Model weights directory
  946. "runs_dir": str(root / "runs"), # Experiment runs directory
  947. "uuid": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(), # SHA-256 anonymized UUID hash
  948. "sync": True, # Enable synchronization
  949. "api_key": "", # Ultralytics API Key
  950. "openai_api_key": "", # OpenAI API Key
  951. "clearml": True, # ClearML integration
  952. "comet": True, # Comet integration
  953. "dvc": True, # DVC integration
  954. "hub": True, # Ultralytics HUB integration
  955. "mlflow": True, # MLflow integration
  956. "neptune": True, # Neptune integration
  957. "raytune": True, # Ray Tune integration
  958. "tensorboard": True, # TensorBoard logging
  959. "wandb": False, # Weights & Biases logging
  960. "vscode_msg": True, # VSCode messaging
  961. }
  962. self.help_msg = (
  963. f"\nView Ultralytics Settings with 'yolo settings' or at '{self.file}'"
  964. "\nUpdate Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. "
  965. "For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings."
  966. )
  967. with torch_distributed_zero_first(RANK):
  968. super().__init__(self.file)
  969. if not self.file.exists() or not self: # Check if file doesn't exist or is empty
  970. LOGGER.info(f"Creating new Ultralytics Settings v{version} file ✅ {self.help_msg}")
  971. self.reset()
  972. self._validate_settings()
  973. def _validate_settings(self):
  974. """Validate the current settings and reset if necessary."""
  975. correct_keys = set(self.keys()) == set(self.defaults.keys())
  976. correct_types = all(isinstance(self.get(k), type(v)) for k, v in self.defaults.items())
  977. correct_version = self.get("settings_version", "") == self.version
  978. if not (correct_keys and correct_types and correct_version):
  979. LOGGER.warning(
  980. "WARNING ⚠️ Ultralytics settings reset to default values. This may be due to a possible problem "
  981. f"with your settings or a recent ultralytics package update. {self.help_msg}"
  982. )
  983. self.reset()
  984. if self.get("datasets_dir") == self.get("runs_dir"):
  985. LOGGER.warning(
  986. f"WARNING ⚠️ Ultralytics setting 'datasets_dir: {self.get('datasets_dir')}' "
  987. f"must be different than 'runs_dir: {self.get('runs_dir')}'. "
  988. f"Please change one to avoid possible issues during training. {self.help_msg}"
  989. )
  990. def __setitem__(self, key, value):
  991. """Updates one key: value pair."""
  992. self.update({key: value})
  993. def update(self, *args, **kwargs):
  994. """Updates settings, validating keys and types."""
  995. for arg in args:
  996. if isinstance(arg, dict):
  997. kwargs.update(arg)
  998. for k, v in kwargs.items():
  999. if k not in self.defaults:
  1000. raise KeyError(f"No Ultralytics setting '{k}'. {self.help_msg}")
  1001. t = type(self.defaults[k])
  1002. if not isinstance(v, t):
  1003. raise TypeError(
  1004. f"Ultralytics setting '{k}' must be '{t.__name__}' type, not '{type(v).__name__}'. {self.help_msg}"
  1005. )
  1006. super().update(*args, **kwargs)
  1007. def reset(self):
  1008. """Resets the settings to default and saves them."""
  1009. self.clear()
  1010. self.update(self.defaults)
  1011. def deprecation_warn(arg, new_arg=None):
  1012. """Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument."""
  1013. msg = f"WARNING ⚠️ '{arg}' is deprecated and will be removed in in the future."
  1014. if new_arg is not None:
  1015. msg += f" Use '{new_arg}' instead."
  1016. LOGGER.warning(msg)
  1017. def clean_url(url):
  1018. """Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt."""
  1019. url = Path(url).as_posix().replace(":/", "://") # Pathlib turns :// -> :/, as_posix() for Windows
  1020. return unquote(url).split("?")[0] # '%2F' to '/', split https://url.com/file.txt?auth
  1021. def url2file(url):
  1022. """Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt."""
  1023. return Path(clean_url(url)).name
  1024. def vscode_msg(ext="ultralytics.ultralytics-snippets") -> str:
  1025. """Display a message to install Ultralytics-Snippets for VS Code if not already installed."""
  1026. path = (USER_CONFIG_DIR.parents[2] if WINDOWS else USER_CONFIG_DIR.parents[1]) / ".vscode/extensions"
  1027. obs_file = path / ".obsolete" # file tracks uninstalled extensions, while source directory remains
  1028. installed = any(path.glob(f"{ext}*")) and ext not in (obs_file.read_text("utf-8") if obs_file.exists() else "")
  1029. url = "https://docs.ultralytics.com/integrations/vscode"
  1030. return "" if installed else f"{colorstr('VS Code:')} view Ultralytics VS Code Extension ⚡ at {url}"
  1031. # Run below code on utils init ------------------------------------------------------------------------------------
  1032. # Check first-install steps
  1033. PREFIX = colorstr("Ultralytics: ")
  1034. SETTINGS = SettingsManager() # initialize settings
  1035. PERSISTENT_CACHE = JSONDict(USER_CONFIG_DIR / "persistent_cache.json") # initialize persistent cache
  1036. DATASETS_DIR = Path(SETTINGS["datasets_dir"]) # global datasets directory
  1037. WEIGHTS_DIR = Path(SETTINGS["weights_dir"]) # global weights directory
  1038. RUNS_DIR = Path(SETTINGS["runs_dir"]) # global runs directory
  1039. ENVIRONMENT = (
  1040. "Colab"
  1041. if IS_COLAB
  1042. else "Kaggle"
  1043. if IS_KAGGLE
  1044. else "Jupyter"
  1045. if IS_JUPYTER
  1046. else "Docker"
  1047. if IS_DOCKER
  1048. else platform.system()
  1049. )
  1050. TESTS_RUNNING = is_pytest_running() or is_github_action_running()
  1051. set_sentry()
  1052. # Apply monkey patches
  1053. from ultralytics.utils.patches import imread, imshow, imwrite, torch_load, torch_save
  1054. torch.load = torch_load
  1055. torch.save = torch_save
  1056. if WINDOWS:
  1057. # Apply cv2 patches for non-ASCII and non-UTF characters in image paths
  1058. cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow