dgenerate-ultralytics-headless 8.3.134__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
  2. dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
  3. dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +22 -0
  8. tests/conftest.py +83 -0
  9. tests/test_cli.py +138 -0
  10. tests/test_cuda.py +215 -0
  11. tests/test_engine.py +131 -0
  12. tests/test_exports.py +236 -0
  13. tests/test_integrations.py +154 -0
  14. tests/test_python.py +694 -0
  15. tests/test_solutions.py +187 -0
  16. ultralytics/__init__.py +30 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1023 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +77 -0
  21. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  22. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  23. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  24. ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +443 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/VOC.yaml +106 -0
  29. ultralytics/cfg/datasets/VisDrone.yaml +77 -0
  30. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  31. ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
  32. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  33. ultralytics/cfg/datasets/coco-pose.yaml +42 -0
  34. ultralytics/cfg/datasets/coco.yaml +118 -0
  35. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  36. ultralytics/cfg/datasets/coco128.yaml +101 -0
  37. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  38. ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
  39. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  40. ultralytics/cfg/datasets/coco8.yaml +101 -0
  41. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  42. ultralytics/cfg/datasets/dog-pose.yaml +24 -0
  43. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  44. ultralytics/cfg/datasets/dota8.yaml +35 -0
  45. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
  46. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  47. ultralytics/cfg/datasets/medical-pills.yaml +22 -0
  48. ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
  49. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  50. ultralytics/cfg/datasets/signature.yaml +21 -0
  51. ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
  52. ultralytics/cfg/datasets/xView.yaml +155 -0
  53. ultralytics/cfg/default.yaml +127 -0
  54. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  55. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  56. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  57. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  58. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  59. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  60. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  61. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  62. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  63. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  64. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  65. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  68. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  69. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  70. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  71. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  74. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  75. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  77. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  78. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  79. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  80. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  81. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  82. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  83. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
  84. ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
  85. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  86. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  87. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  88. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  89. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  90. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  91. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  92. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  93. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  94. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  95. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  96. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  97. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  99. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  100. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  102. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  103. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  105. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  106. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  109. ultralytics/cfg/trackers/botsort.yaml +22 -0
  110. ultralytics/cfg/trackers/bytetrack.yaml +14 -0
  111. ultralytics/data/__init__.py +26 -0
  112. ultralytics/data/annotator.py +66 -0
  113. ultralytics/data/augment.py +2945 -0
  114. ultralytics/data/base.py +438 -0
  115. ultralytics/data/build.py +258 -0
  116. ultralytics/data/converter.py +754 -0
  117. ultralytics/data/dataset.py +834 -0
  118. ultralytics/data/loaders.py +676 -0
  119. ultralytics/data/scripts/download_weights.sh +18 -0
  120. ultralytics/data/scripts/get_coco.sh +61 -0
  121. ultralytics/data/scripts/get_coco128.sh +18 -0
  122. ultralytics/data/scripts/get_imagenet.sh +52 -0
  123. ultralytics/data/split.py +125 -0
  124. ultralytics/data/split_dota.py +325 -0
  125. ultralytics/data/utils.py +777 -0
  126. ultralytics/engine/__init__.py +1 -0
  127. ultralytics/engine/exporter.py +1519 -0
  128. ultralytics/engine/model.py +1156 -0
  129. ultralytics/engine/predictor.py +502 -0
  130. ultralytics/engine/results.py +1840 -0
  131. ultralytics/engine/trainer.py +853 -0
  132. ultralytics/engine/tuner.py +243 -0
  133. ultralytics/engine/validator.py +377 -0
  134. ultralytics/hub/__init__.py +168 -0
  135. ultralytics/hub/auth.py +137 -0
  136. ultralytics/hub/google/__init__.py +176 -0
  137. ultralytics/hub/session.py +446 -0
  138. ultralytics/hub/utils.py +248 -0
  139. ultralytics/models/__init__.py +9 -0
  140. ultralytics/models/fastsam/__init__.py +7 -0
  141. ultralytics/models/fastsam/model.py +61 -0
  142. ultralytics/models/fastsam/predict.py +181 -0
  143. ultralytics/models/fastsam/utils.py +24 -0
  144. ultralytics/models/fastsam/val.py +40 -0
  145. ultralytics/models/nas/__init__.py +7 -0
  146. ultralytics/models/nas/model.py +102 -0
  147. ultralytics/models/nas/predict.py +58 -0
  148. ultralytics/models/nas/val.py +39 -0
  149. ultralytics/models/rtdetr/__init__.py +7 -0
  150. ultralytics/models/rtdetr/model.py +63 -0
  151. ultralytics/models/rtdetr/predict.py +84 -0
  152. ultralytics/models/rtdetr/train.py +85 -0
  153. ultralytics/models/rtdetr/val.py +191 -0
  154. ultralytics/models/sam/__init__.py +6 -0
  155. ultralytics/models/sam/amg.py +260 -0
  156. ultralytics/models/sam/build.py +358 -0
  157. ultralytics/models/sam/model.py +170 -0
  158. ultralytics/models/sam/modules/__init__.py +1 -0
  159. ultralytics/models/sam/modules/blocks.py +1129 -0
  160. ultralytics/models/sam/modules/decoders.py +515 -0
  161. ultralytics/models/sam/modules/encoders.py +854 -0
  162. ultralytics/models/sam/modules/memory_attention.py +299 -0
  163. ultralytics/models/sam/modules/sam.py +1006 -0
  164. ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
  165. ultralytics/models/sam/modules/transformer.py +351 -0
  166. ultralytics/models/sam/modules/utils.py +394 -0
  167. ultralytics/models/sam/predict.py +1605 -0
  168. ultralytics/models/utils/__init__.py +1 -0
  169. ultralytics/models/utils/loss.py +455 -0
  170. ultralytics/models/utils/ops.py +268 -0
  171. ultralytics/models/yolo/__init__.py +7 -0
  172. ultralytics/models/yolo/classify/__init__.py +7 -0
  173. ultralytics/models/yolo/classify/predict.py +88 -0
  174. ultralytics/models/yolo/classify/train.py +233 -0
  175. ultralytics/models/yolo/classify/val.py +215 -0
  176. ultralytics/models/yolo/detect/__init__.py +7 -0
  177. ultralytics/models/yolo/detect/predict.py +124 -0
  178. ultralytics/models/yolo/detect/train.py +217 -0
  179. ultralytics/models/yolo/detect/val.py +451 -0
  180. ultralytics/models/yolo/model.py +354 -0
  181. ultralytics/models/yolo/obb/__init__.py +7 -0
  182. ultralytics/models/yolo/obb/predict.py +66 -0
  183. ultralytics/models/yolo/obb/train.py +81 -0
  184. ultralytics/models/yolo/obb/val.py +283 -0
  185. ultralytics/models/yolo/pose/__init__.py +7 -0
  186. ultralytics/models/yolo/pose/predict.py +79 -0
  187. ultralytics/models/yolo/pose/train.py +154 -0
  188. ultralytics/models/yolo/pose/val.py +394 -0
  189. ultralytics/models/yolo/segment/__init__.py +7 -0
  190. ultralytics/models/yolo/segment/predict.py +113 -0
  191. ultralytics/models/yolo/segment/train.py +123 -0
  192. ultralytics/models/yolo/segment/val.py +428 -0
  193. ultralytics/models/yolo/world/__init__.py +5 -0
  194. ultralytics/models/yolo/world/train.py +119 -0
  195. ultralytics/models/yolo/world/train_world.py +176 -0
  196. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  197. ultralytics/models/yolo/yoloe/predict.py +169 -0
  198. ultralytics/models/yolo/yoloe/train.py +298 -0
  199. ultralytics/models/yolo/yoloe/train_seg.py +124 -0
  200. ultralytics/models/yolo/yoloe/val.py +191 -0
  201. ultralytics/nn/__init__.py +29 -0
  202. ultralytics/nn/autobackend.py +842 -0
  203. ultralytics/nn/modules/__init__.py +182 -0
  204. ultralytics/nn/modules/activation.py +53 -0
  205. ultralytics/nn/modules/block.py +1966 -0
  206. ultralytics/nn/modules/conv.py +712 -0
  207. ultralytics/nn/modules/head.py +880 -0
  208. ultralytics/nn/modules/transformer.py +713 -0
  209. ultralytics/nn/modules/utils.py +164 -0
  210. ultralytics/nn/tasks.py +1627 -0
  211. ultralytics/nn/text_model.py +351 -0
  212. ultralytics/solutions/__init__.py +41 -0
  213. ultralytics/solutions/ai_gym.py +116 -0
  214. ultralytics/solutions/analytics.py +252 -0
  215. ultralytics/solutions/config.py +106 -0
  216. ultralytics/solutions/distance_calculation.py +124 -0
  217. ultralytics/solutions/heatmap.py +127 -0
  218. ultralytics/solutions/instance_segmentation.py +84 -0
  219. ultralytics/solutions/object_blurrer.py +90 -0
  220. ultralytics/solutions/object_counter.py +195 -0
  221. ultralytics/solutions/object_cropper.py +84 -0
  222. ultralytics/solutions/parking_management.py +273 -0
  223. ultralytics/solutions/queue_management.py +93 -0
  224. ultralytics/solutions/region_counter.py +120 -0
  225. ultralytics/solutions/security_alarm.py +154 -0
  226. ultralytics/solutions/similarity_search.py +172 -0
  227. ultralytics/solutions/solutions.py +724 -0
  228. ultralytics/solutions/speed_estimation.py +110 -0
  229. ultralytics/solutions/streamlit_inference.py +196 -0
  230. ultralytics/solutions/templates/similarity-search.html +160 -0
  231. ultralytics/solutions/trackzone.py +88 -0
  232. ultralytics/solutions/vision_eye.py +68 -0
  233. ultralytics/trackers/__init__.py +7 -0
  234. ultralytics/trackers/basetrack.py +124 -0
  235. ultralytics/trackers/bot_sort.py +260 -0
  236. ultralytics/trackers/byte_tracker.py +480 -0
  237. ultralytics/trackers/track.py +125 -0
  238. ultralytics/trackers/utils/__init__.py +1 -0
  239. ultralytics/trackers/utils/gmc.py +376 -0
  240. ultralytics/trackers/utils/kalman_filter.py +493 -0
  241. ultralytics/trackers/utils/matching.py +157 -0
  242. ultralytics/utils/__init__.py +1435 -0
  243. ultralytics/utils/autobatch.py +106 -0
  244. ultralytics/utils/autodevice.py +174 -0
  245. ultralytics/utils/benchmarks.py +695 -0
  246. ultralytics/utils/callbacks/__init__.py +5 -0
  247. ultralytics/utils/callbacks/base.py +234 -0
  248. ultralytics/utils/callbacks/clearml.py +153 -0
  249. ultralytics/utils/callbacks/comet.py +552 -0
  250. ultralytics/utils/callbacks/dvc.py +205 -0
  251. ultralytics/utils/callbacks/hub.py +108 -0
  252. ultralytics/utils/callbacks/mlflow.py +138 -0
  253. ultralytics/utils/callbacks/neptune.py +140 -0
  254. ultralytics/utils/callbacks/raytune.py +43 -0
  255. ultralytics/utils/callbacks/tensorboard.py +132 -0
  256. ultralytics/utils/callbacks/wb.py +185 -0
  257. ultralytics/utils/checks.py +897 -0
  258. ultralytics/utils/dist.py +119 -0
  259. ultralytics/utils/downloads.py +499 -0
  260. ultralytics/utils/errors.py +43 -0
  261. ultralytics/utils/export.py +219 -0
  262. ultralytics/utils/files.py +221 -0
  263. ultralytics/utils/instance.py +499 -0
  264. ultralytics/utils/loss.py +813 -0
  265. ultralytics/utils/metrics.py +1356 -0
  266. ultralytics/utils/ops.py +885 -0
  267. ultralytics/utils/patches.py +143 -0
  268. ultralytics/utils/plotting.py +1011 -0
  269. ultralytics/utils/tal.py +416 -0
  270. ultralytics/utils/torch_utils.py +990 -0
  271. ultralytics/utils/triton.py +116 -0
  272. ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,1435 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import contextlib
4
+ import importlib.metadata
5
+ import inspect
6
+ import json
7
+ import logging
8
+ import os
9
+ import platform
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ import threading
14
+ import time
15
+ import warnings
16
+ from pathlib import Path
17
+ from threading import Lock
18
+ from types import SimpleNamespace
19
+ from typing import Union
20
+ from urllib.parse import unquote
21
+
22
+ import cv2
23
+ import numpy as np
24
+ import torch
25
+ import tqdm
26
+
27
+ from ultralytics import __version__
28
+ from ultralytics.utils.patches import imread, imshow, imwrite, torch_load, torch_save # for patches
29
+
30
+ # PyTorch Multi-GPU DDP Constants
31
+ RANK = int(os.getenv("RANK", -1))
32
+ LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
33
+
34
+ # Other Constants
35
+ ARGV = sys.argv or ["", ""] # sometimes sys.argv = []
36
+ FILE = Path(__file__).resolve()
37
+ ROOT = FILE.parents[1] # YOLO
38
+ ASSETS = ROOT / "assets" # default images
39
+ ASSETS_URL = "https://github.com/ultralytics/assets/releases/download/v0.0.0" # assets GitHub URL
40
+ DEFAULT_CFG_PATH = ROOT / "cfg/default.yaml"
41
+ NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLO multiprocessing threads
42
+ AUTOINSTALL = str(os.getenv("YOLO_AUTOINSTALL", True)).lower() == "true" # global auto-install mode
43
+ VERBOSE = str(os.getenv("YOLO_VERBOSE", True)).lower() == "true" # global verbose mode
44
+ TQDM_BAR_FORMAT = "{l_bar}{bar:10}{r_bar}" if VERBOSE else None # tqdm bar format
45
+ LOGGING_NAME = "ultralytics"
46
+ MACOS, LINUX, WINDOWS = (platform.system() == x for x in ["Darwin", "Linux", "Windows"]) # environment booleans
47
+ MACOS_VERSION = platform.mac_ver()[0] if MACOS else None
48
+ ARM64 = platform.machine() in {"arm64", "aarch64"} # ARM64 booleans
49
+ PYTHON_VERSION = platform.python_version()
50
+ TORCH_VERSION = torch.__version__
51
+ TORCHVISION_VERSION = importlib.metadata.version("torchvision") # faster than importing torchvision
52
+ IS_VSCODE = os.environ.get("TERM_PROGRAM", False) == "vscode"
53
+ RKNN_CHIPS = frozenset(
54
+ {
55
+ "rk3588",
56
+ "rk3576",
57
+ "rk3566",
58
+ "rk3568",
59
+ "rk3562",
60
+ "rv1103",
61
+ "rv1106",
62
+ "rv1103b",
63
+ "rv1106b",
64
+ "rk2118",
65
+ }
66
+ ) # Rockchip processors available for export
67
+ HELP_MSG = """
68
+ Examples for running Ultralytics:
69
+
70
+ 1. Install the ultralytics package:
71
+
72
+ pip install ultralytics
73
+
74
+ 2. Use the Python SDK:
75
+
76
+ from ultralytics import YOLO
77
+
78
+ # Load a model
79
+ model = YOLO("yolo11n.yaml") # build a new model from scratch
80
+ model = YOLO("yolo11n.pt") # load a pretrained model (recommended for training)
81
+
82
+ # Use the model
83
+ results = model.train(data="coco8.yaml", epochs=3) # train the model
84
+ results = model.val() # evaluate model performance on the validation set
85
+ results = model("https://ultralytics.com/images/bus.jpg") # predict on an image
86
+ success = model.export(format="onnx") # export the model to ONNX format
87
+
88
+ 3. Use the command line interface (CLI):
89
+
90
+ Ultralytics 'yolo' CLI commands use the following syntax:
91
+
92
+ yolo TASK MODE ARGS
93
+
94
+ Where TASK (optional) is one of [detect, segment, classify, pose, obb]
95
+ MODE (required) is one of [train, val, predict, export, track, benchmark]
96
+ ARGS (optional) are any number of custom "arg=value" pairs like "imgsz=320" that override defaults.
97
+ See all ARGS at https://docs.ultralytics.com/usage/cfg or with "yolo cfg"
98
+
99
+ - Train a detection model for 10 epochs with an initial learning_rate of 0.01
100
+ yolo detect train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01
101
+
102
+ - Predict a YouTube video using a pretrained segmentation model at image size 320:
103
+ yolo segment predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320
104
+
105
+ - Val a pretrained detection model at batch-size 1 and image size 640:
106
+ yolo detect val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640
107
+
108
+ - Export a YOLO11n classification model to ONNX format at image size 224 by 128 (no TASK required)
109
+ yolo export model=yolo11n-cls.pt format=onnx imgsz=224,128
110
+
111
+ - Run special commands:
112
+ yolo help
113
+ yolo checks
114
+ yolo version
115
+ yolo settings
116
+ yolo copy-cfg
117
+ yolo cfg
118
+
119
+ Docs: https://docs.ultralytics.com
120
+ Community: https://community.ultralytics.com
121
+ GitHub: https://github.com/ultralytics/ultralytics
122
+ """
123
+
124
+ # Settings and Environment Variables
125
+ torch.set_printoptions(linewidth=320, precision=4, profile="default")
126
+ np.set_printoptions(linewidth=320, formatter=dict(float_kind="{:11.5g}".format)) # format short g, %precision=5
127
+ cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
128
+ os.environ["NUMEXPR_MAX_THREADS"] = str(NUM_THREADS) # NumExpr max threads
129
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # suppress verbose TF compiler warnings in Colab
130
+ os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR" # suppress "NNPACK.cpp could not initialize NNPACK" warnings
131
+ os.environ["KINETO_LOG_LEVEL"] = "5" # suppress verbose PyTorch profiler output when computing FLOPs
132
+
133
+ if TQDM_RICH := str(os.getenv("YOLO_TQDM_RICH", False)).lower() == "true":
134
+ from tqdm import rich
135
+
136
+
137
+ class TQDM(rich.tqdm if TQDM_RICH else tqdm.tqdm):
138
+ """
139
+ A custom TQDM progress bar class that extends the original tqdm functionality.
140
+
141
+ This class modifies the behavior of the original tqdm progress bar based on global settings and provides
142
+ additional customization options.
143
+
144
+ Attributes:
145
+ disable (bool): Whether to disable the progress bar. Determined by the global VERBOSE setting and
146
+ any passed 'disable' argument.
147
+ bar_format (str): The format string for the progress bar. Uses the global TQDM_BAR_FORMAT if not
148
+ explicitly set.
149
+
150
+ Methods:
151
+ __init__: Initializes the TQDM object with custom settings.
152
+
153
+ Examples:
154
+ >>> from ultralytics.utils import TQDM
155
+ >>> for i in TQDM(range(100)):
156
+ ... # Your processing code here
157
+ ... pass
158
+ """
159
+
160
+ def __init__(self, *args, **kwargs):
161
+ """
162
+ Initializes a custom TQDM progress bar.
163
+
164
+ This class extends the original tqdm class to provide customized behavior for Ultralytics projects.
165
+
166
+ Args:
167
+ *args (Any): Variable length argument list to be passed to the original tqdm constructor.
168
+ **kwargs (Any): Arbitrary keyword arguments to be passed to the original tqdm constructor.
169
+
170
+ Notes:
171
+ - The progress bar is disabled if VERBOSE is False or if 'disable' is explicitly set to True in kwargs.
172
+ - The default bar format is set to TQDM_BAR_FORMAT unless overridden in kwargs.
173
+
174
+ Examples:
175
+ >>> from ultralytics.utils import TQDM
176
+ >>> for i in TQDM(range(100)):
177
+ ... # Your code here
178
+ ... pass
179
+ """
180
+ warnings.filterwarnings("ignore", category=tqdm.TqdmExperimentalWarning) # suppress tqdm.rich warning
181
+ kwargs["disable"] = not VERBOSE or kwargs.get("disable", False)
182
+ kwargs.setdefault("bar_format", TQDM_BAR_FORMAT) # override default value if passed
183
+ super().__init__(*args, **kwargs)
184
+
185
+ def __iter__(self):
186
+ """Return self as iterator to satisfy Iterable interface."""
187
+ return super().__iter__()
188
+
189
+
190
+ class SimpleClass:
191
+ """
192
+ A simple base class for creating objects with string representations of their attributes.
193
+
194
+ This class provides a foundation for creating objects that can be easily printed or represented as strings,
195
+ showing all their non-callable attributes. It's useful for debugging and introspection of object states.
196
+
197
+ Methods:
198
+ __str__: Returns a human-readable string representation of the object.
199
+ __repr__: Returns a machine-readable string representation of the object.
200
+ __getattr__: Provides a custom attribute access error message with helpful information.
201
+
202
+ Examples:
203
+ >>> class MyClass(SimpleClass):
204
+ ... def __init__(self):
205
+ ... self.x = 10
206
+ ... self.y = "hello"
207
+ >>> obj = MyClass()
208
+ >>> print(obj)
209
+ __main__.MyClass object with attributes:
210
+
211
+ x: 10
212
+ y: 'hello'
213
+
214
+ Notes:
215
+ - This class is designed to be subclassed. It provides a convenient way to inspect object attributes.
216
+ - The string representation includes the module and class name of the object.
217
+ - Callable attributes and attributes starting with an underscore are excluded from the string representation.
218
+ """
219
+
220
+ def __str__(self):
221
+ """Return a human-readable string representation of the object."""
222
+ attr = []
223
+ for a in dir(self):
224
+ v = getattr(self, a)
225
+ if not callable(v) and not a.startswith("_"):
226
+ if isinstance(v, SimpleClass):
227
+ # Display only the module and class name for subclasses
228
+ s = f"{a}: {v.__module__}.{v.__class__.__name__} object"
229
+ else:
230
+ s = f"{a}: {repr(v)}"
231
+ attr.append(s)
232
+ return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr)
233
+
234
+ def __repr__(self):
235
+ """Return a machine-readable string representation of the object."""
236
+ return self.__str__()
237
+
238
+ def __getattr__(self, attr):
239
+ """Custom attribute access error message with helpful information."""
240
+ name = self.__class__.__name__
241
+ raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
242
+
243
+
244
+ class IterableSimpleNamespace(SimpleNamespace):
245
+ """
246
+ An iterable SimpleNamespace class that provides enhanced functionality for attribute access and iteration.
247
+
248
+ This class extends the SimpleNamespace class with additional methods for iteration, string representation,
249
+ and attribute access. It is designed to be used as a convenient container for storing and accessing
250
+ configuration parameters.
251
+
252
+ Methods:
253
+ __iter__: Returns an iterator of key-value pairs from the namespace's attributes.
254
+ __str__: Returns a human-readable string representation of the object.
255
+ __getattr__: Provides a custom attribute access error message with helpful information.
256
+ get: Retrieves the value of a specified key, or a default value if the key doesn't exist.
257
+
258
+ Examples:
259
+ >>> cfg = IterableSimpleNamespace(a=1, b=2, c=3)
260
+ >>> for k, v in cfg:
261
+ ... print(f"{k}: {v}")
262
+ a: 1
263
+ b: 2
264
+ c: 3
265
+ >>> print(cfg)
266
+ a=1
267
+ b=2
268
+ c=3
269
+ >>> cfg.get("b")
270
+ 2
271
+ >>> cfg.get("d", "default")
272
+ 'default'
273
+
274
+ Notes:
275
+ This class is particularly useful for storing configuration parameters in a more accessible
276
+ and iterable format compared to a standard dictionary.
277
+ """
278
+
279
+ def __iter__(self):
280
+ """Return an iterator of key-value pairs from the namespace's attributes."""
281
+ return iter(vars(self).items())
282
+
283
+ def __str__(self):
284
+ """Return a human-readable string representation of the object."""
285
+ return "\n".join(f"{k}={v}" for k, v in vars(self).items())
286
+
287
+ def __getattr__(self, attr):
288
+ """Custom attribute access error message with helpful information."""
289
+ name = self.__class__.__name__
290
+ raise AttributeError(
291
+ f"""
292
+ '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics
293
+ 'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace
294
+ {DEFAULT_CFG_PATH} with the latest version from
295
+ https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
296
+ """
297
+ )
298
+
299
+ def get(self, key, default=None):
300
+ """Return the value of the specified key if it exists; otherwise, return the default value."""
301
+ return getattr(self, key, default)
302
+
303
+
304
+ def plt_settings(rcparams=None, backend="Agg"):
305
+ """
306
+ Decorator to temporarily set rc parameters and the backend for a plotting function.
307
+
308
+ Args:
309
+ rcparams (dict, optional): Dictionary of rc parameters to set.
310
+ backend (str, optional): Name of the backend to use. Defaults to 'Agg'.
311
+
312
+ Returns:
313
+ (Callable): Decorated function with temporarily set rc parameters and backend.
314
+
315
+ Examples:
316
+ >>> @plt_settings({"font.size": 12})
317
+ >>> def plot_function():
318
+ ... plt.figure()
319
+ ... plt.plot([1, 2, 3])
320
+ ... plt.show()
321
+
322
+ >>> with plt_settings({"font.size": 12}):
323
+ ... plt.figure()
324
+ ... plt.plot([1, 2, 3])
325
+ ... plt.show()
326
+ """
327
+ if rcparams is None:
328
+ rcparams = {"font.size": 11}
329
+
330
+ def decorator(func):
331
+ """Decorator to apply temporary rc parameters and backend to a function."""
332
+
333
+ def wrapper(*args, **kwargs):
334
+ """Sets rc parameters and backend, calls the original function, and restores the settings."""
335
+ import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
336
+
337
+ original_backend = plt.get_backend()
338
+ switch = backend.lower() != original_backend.lower()
339
+ if switch:
340
+ plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8
341
+ plt.switch_backend(backend)
342
+
343
+ # Plot with backend and always revert to original backend
344
+ try:
345
+ with plt.rc_context(rcparams):
346
+ result = func(*args, **kwargs)
347
+ finally:
348
+ if switch:
349
+ plt.close("all")
350
+ plt.switch_backend(original_backend)
351
+ return result
352
+
353
+ return wrapper
354
+
355
+ return decorator
356
+
357
+
358
+ def set_logging(name="LOGGING_NAME", verbose=True):
359
+ """
360
+ Sets up logging with UTF-8 encoding and configurable verbosity.
361
+
362
+ This function configures logging for the Ultralytics library, setting the appropriate logging level and
363
+ formatter based on the verbosity flag and the current process rank. It handles special cases for Windows
364
+ environments where UTF-8 encoding might not be the default.
365
+
366
+ Args:
367
+ name (str): Name of the logger. Defaults to "LOGGING_NAME".
368
+ verbose (bool): Flag to set logging level to INFO if True, ERROR otherwise. Defaults to True.
369
+
370
+ Returns:
371
+ (logging.Logger): Configured logger object.
372
+
373
+ Examples:
374
+ >>> set_logging(name="ultralytics", verbose=True)
375
+ >>> logger = logging.getLogger("ultralytics")
376
+ >>> logger.info("This is an info message")
377
+
378
+ Notes:
379
+ - On Windows, this function attempts to reconfigure stdout to use UTF-8 encoding if possible.
380
+ - If reconfiguration is not possible, it falls back to a custom formatter that handles non-UTF-8 environments.
381
+ - The function sets up a StreamHandler with the appropriate formatter and level.
382
+ - The logger's propagate flag is set to False to prevent duplicate logging in parent loggers.
383
+ """
384
+ level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR # rank in world for Multi-GPU trainings
385
+
386
+ class PrefixFormatter(logging.Formatter):
387
+ def format(self, record):
388
+ """Format log records with prefixes based on level."""
389
+ # Apply prefixes based on log level
390
+ if record.levelno == logging.WARNING:
391
+ prefix = "WARNING ⚠️" if not WINDOWS else "WARNING"
392
+ record.msg = f"{prefix} {record.msg}"
393
+ elif record.levelno == logging.ERROR:
394
+ prefix = "ERROR ❌" if not WINDOWS else "ERROR"
395
+ record.msg = f"{prefix} {record.msg}"
396
+
397
+ # Handle emojis in message based on platform
398
+ formatted_message = super().format(record)
399
+ return emojis(formatted_message)
400
+
401
+ formatter = PrefixFormatter("%(message)s")
402
+
403
+ # Handle Windows UTF-8 encoding issues
404
+ if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8":
405
+ try:
406
+ # Attempt to reconfigure stdout to use UTF-8 encoding if possible
407
+ if hasattr(sys.stdout, "reconfigure"):
408
+ sys.stdout.reconfigure(encoding="utf-8")
409
+ # For environments where reconfigure is not available, wrap stdout in a TextIOWrapper
410
+ elif hasattr(sys.stdout, "buffer"):
411
+ import io
412
+
413
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
414
+ except Exception:
415
+ pass
416
+
417
+ # Create and configure the StreamHandler with the appropriate formatter and level
418
+ stream_handler = logging.StreamHandler(sys.stdout)
419
+ stream_handler.setFormatter(formatter)
420
+ stream_handler.setLevel(level)
421
+
422
+ # Set up the logger
423
+ logger = logging.getLogger(name)
424
+ logger.setLevel(level)
425
+ logger.addHandler(stream_handler)
426
+ logger.propagate = False
427
+ return logger
428
+
429
+
430
+ # Set logger
431
+ LOGGER = set_logging(LOGGING_NAME, verbose=VERBOSE) # define globally (used in train.py, val.py, predict.py, etc.)
432
+ for logger in "sentry_sdk", "urllib3.connectionpool":
433
+ logging.getLogger(logger).setLevel(logging.CRITICAL + 1)
434
+
435
+
436
+ def emojis(string=""):
437
+ """Return platform-dependent emoji-safe version of string."""
438
+ return string.encode().decode("ascii", "ignore") if WINDOWS else string
439
+
440
+
441
+ class ThreadingLocked:
442
+ """
443
+ A decorator class for ensuring thread-safe execution of a function or method.
444
+
445
+ This class can be used as a decorator to make sure that if the decorated function is called from multiple threads,
446
+ only one thread at a time will be able to execute the function.
447
+
448
+ Attributes:
449
+ lock (threading.Lock): A lock object used to manage access to the decorated function.
450
+
451
+ Examples:
452
+ >>> from ultralytics.utils import ThreadingLocked
453
+ >>> @ThreadingLocked()
454
+ >>> def my_function():
455
+ ... # Your code here
456
+ """
457
+
458
+ def __init__(self):
459
+ """Initialize the decorator class with a threading lock."""
460
+ self.lock = threading.Lock()
461
+
462
+ def __call__(self, f):
463
+ """Run thread-safe execution of function or method."""
464
+ from functools import wraps
465
+
466
+ @wraps(f)
467
+ def decorated(*args, **kwargs):
468
+ """Applies thread-safety to the decorated function or method."""
469
+ with self.lock:
470
+ return f(*args, **kwargs)
471
+
472
+ return decorated
473
+
474
+
475
+ class YAML:
476
+ """
477
+ YAML utility class for efficient file operations with automatic C-implementation detection.
478
+
479
+ This class provides optimized YAML loading and saving operations using PyYAML's fastest available implementation
480
+ (C-based when possible). It implements a singleton pattern with lazy initialization, allowing direct class method
481
+ usage without explicit instantiation. The class handles file path creation, validation, and character encoding
482
+ issues automatically.
483
+
484
+ The implementation prioritizes performance through:
485
+ - Automatic C-based loader/dumper selection when available
486
+ - Singleton pattern to reuse the same instance
487
+ - Lazy initialization to defer import costs until needed
488
+ - Fallback mechanisms for handling problematic YAML content
489
+
490
+ Attributes:
491
+ _instance: Internal singleton instance storage.
492
+ yaml: Reference to the PyYAML module.
493
+ SafeLoader: Best available YAML loader (CSafeLoader if available).
494
+ SafeDumper: Best available YAML dumper (CSafeDumper if available).
495
+
496
+ Examples:
497
+ >>> data = YAML.load("config.yaml")
498
+ >>> data["new_value"] = 123
499
+ >>> YAML.save("updated_config.yaml", data)
500
+ >>> YAML.print(data)
501
+ """
502
+
503
+ _instance = None
504
+
505
+ @classmethod
506
+ def _get_instance(cls):
507
+ """Initialize singleton instance on first use."""
508
+ if cls._instance is None:
509
+ cls._instance = cls()
510
+ return cls._instance
511
+
512
+ def __init__(self):
513
+ """Initialize with optimal YAML implementation (C-based when available)."""
514
+ import yaml
515
+
516
+ self.yaml = yaml
517
+ # Use C-based implementation if available for better performance
518
+ try:
519
+ self.SafeLoader = yaml.CSafeLoader
520
+ self.SafeDumper = yaml.CSafeDumper
521
+ except (AttributeError, ImportError):
522
+ self.SafeLoader = yaml.SafeLoader
523
+ self.SafeDumper = yaml.SafeDumper
524
+
525
+ @classmethod
526
+ def save(cls, file="data.yaml", data=None, header=""):
527
+ """
528
+ Save Python object as YAML file.
529
+
530
+ Args:
531
+ file (str | Path): Path to save YAML file.
532
+ data (dict | None): Dict or compatible object to save.
533
+ header (str): Optional string to add at file beginning.
534
+ """
535
+ instance = cls._get_instance()
536
+ if data is None:
537
+ data = {}
538
+
539
+ # Create parent directories if needed
540
+ file = Path(file)
541
+ file.parent.mkdir(parents=True, exist_ok=True)
542
+
543
+ # Convert non-serializable objects to strings
544
+ valid_types = int, float, str, bool, list, tuple, dict, type(None)
545
+ for k, v in data.items():
546
+ if not isinstance(v, valid_types):
547
+ data[k] = str(v)
548
+
549
+ # Write YAML file
550
+ with open(file, "w", errors="ignore", encoding="utf-8") as f:
551
+ if header:
552
+ f.write(header)
553
+ instance.yaml.dump(data, f, sort_keys=False, allow_unicode=True, Dumper=instance.SafeDumper)
554
+
555
+ @classmethod
556
+ def load(cls, file="data.yaml", append_filename=False):
557
+ """
558
+ Load YAML file to Python object with robust error handling.
559
+
560
+ Args:
561
+ file (str | Path): Path to YAML file.
562
+ append_filename (bool): Whether to add filename to returned dict.
563
+
564
+ Returns:
565
+ (dict): Loaded YAML content.
566
+ """
567
+ instance = cls._get_instance()
568
+ assert str(file).endswith((".yaml", ".yml")), f"Not a YAML file: {file}"
569
+
570
+ # Read file content
571
+ with open(file, errors="ignore", encoding="utf-8") as f:
572
+ s = f.read()
573
+
574
+ # Try loading YAML with fallback for problematic characters
575
+ try:
576
+ data = instance.yaml.load(s, Loader=instance.SafeLoader) or {}
577
+ except Exception:
578
+ # Remove problematic characters and retry
579
+ s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+", "", s)
580
+ data = instance.yaml.load(s, Loader=instance.SafeLoader) or {}
581
+
582
+ # Check for accidental user-error None strings (should be 'null' in YAML)
583
+ if "None" in data.values():
584
+ data = {k: None if v == "None" else v for k, v in data.items()}
585
+
586
+ if append_filename:
587
+ data["yaml_file"] = str(file)
588
+ return data
589
+
590
+ @classmethod
591
+ def print(cls, yaml_file):
592
+ """
593
+ Pretty print YAML file or object to console.
594
+
595
+ Args:
596
+ yaml_file (str | Path | dict): Path to YAML file or dict to print.
597
+ """
598
+ instance = cls._get_instance()
599
+
600
+ # Load file if path provided
601
+ yaml_dict = cls.load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file
602
+
603
+ # Use -1 for unlimited width in C implementation
604
+ dump = instance.yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True, width=-1, Dumper=instance.SafeDumper)
605
+
606
+ LOGGER.info(f"Printing '{colorstr('bold', 'black', yaml_file)}'\n\n{dump}")
607
+
608
+
609
+ # Default configuration
610
+ DEFAULT_CFG_DICT = YAML.load(DEFAULT_CFG_PATH)
611
+ DEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys()
612
+ DEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT)
613
+
614
+
615
+ def read_device_model() -> str:
616
+ """
617
+ Reads the device model information from the system and caches it for quick access.
618
+
619
+ Returns:
620
+ (str): Kernel release information.
621
+ """
622
+ return platform.release().lower()
623
+
624
+
625
+ def is_ubuntu() -> bool:
626
+ """
627
+ Check if the OS is Ubuntu.
628
+
629
+ Returns:
630
+ (bool): True if OS is Ubuntu, False otherwise.
631
+ """
632
+ try:
633
+ with open("/etc/os-release") as f:
634
+ return "ID=ubuntu" in f.read()
635
+ except FileNotFoundError:
636
+ return False
637
+
638
+
639
+ def is_colab():
640
+ """
641
+ Check if the current script is running inside a Google Colab notebook.
642
+
643
+ Returns:
644
+ (bool): True if running inside a Colab notebook, False otherwise.
645
+ """
646
+ return "COLAB_RELEASE_TAG" in os.environ or "COLAB_BACKEND_VERSION" in os.environ
647
+
648
+
649
+ def is_kaggle():
650
+ """
651
+ Check if the current script is running inside a Kaggle kernel.
652
+
653
+ Returns:
654
+ (bool): True if running inside a Kaggle kernel, False otherwise.
655
+ """
656
+ return os.environ.get("PWD") == "/kaggle/working" and os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com"
657
+
658
+
659
+ def is_jupyter():
660
+ """
661
+ Check if the current script is running inside a Jupyter Notebook.
662
+
663
+ Returns:
664
+ (bool): True if running inside a Jupyter Notebook, False otherwise.
665
+
666
+ Note:
667
+ - Only works on Colab and Kaggle, other environments like Jupyterlab and Paperspace are not reliably detectable.
668
+ - "get_ipython" in globals() method suffers false positives when IPython package installed manually.
669
+ """
670
+ return IS_COLAB or IS_KAGGLE
671
+
672
+
673
+ def is_runpod():
674
+ """
675
+ Check if the current script is running inside a RunPod container.
676
+
677
+ Returns:
678
+ (bool): True if running in RunPod, False otherwise.
679
+ """
680
+ return "RUNPOD_POD_ID" in os.environ
681
+
682
+
683
+ def is_docker() -> bool:
684
+ """
685
+ Determine if the script is running inside a Docker container.
686
+
687
+ Returns:
688
+ (bool): True if the script is running inside a Docker container, False otherwise.
689
+ """
690
+ try:
691
+ with open("/proc/self/cgroup") as f:
692
+ return "docker" in f.read()
693
+ except Exception:
694
+ return False
695
+
696
+
697
+ def is_raspberrypi() -> bool:
698
+ """
699
+ Determines if the Python environment is running on a Raspberry Pi.
700
+
701
+ Returns:
702
+ (bool): True if running on a Raspberry Pi, False otherwise.
703
+ """
704
+ return "rpi" in DEVICE_MODEL
705
+
706
+
707
+ def is_jetson() -> bool:
708
+ """
709
+ Determines if the Python environment is running on an NVIDIA Jetson device.
710
+
711
+ Returns:
712
+ (bool): True if running on an NVIDIA Jetson device, False otherwise.
713
+ """
714
+ return "tegra" in DEVICE_MODEL
715
+
716
+
717
+ def is_online() -> bool:
718
+ """
719
+ Check internet connectivity by attempting to connect to a known online host.
720
+
721
+ Returns:
722
+ (bool): True if connection is successful, False otherwise.
723
+ """
724
+ try:
725
+ assert str(os.getenv("YOLO_OFFLINE", "")).lower() != "true" # check if ENV var YOLO_OFFLINE="True"
726
+ import socket
727
+
728
+ for dns in ("1.1.1.1", "8.8.8.8"): # check Cloudflare and Google DNS
729
+ socket.create_connection(address=(dns, 80), timeout=2.0).close()
730
+ return True
731
+ except Exception:
732
+ return False
733
+
734
+
735
+ def is_pip_package(filepath: str = __name__) -> bool:
736
+ """
737
+ Determines if the file at the given filepath is part of a pip package.
738
+
739
+ Args:
740
+ filepath (str): The filepath to check.
741
+
742
+ Returns:
743
+ (bool): True if the file is part of a pip package, False otherwise.
744
+ """
745
+ import importlib.util
746
+
747
+ # Get the spec for the module
748
+ spec = importlib.util.find_spec(filepath)
749
+
750
+ # Return whether the spec is not None and the origin is not None (indicating it is a package)
751
+ return spec is not None and spec.origin is not None
752
+
753
+
754
+ def is_dir_writeable(dir_path: Union[str, Path]) -> bool:
755
+ """
756
+ Check if a directory is writeable.
757
+
758
+ Args:
759
+ dir_path (str | Path): The path to the directory.
760
+
761
+ Returns:
762
+ (bool): True if the directory is writeable, False otherwise.
763
+ """
764
+ return os.access(str(dir_path), os.W_OK)
765
+
766
+
767
+ def is_pytest_running():
768
+ """
769
+ Determines whether pytest is currently running or not.
770
+
771
+ Returns:
772
+ (bool): True if pytest is running, False otherwise.
773
+ """
774
+ return ("PYTEST_CURRENT_TEST" in os.environ) or ("pytest" in sys.modules) or ("pytest" in Path(ARGV[0]).stem)
775
+
776
+
777
+ def is_github_action_running() -> bool:
778
+ """
779
+ Determine if the current environment is a GitHub Actions runner.
780
+
781
+ Returns:
782
+ (bool): True if the current environment is a GitHub Actions runner, False otherwise.
783
+ """
784
+ return "GITHUB_ACTIONS" in os.environ and "GITHUB_WORKFLOW" in os.environ and "RUNNER_OS" in os.environ
785
+
786
+
787
+ def get_git_dir():
788
+ """
789
+ Determines whether the current file is part of a git repository and if so, returns the repository root directory.
790
+
791
+ Returns:
792
+ (Path | None): Git root directory if found or None if not found.
793
+ """
794
+ for d in Path(__file__).parents:
795
+ if (d / ".git").is_dir():
796
+ return d
797
+
798
+
799
+ def is_git_dir():
800
+ """
801
+ Determines whether the current file is part of a git repository.
802
+
803
+ Returns:
804
+ (bool): True if current file is part of a git repository.
805
+ """
806
+ return GIT_DIR is not None
807
+
808
+
809
+ def get_git_origin_url():
810
+ """
811
+ Retrieves the origin URL of a git repository.
812
+
813
+ Returns:
814
+ (str | None): The origin URL of the git repository or None if not git directory.
815
+ """
816
+ if IS_GIT_DIR:
817
+ try:
818
+ origin = subprocess.check_output(["git", "config", "--get", "remote.origin.url"])
819
+ return origin.decode().strip()
820
+ except subprocess.CalledProcessError:
821
+ return None
822
+
823
+
824
+ def get_git_branch():
825
+ """
826
+ Returns the current git branch name. If not in a git repository, returns None.
827
+
828
+ Returns:
829
+ (str | None): The current git branch name or None if not a git directory.
830
+ """
831
+ if IS_GIT_DIR:
832
+ try:
833
+ origin = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"])
834
+ return origin.decode().strip()
835
+ except subprocess.CalledProcessError:
836
+ return None
837
+
838
+
839
+ def get_default_args(func):
840
+ """
841
+ Returns a dictionary of default arguments for a function.
842
+
843
+ Args:
844
+ func (callable): The function to inspect.
845
+
846
+ Returns:
847
+ (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.
848
+ """
849
+ signature = inspect.signature(func)
850
+ return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}
851
+
852
+
853
+ def get_ubuntu_version():
854
+ """
855
+ Retrieve the Ubuntu version if the OS is Ubuntu.
856
+
857
+ Returns:
858
+ (str): Ubuntu version or None if not an Ubuntu OS.
859
+ """
860
+ if is_ubuntu():
861
+ try:
862
+ with open("/etc/os-release") as f:
863
+ return re.search(r'VERSION_ID="(\d+\.\d+)"', f.read())[1]
864
+ except (FileNotFoundError, AttributeError):
865
+ return None
866
+
867
+
868
+ def get_user_config_dir(sub_dir="Ultralytics"):
869
+ """
870
+ Return the appropriate config directory based on the environment operating system.
871
+
872
+ Args:
873
+ sub_dir (str): The name of the subdirectory to create.
874
+
875
+ Returns:
876
+ (Path): The path to the user config directory.
877
+ """
878
+ if WINDOWS:
879
+ path = Path.home() / "AppData" / "Roaming" / sub_dir
880
+ elif MACOS: # macOS
881
+ path = Path.home() / "Library" / "Application Support" / sub_dir
882
+ elif LINUX:
883
+ path = Path.home() / ".config" / sub_dir
884
+ else:
885
+ raise ValueError(f"Unsupported operating system: {platform.system()}")
886
+
887
+ # GCP and AWS lambda fix, only /tmp is writeable
888
+ if not is_dir_writeable(path.parent):
889
+ LOGGER.warning(
890
+ f"user config directory '{path}' is not writeable, defaulting to '/tmp' or CWD."
891
+ "Alternatively you can define a YOLO_CONFIG_DIR environment variable for this path."
892
+ )
893
+ path = Path("/tmp") / sub_dir if is_dir_writeable("/tmp") else Path().cwd() / sub_dir
894
+
895
+ # Create the subdirectory if it does not exist
896
+ path.mkdir(parents=True, exist_ok=True)
897
+
898
+ return path
899
+
900
+
901
+ # Define constants (required below)
902
+ DEVICE_MODEL = read_device_model() # is_jetson() and is_raspberrypi() depend on this constant
903
+ ONLINE = is_online()
904
+ IS_COLAB = is_colab()
905
+ IS_KAGGLE = is_kaggle()
906
+ IS_DOCKER = is_docker()
907
+ IS_JETSON = is_jetson()
908
+ IS_JUPYTER = is_jupyter()
909
+ IS_PIP_PACKAGE = is_pip_package()
910
+ IS_RASPBERRYPI = is_raspberrypi()
911
+ GIT_DIR = get_git_dir()
912
+ IS_GIT_DIR = is_git_dir()
913
+ USER_CONFIG_DIR = Path(os.getenv("YOLO_CONFIG_DIR") or get_user_config_dir()) # Ultralytics settings dir
914
+ SETTINGS_FILE = USER_CONFIG_DIR / "settings.json"
915
+
916
+
917
+ def colorstr(*input):
918
+ r"""
919
+ Colors a string based on the provided color and style arguments. Utilizes ANSI escape codes.
920
+ See https://en.wikipedia.org/wiki/ANSI_escape_code for more details.
921
+
922
+ This function can be called in two ways:
923
+ - colorstr('color', 'style', 'your string')
924
+ - colorstr('your string')
925
+
926
+ In the second form, 'blue' and 'bold' will be applied by default.
927
+
928
+ Args:
929
+ *input (str | Path): A sequence of strings where the first n-1 strings are color and style arguments,
930
+ and the last string is the one to be colored.
931
+
932
+ Supported Colors and Styles:
933
+ Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
934
+ Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow',
935
+ 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white'
936
+ Misc: 'end', 'bold', 'underline'
937
+
938
+ Returns:
939
+ (str): The input string wrapped with ANSI escape codes for the specified color and style.
940
+
941
+ Examples:
942
+ >>> colorstr("blue", "bold", "hello world")
943
+ >>> "\033[34m\033[1mhello world\033[0m"
944
+ """
945
+ *args, string = input if len(input) > 1 else ("blue", "bold", input[0]) # color arguments, string
946
+ colors = {
947
+ "black": "\033[30m", # basic colors
948
+ "red": "\033[31m",
949
+ "green": "\033[32m",
950
+ "yellow": "\033[33m",
951
+ "blue": "\033[34m",
952
+ "magenta": "\033[35m",
953
+ "cyan": "\033[36m",
954
+ "white": "\033[37m",
955
+ "bright_black": "\033[90m", # bright colors
956
+ "bright_red": "\033[91m",
957
+ "bright_green": "\033[92m",
958
+ "bright_yellow": "\033[93m",
959
+ "bright_blue": "\033[94m",
960
+ "bright_magenta": "\033[95m",
961
+ "bright_cyan": "\033[96m",
962
+ "bright_white": "\033[97m",
963
+ "end": "\033[0m", # misc
964
+ "bold": "\033[1m",
965
+ "underline": "\033[4m",
966
+ }
967
+ return "".join(colors[x] for x in args) + f"{string}" + colors["end"]
968
+
969
+
970
+ def remove_colorstr(input_string):
971
+ """
972
+ Removes ANSI escape codes from a string, effectively un-coloring it.
973
+
974
+ Args:
975
+ input_string (str): The string to remove color and style from.
976
+
977
+ Returns:
978
+ (str): A new string with all ANSI escape codes removed.
979
+
980
+ Examples:
981
+ >>> remove_colorstr(colorstr("blue", "bold", "hello world"))
982
+ >>> "hello world"
983
+ """
984
+ ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
985
+ return ansi_escape.sub("", input_string)
986
+
987
+
988
+ class TryExcept(contextlib.ContextDecorator):
989
+ """
990
+ Ultralytics TryExcept class. Use as @TryExcept() decorator or 'with TryExcept():' context manager.
991
+
992
+ Examples:
993
+ As a decorator:
994
+ >>> @TryExcept(msg="Error occurred in func", verbose=True)
995
+ >>> def func():
996
+ >>> # Function logic here
997
+ >>> pass
998
+
999
+ As a context manager:
1000
+ >>> with TryExcept(msg="Error occurred in block", verbose=True):
1001
+ >>> # Code block here
1002
+ >>> pass
1003
+ """
1004
+
1005
+ def __init__(self, msg="", verbose=True):
1006
+ """Initialize TryExcept class with optional message and verbosity settings."""
1007
+ self.msg = msg
1008
+ self.verbose = verbose
1009
+
1010
+ def __enter__(self):
1011
+ """Executes when entering TryExcept context, initializes instance."""
1012
+ pass
1013
+
1014
+ def __exit__(self, exc_type, value, traceback):
1015
+ """Defines behavior when exiting a 'with' block, prints error message if necessary."""
1016
+ if self.verbose and value:
1017
+ LOGGER.warning(f"{self.msg}{': ' if self.msg else ''}{value}")
1018
+ return True
1019
+
1020
+
1021
+ class Retry(contextlib.ContextDecorator):
1022
+ """
1023
+ Retry class for function execution with exponential backoff.
1024
+
1025
+ Can be used as a decorator to retry a function on exceptions, up to a specified number of times with an
1026
+ exponentially increasing delay between retries.
1027
+
1028
+ Examples:
1029
+ Example usage as a decorator:
1030
+ >>> @Retry(times=3, delay=2)
1031
+ >>> def test_func():
1032
+ >>> # Replace with function logic that may raise exceptions
1033
+ >>> return True
1034
+ """
1035
+
1036
+ def __init__(self, times=3, delay=2):
1037
+ """Initialize Retry class with specified number of retries and delay."""
1038
+ self.times = times
1039
+ self.delay = delay
1040
+ self._attempts = 0
1041
+
1042
+ def __call__(self, func):
1043
+ """Decorator implementation for Retry with exponential backoff."""
1044
+
1045
+ def wrapped_func(*args, **kwargs):
1046
+ """Applies retries to the decorated function or method."""
1047
+ self._attempts = 0
1048
+ while self._attempts < self.times:
1049
+ try:
1050
+ return func(*args, **kwargs)
1051
+ except Exception as e:
1052
+ self._attempts += 1
1053
+ LOGGER.warning(f"Retry {self._attempts}/{self.times} failed: {e}")
1054
+ if self._attempts >= self.times:
1055
+ raise e
1056
+ time.sleep(self.delay * (2**self._attempts)) # exponential backoff delay
1057
+
1058
+ return wrapped_func
1059
+
1060
+
1061
+ def threaded(func):
1062
+ """
1063
+ Multi-threads a target function by default and returns the thread or function result.
1064
+
1065
+ This decorator provides flexible execution of the target function, either in a separate thread or synchronously.
1066
+ By default, the function runs in a thread, but this can be controlled via the 'threaded=False' keyword argument
1067
+ which is removed from kwargs before calling the function.
1068
+
1069
+ Args:
1070
+ func (callable): The function to be potentially executed in a separate thread.
1071
+
1072
+ Returns:
1073
+ (callable): A wrapper function that either returns a daemon thread or the direct function result.
1074
+
1075
+ Examples:
1076
+ >>> @threaded
1077
+ ... def process_data(data):
1078
+ ... return data
1079
+ >>>
1080
+ >>> thread = process_data(my_data) # Runs in background thread
1081
+ >>> result = process_data(my_data, threaded=False) # Runs synchronously, returns function result
1082
+ """
1083
+
1084
+ def wrapper(*args, **kwargs):
1085
+ """Multi-threads a given function based on 'threaded' kwarg and returns the thread or function result."""
1086
+ if kwargs.pop("threaded", True): # run in thread
1087
+ thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
1088
+ thread.start()
1089
+ return thread
1090
+ else:
1091
+ return func(*args, **kwargs)
1092
+
1093
+ return wrapper
1094
+
1095
+
1096
+ def set_sentry():
1097
+ """
1098
+ Initialize the Sentry SDK for error tracking and reporting.
1099
+
1100
+ Only used if sentry_sdk package is installed and sync=True in settings. Run 'yolo settings' to see and update
1101
+ settings.
1102
+
1103
+ Conditions required to send errors (ALL conditions must be met or no errors will be reported):
1104
+ - sentry_sdk package is installed
1105
+ - sync=True in YOLO settings
1106
+ - pytest is not running
1107
+ - running in a pip package installation
1108
+ - running in a non-git directory
1109
+ - running with rank -1 or 0
1110
+ - online environment
1111
+ - CLI used to run package (checked with 'yolo' as the name of the main CLI command)
1112
+ """
1113
+ if (
1114
+ not SETTINGS["sync"]
1115
+ or RANK not in {-1, 0}
1116
+ or Path(ARGV[0]).name != "yolo"
1117
+ or TESTS_RUNNING
1118
+ or not ONLINE
1119
+ or not IS_PIP_PACKAGE
1120
+ or IS_GIT_DIR
1121
+ ):
1122
+ return
1123
+ # If sentry_sdk package is not installed then return and do not use Sentry
1124
+ try:
1125
+ import sentry_sdk # noqa
1126
+ except ImportError:
1127
+ return
1128
+
1129
+ def before_send(event, hint):
1130
+ """
1131
+ Modify the event before sending it to Sentry based on specific exception types and messages.
1132
+
1133
+ Args:
1134
+ event (dict): The event dictionary containing information about the error.
1135
+ hint (dict): A dictionary containing additional information about the error.
1136
+
1137
+ Returns:
1138
+ dict: The modified event or None if the event should not be sent to Sentry.
1139
+ """
1140
+ if "exc_info" in hint:
1141
+ exc_type, exc_value, _ = hint["exc_info"]
1142
+ if exc_type in {KeyboardInterrupt, FileNotFoundError} or "out of memory" in str(exc_value):
1143
+ return None # do not send event
1144
+
1145
+ event["tags"] = {
1146
+ "sys_argv": ARGV[0],
1147
+ "sys_argv_name": Path(ARGV[0]).name,
1148
+ "install": "git" if IS_GIT_DIR else "pip" if IS_PIP_PACKAGE else "other",
1149
+ "os": ENVIRONMENT,
1150
+ }
1151
+ return event
1152
+
1153
+ sentry_sdk.init(
1154
+ dsn="https://888e5a0778212e1d0314c37d4b9aae5d@o4504521589325824.ingest.us.sentry.io/4504521592406016",
1155
+ debug=False,
1156
+ auto_enabling_integrations=False,
1157
+ traces_sample_rate=1.0,
1158
+ release=__version__,
1159
+ environment="runpod" if is_runpod() else "production",
1160
+ before_send=before_send,
1161
+ ignore_errors=[KeyboardInterrupt, FileNotFoundError],
1162
+ )
1163
+ sentry_sdk.set_user({"id": SETTINGS["uuid"]}) # SHA-256 anonymized UUID hash
1164
+
1165
+
1166
+ class JSONDict(dict):
1167
+ """
1168
+ A dictionary-like class that provides JSON persistence for its contents.
1169
+
1170
+ This class extends the built-in dictionary to automatically save its contents to a JSON file whenever they are
1171
+ modified. It ensures thread-safe operations using a lock.
1172
+
1173
+ Attributes:
1174
+ file_path (Path): The path to the JSON file used for persistence.
1175
+ lock (threading.Lock): A lock object to ensure thread-safe operations.
1176
+
1177
+ Methods:
1178
+ _load: Loads the data from the JSON file into the dictionary.
1179
+ _save: Saves the current state of the dictionary to the JSON file.
1180
+ __setitem__: Stores a key-value pair and persists it to disk.
1181
+ __delitem__: Removes an item and updates the persistent storage.
1182
+ update: Updates the dictionary and persists changes.
1183
+ clear: Clears all entries and updates the persistent storage.
1184
+
1185
+ Examples:
1186
+ >>> json_dict = JSONDict("data.json")
1187
+ >>> json_dict["key"] = "value"
1188
+ >>> print(json_dict["key"])
1189
+ value
1190
+ >>> del json_dict["key"]
1191
+ >>> json_dict.update({"new_key": "new_value"})
1192
+ >>> json_dict.clear()
1193
+ """
1194
+
1195
+ def __init__(self, file_path: Union[str, Path] = "data.json"):
1196
+ """Initialize a JSONDict object with a specified file path for JSON persistence."""
1197
+ super().__init__()
1198
+ self.file_path = Path(file_path)
1199
+ self.lock = Lock()
1200
+ self._load()
1201
+
1202
+ def _load(self):
1203
+ """Load the data from the JSON file into the dictionary."""
1204
+ try:
1205
+ if self.file_path.exists():
1206
+ with open(self.file_path) as f:
1207
+ self.update(json.load(f))
1208
+ except json.JSONDecodeError:
1209
+ LOGGER.warning(f"Error decoding JSON from {self.file_path}. Starting with an empty dictionary.")
1210
+ except Exception as e:
1211
+ LOGGER.error(f"Error reading from {self.file_path}: {e}")
1212
+
1213
+ def _save(self):
1214
+ """Save the current state of the dictionary to the JSON file."""
1215
+ try:
1216
+ self.file_path.parent.mkdir(parents=True, exist_ok=True)
1217
+ with open(self.file_path, "w", encoding="utf-8") as f:
1218
+ json.dump(dict(self), f, indent=2, default=self._json_default)
1219
+ except Exception as e:
1220
+ LOGGER.error(f"Error writing to {self.file_path}: {e}")
1221
+
1222
+ @staticmethod
1223
+ def _json_default(obj):
1224
+ """Handle JSON serialization of Path objects."""
1225
+ if isinstance(obj, Path):
1226
+ return str(obj)
1227
+ raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
1228
+
1229
+ def __setitem__(self, key, value):
1230
+ """Store a key-value pair and persist to disk."""
1231
+ with self.lock:
1232
+ super().__setitem__(key, value)
1233
+ self._save()
1234
+
1235
+ def __delitem__(self, key):
1236
+ """Remove an item and update the persistent storage."""
1237
+ with self.lock:
1238
+ super().__delitem__(key)
1239
+ self._save()
1240
+
1241
+ def __str__(self):
1242
+ """Return a pretty-printed JSON string representation of the dictionary."""
1243
+ contents = json.dumps(dict(self), indent=2, ensure_ascii=False, default=self._json_default)
1244
+ return f'JSONDict("{self.file_path}"):\n{contents}'
1245
+
1246
+ def update(self, *args, **kwargs):
1247
+ """Update the dictionary and persist changes."""
1248
+ with self.lock:
1249
+ super().update(*args, **kwargs)
1250
+ self._save()
1251
+
1252
+ def clear(self):
1253
+ """Clear all entries and update the persistent storage."""
1254
+ with self.lock:
1255
+ super().clear()
1256
+ self._save()
1257
+
1258
+
1259
+ class SettingsManager(JSONDict):
1260
+ """
1261
+ SettingsManager class for managing and persisting Ultralytics settings.
1262
+
1263
+ This class extends JSONDict to provide JSON persistence for settings, ensuring thread-safe operations and default
1264
+ values. It validates settings on initialization and provides methods to update or reset settings.
1265
+
1266
+ Attributes:
1267
+ file (Path): The path to the JSON file used for persistence.
1268
+ version (str): The version of the settings schema.
1269
+ defaults (dict): A dictionary containing default settings.
1270
+ help_msg (str): A help message for users on how to view and update settings.
1271
+
1272
+ Methods:
1273
+ _validate_settings: Validates the current settings and resets if necessary.
1274
+ update: Updates settings, validating keys and types.
1275
+ reset: Resets the settings to default and saves them.
1276
+
1277
+ Examples:
1278
+ Initialize and update settings:
1279
+ >>> settings = SettingsManager()
1280
+ >>> settings.update(runs_dir="/new/runs/dir")
1281
+ >>> print(settings["runs_dir"])
1282
+ /new/runs/dir
1283
+ """
1284
+
1285
+ def __init__(self, file=SETTINGS_FILE, version="0.0.6"):
1286
+ """Initializes the SettingsManager with default settings and loads user settings."""
1287
+ import hashlib
1288
+ import uuid
1289
+
1290
+ from ultralytics.utils.torch_utils import torch_distributed_zero_first
1291
+
1292
+ root = GIT_DIR or Path()
1293
+ datasets_root = (root.parent if GIT_DIR and is_dir_writeable(root.parent) else root).resolve()
1294
+
1295
+ self.file = Path(file)
1296
+ self.version = version
1297
+ self.defaults = {
1298
+ "settings_version": version, # Settings schema version
1299
+ "datasets_dir": str(datasets_root / "datasets"), # Datasets directory
1300
+ "weights_dir": str(root / "weights"), # Model weights directory
1301
+ "runs_dir": str(root / "runs"), # Experiment runs directory
1302
+ "uuid": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(), # SHA-256 anonymized UUID hash
1303
+ "sync": True, # Enable synchronization
1304
+ "api_key": "", # Ultralytics API Key
1305
+ "openai_api_key": "", # OpenAI API Key
1306
+ "clearml": True, # ClearML integration
1307
+ "comet": True, # Comet integration
1308
+ "dvc": True, # DVC integration
1309
+ "hub": True, # Ultralytics HUB integration
1310
+ "mlflow": True, # MLflow integration
1311
+ "neptune": True, # Neptune integration
1312
+ "raytune": True, # Ray Tune integration
1313
+ "tensorboard": False, # TensorBoard logging
1314
+ "wandb": False, # Weights & Biases logging
1315
+ "vscode_msg": True, # VSCode message
1316
+ "openvino_msg": True, # OpenVINO export on Intel CPU message
1317
+ }
1318
+
1319
+ self.help_msg = (
1320
+ f"\nView Ultralytics Settings with 'yolo settings' or at '{self.file}'"
1321
+ "\nUpdate Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. "
1322
+ "For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings."
1323
+ )
1324
+
1325
+ with torch_distributed_zero_first(LOCAL_RANK):
1326
+ super().__init__(self.file)
1327
+
1328
+ if not self.file.exists() or not self: # Check if file doesn't exist or is empty
1329
+ LOGGER.info(f"Creating new Ultralytics Settings v{version} file ✅ {self.help_msg}")
1330
+ self.reset()
1331
+
1332
+ self._validate_settings()
1333
+
1334
+ def _validate_settings(self):
1335
+ """Validate the current settings and reset if necessary."""
1336
+ correct_keys = frozenset(self.keys()) == frozenset(self.defaults.keys())
1337
+ correct_types = all(isinstance(self.get(k), type(v)) for k, v in self.defaults.items())
1338
+ correct_version = self.get("settings_version", "") == self.version
1339
+
1340
+ if not (correct_keys and correct_types and correct_version):
1341
+ LOGGER.warning(
1342
+ "Ultralytics settings reset to default values. This may be due to a possible problem "
1343
+ f"with your settings or a recent ultralytics package update. {self.help_msg}"
1344
+ )
1345
+ self.reset()
1346
+
1347
+ if self.get("datasets_dir") == self.get("runs_dir"):
1348
+ LOGGER.warning(
1349
+ f"Ultralytics setting 'datasets_dir: {self.get('datasets_dir')}' "
1350
+ f"must be different than 'runs_dir: {self.get('runs_dir')}'. "
1351
+ f"Please change one to avoid possible issues during training. {self.help_msg}"
1352
+ )
1353
+
1354
+ def __setitem__(self, key, value):
1355
+ """Updates one key: value pair."""
1356
+ self.update({key: value})
1357
+
1358
+ def update(self, *args, **kwargs):
1359
+ """Updates settings, validating keys and types."""
1360
+ for arg in args:
1361
+ if isinstance(arg, dict):
1362
+ kwargs.update(arg)
1363
+ for k, v in kwargs.items():
1364
+ if k not in self.defaults:
1365
+ raise KeyError(f"No Ultralytics setting '{k}'. {self.help_msg}")
1366
+ t = type(self.defaults[k])
1367
+ if not isinstance(v, t):
1368
+ raise TypeError(
1369
+ f"Ultralytics setting '{k}' must be '{t.__name__}' type, not '{type(v).__name__}'. {self.help_msg}"
1370
+ )
1371
+ super().update(*args, **kwargs)
1372
+
1373
+ def reset(self):
1374
+ """Resets the settings to default and saves them."""
1375
+ self.clear()
1376
+ self.update(self.defaults)
1377
+
1378
+
1379
+ def deprecation_warn(arg, new_arg=None):
1380
+ """Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument."""
1381
+ msg = f"'{arg}' is deprecated and will be removed in in the future."
1382
+ if new_arg is not None:
1383
+ msg += f" Use '{new_arg}' instead."
1384
+ LOGGER.warning(msg)
1385
+
1386
+
1387
+ def clean_url(url):
1388
+ """Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt."""
1389
+ url = Path(url).as_posix().replace(":/", "://") # Pathlib turns :// -> :/, as_posix() for Windows
1390
+ return unquote(url).split("?")[0] # '%2F' to '/', split https://url.com/file.txt?auth
1391
+
1392
+
1393
+ def url2file(url):
1394
+ """Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt."""
1395
+ return Path(clean_url(url)).name
1396
+
1397
+
1398
+ def vscode_msg(ext="ultralytics.ultralytics-snippets") -> str:
1399
+ """Display a message to install Ultralytics-Snippets for VS Code if not already installed."""
1400
+ path = (USER_CONFIG_DIR.parents[2] if WINDOWS else USER_CONFIG_DIR.parents[1]) / ".vscode/extensions"
1401
+ obs_file = path / ".obsolete" # file tracks uninstalled extensions, while source directory remains
1402
+ installed = any(path.glob(f"{ext}*")) and ext not in (obs_file.read_text("utf-8") if obs_file.exists() else "")
1403
+ url = "https://docs.ultralytics.com/integrations/vscode"
1404
+ return "" if installed else f"{colorstr('VS Code:')} view Ultralytics VS Code Extension ⚡ at {url}"
1405
+
1406
+
1407
+ # Run below code on utils init ------------------------------------------------------------------------------------
1408
+
1409
+ # Check first-install steps
1410
+ PREFIX = colorstr("Ultralytics: ")
1411
+ SETTINGS = SettingsManager() # initialize settings
1412
+ PERSISTENT_CACHE = JSONDict(USER_CONFIG_DIR / "persistent_cache.json") # initialize persistent cache
1413
+ DATASETS_DIR = Path(SETTINGS["datasets_dir"]) # global datasets directory
1414
+ WEIGHTS_DIR = Path(SETTINGS["weights_dir"]) # global weights directory
1415
+ RUNS_DIR = Path(SETTINGS["runs_dir"]) # global runs directory
1416
+ ENVIRONMENT = (
1417
+ "Colab"
1418
+ if IS_COLAB
1419
+ else "Kaggle"
1420
+ if IS_KAGGLE
1421
+ else "Jupyter"
1422
+ if IS_JUPYTER
1423
+ else "Docker"
1424
+ if IS_DOCKER
1425
+ else platform.system()
1426
+ )
1427
+ TESTS_RUNNING = is_pytest_running() or is_github_action_running()
1428
+ set_sentry()
1429
+
1430
+ # Apply monkey patches
1431
+ torch.load = torch_load
1432
+ torch.save = torch_save
1433
+ if WINDOWS:
1434
+ # Apply cv2 patches for non-ASCII and non-UTF characters in image paths
1435
+ cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow