ultralytics-opencv-headless 8.3.246__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 (298) hide show
  1. tests/__init__.py +23 -0
  2. tests/conftest.py +59 -0
  3. tests/test_cli.py +131 -0
  4. tests/test_cuda.py +216 -0
  5. tests/test_engine.py +157 -0
  6. tests/test_exports.py +309 -0
  7. tests/test_integrations.py +151 -0
  8. tests/test_python.py +777 -0
  9. tests/test_solutions.py +371 -0
  10. ultralytics/__init__.py +48 -0
  11. ultralytics/assets/bus.jpg +0 -0
  12. ultralytics/assets/zidane.jpg +0 -0
  13. ultralytics/cfg/__init__.py +1026 -0
  14. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  15. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  16. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  17. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  18. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  19. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  20. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  21. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  22. ultralytics/cfg/datasets/VOC.yaml +102 -0
  23. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  24. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  25. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  26. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  27. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  28. ultralytics/cfg/datasets/coco.yaml +118 -0
  29. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  30. ultralytics/cfg/datasets/coco128.yaml +101 -0
  31. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  32. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  33. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  34. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  35. ultralytics/cfg/datasets/coco8.yaml +101 -0
  36. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  37. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  38. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  39. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  40. ultralytics/cfg/datasets/dota8.yaml +35 -0
  41. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  42. ultralytics/cfg/datasets/kitti.yaml +27 -0
  43. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  44. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  45. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  46. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  47. ultralytics/cfg/datasets/signature.yaml +21 -0
  48. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  49. ultralytics/cfg/datasets/xView.yaml +155 -0
  50. ultralytics/cfg/default.yaml +130 -0
  51. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  52. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  53. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  54. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  55. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  56. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  57. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  58. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  59. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  60. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  61. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  62. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  63. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  64. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  65. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  66. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  68. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  69. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  70. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  71. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  74. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  75. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  76. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  77. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  78. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  79. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  80. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  81. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  82. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  83. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  84. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  85. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  86. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  87. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  88. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  89. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  90. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  91. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  92. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  93. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  94. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  95. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  97. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  98. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  99. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  100. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  101. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  102. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  103. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  105. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  106. ultralytics/cfg/trackers/botsort.yaml +21 -0
  107. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  108. ultralytics/data/__init__.py +26 -0
  109. ultralytics/data/annotator.py +66 -0
  110. ultralytics/data/augment.py +2801 -0
  111. ultralytics/data/base.py +435 -0
  112. ultralytics/data/build.py +437 -0
  113. ultralytics/data/converter.py +855 -0
  114. ultralytics/data/dataset.py +834 -0
  115. ultralytics/data/loaders.py +704 -0
  116. ultralytics/data/scripts/download_weights.sh +18 -0
  117. ultralytics/data/scripts/get_coco.sh +61 -0
  118. ultralytics/data/scripts/get_coco128.sh +18 -0
  119. ultralytics/data/scripts/get_imagenet.sh +52 -0
  120. ultralytics/data/split.py +138 -0
  121. ultralytics/data/split_dota.py +344 -0
  122. ultralytics/data/utils.py +798 -0
  123. ultralytics/engine/__init__.py +1 -0
  124. ultralytics/engine/exporter.py +1578 -0
  125. ultralytics/engine/model.py +1124 -0
  126. ultralytics/engine/predictor.py +508 -0
  127. ultralytics/engine/results.py +1522 -0
  128. ultralytics/engine/trainer.py +974 -0
  129. ultralytics/engine/tuner.py +448 -0
  130. ultralytics/engine/validator.py +384 -0
  131. ultralytics/hub/__init__.py +166 -0
  132. ultralytics/hub/auth.py +151 -0
  133. ultralytics/hub/google/__init__.py +174 -0
  134. ultralytics/hub/session.py +422 -0
  135. ultralytics/hub/utils.py +162 -0
  136. ultralytics/models/__init__.py +9 -0
  137. ultralytics/models/fastsam/__init__.py +7 -0
  138. ultralytics/models/fastsam/model.py +79 -0
  139. ultralytics/models/fastsam/predict.py +169 -0
  140. ultralytics/models/fastsam/utils.py +23 -0
  141. ultralytics/models/fastsam/val.py +38 -0
  142. ultralytics/models/nas/__init__.py +7 -0
  143. ultralytics/models/nas/model.py +98 -0
  144. ultralytics/models/nas/predict.py +56 -0
  145. ultralytics/models/nas/val.py +38 -0
  146. ultralytics/models/rtdetr/__init__.py +7 -0
  147. ultralytics/models/rtdetr/model.py +63 -0
  148. ultralytics/models/rtdetr/predict.py +88 -0
  149. ultralytics/models/rtdetr/train.py +89 -0
  150. ultralytics/models/rtdetr/val.py +216 -0
  151. ultralytics/models/sam/__init__.py +25 -0
  152. ultralytics/models/sam/amg.py +275 -0
  153. ultralytics/models/sam/build.py +365 -0
  154. ultralytics/models/sam/build_sam3.py +377 -0
  155. ultralytics/models/sam/model.py +169 -0
  156. ultralytics/models/sam/modules/__init__.py +1 -0
  157. ultralytics/models/sam/modules/blocks.py +1067 -0
  158. ultralytics/models/sam/modules/decoders.py +495 -0
  159. ultralytics/models/sam/modules/encoders.py +794 -0
  160. ultralytics/models/sam/modules/memory_attention.py +298 -0
  161. ultralytics/models/sam/modules/sam.py +1160 -0
  162. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  163. ultralytics/models/sam/modules/transformer.py +344 -0
  164. ultralytics/models/sam/modules/utils.py +512 -0
  165. ultralytics/models/sam/predict.py +3940 -0
  166. ultralytics/models/sam/sam3/__init__.py +3 -0
  167. ultralytics/models/sam/sam3/decoder.py +546 -0
  168. ultralytics/models/sam/sam3/encoder.py +529 -0
  169. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  170. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  171. ultralytics/models/sam/sam3/model_misc.py +199 -0
  172. ultralytics/models/sam/sam3/necks.py +129 -0
  173. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  174. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  175. ultralytics/models/sam/sam3/vitdet.py +547 -0
  176. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  177. ultralytics/models/utils/__init__.py +1 -0
  178. ultralytics/models/utils/loss.py +466 -0
  179. ultralytics/models/utils/ops.py +315 -0
  180. ultralytics/models/yolo/__init__.py +7 -0
  181. ultralytics/models/yolo/classify/__init__.py +7 -0
  182. ultralytics/models/yolo/classify/predict.py +90 -0
  183. ultralytics/models/yolo/classify/train.py +202 -0
  184. ultralytics/models/yolo/classify/val.py +216 -0
  185. ultralytics/models/yolo/detect/__init__.py +7 -0
  186. ultralytics/models/yolo/detect/predict.py +122 -0
  187. ultralytics/models/yolo/detect/train.py +227 -0
  188. ultralytics/models/yolo/detect/val.py +507 -0
  189. ultralytics/models/yolo/model.py +430 -0
  190. ultralytics/models/yolo/obb/__init__.py +7 -0
  191. ultralytics/models/yolo/obb/predict.py +56 -0
  192. ultralytics/models/yolo/obb/train.py +79 -0
  193. ultralytics/models/yolo/obb/val.py +302 -0
  194. ultralytics/models/yolo/pose/__init__.py +7 -0
  195. ultralytics/models/yolo/pose/predict.py +65 -0
  196. ultralytics/models/yolo/pose/train.py +110 -0
  197. ultralytics/models/yolo/pose/val.py +248 -0
  198. ultralytics/models/yolo/segment/__init__.py +7 -0
  199. ultralytics/models/yolo/segment/predict.py +109 -0
  200. ultralytics/models/yolo/segment/train.py +69 -0
  201. ultralytics/models/yolo/segment/val.py +307 -0
  202. ultralytics/models/yolo/world/__init__.py +5 -0
  203. ultralytics/models/yolo/world/train.py +173 -0
  204. ultralytics/models/yolo/world/train_world.py +178 -0
  205. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  206. ultralytics/models/yolo/yoloe/predict.py +162 -0
  207. ultralytics/models/yolo/yoloe/train.py +287 -0
  208. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  209. ultralytics/models/yolo/yoloe/val.py +206 -0
  210. ultralytics/nn/__init__.py +27 -0
  211. ultralytics/nn/autobackend.py +958 -0
  212. ultralytics/nn/modules/__init__.py +182 -0
  213. ultralytics/nn/modules/activation.py +54 -0
  214. ultralytics/nn/modules/block.py +1947 -0
  215. ultralytics/nn/modules/conv.py +669 -0
  216. ultralytics/nn/modules/head.py +1183 -0
  217. ultralytics/nn/modules/transformer.py +793 -0
  218. ultralytics/nn/modules/utils.py +159 -0
  219. ultralytics/nn/tasks.py +1768 -0
  220. ultralytics/nn/text_model.py +356 -0
  221. ultralytics/py.typed +1 -0
  222. ultralytics/solutions/__init__.py +41 -0
  223. ultralytics/solutions/ai_gym.py +108 -0
  224. ultralytics/solutions/analytics.py +264 -0
  225. ultralytics/solutions/config.py +107 -0
  226. ultralytics/solutions/distance_calculation.py +123 -0
  227. ultralytics/solutions/heatmap.py +125 -0
  228. ultralytics/solutions/instance_segmentation.py +86 -0
  229. ultralytics/solutions/object_blurrer.py +89 -0
  230. ultralytics/solutions/object_counter.py +190 -0
  231. ultralytics/solutions/object_cropper.py +87 -0
  232. ultralytics/solutions/parking_management.py +280 -0
  233. ultralytics/solutions/queue_management.py +93 -0
  234. ultralytics/solutions/region_counter.py +133 -0
  235. ultralytics/solutions/security_alarm.py +151 -0
  236. ultralytics/solutions/similarity_search.py +219 -0
  237. ultralytics/solutions/solutions.py +828 -0
  238. ultralytics/solutions/speed_estimation.py +114 -0
  239. ultralytics/solutions/streamlit_inference.py +260 -0
  240. ultralytics/solutions/templates/similarity-search.html +156 -0
  241. ultralytics/solutions/trackzone.py +88 -0
  242. ultralytics/solutions/vision_eye.py +67 -0
  243. ultralytics/trackers/__init__.py +7 -0
  244. ultralytics/trackers/basetrack.py +115 -0
  245. ultralytics/trackers/bot_sort.py +257 -0
  246. ultralytics/trackers/byte_tracker.py +469 -0
  247. ultralytics/trackers/track.py +116 -0
  248. ultralytics/trackers/utils/__init__.py +1 -0
  249. ultralytics/trackers/utils/gmc.py +339 -0
  250. ultralytics/trackers/utils/kalman_filter.py +482 -0
  251. ultralytics/trackers/utils/matching.py +154 -0
  252. ultralytics/utils/__init__.py +1450 -0
  253. ultralytics/utils/autobatch.py +118 -0
  254. ultralytics/utils/autodevice.py +205 -0
  255. ultralytics/utils/benchmarks.py +728 -0
  256. ultralytics/utils/callbacks/__init__.py +5 -0
  257. ultralytics/utils/callbacks/base.py +233 -0
  258. ultralytics/utils/callbacks/clearml.py +146 -0
  259. ultralytics/utils/callbacks/comet.py +625 -0
  260. ultralytics/utils/callbacks/dvc.py +197 -0
  261. ultralytics/utils/callbacks/hub.py +110 -0
  262. ultralytics/utils/callbacks/mlflow.py +134 -0
  263. ultralytics/utils/callbacks/neptune.py +126 -0
  264. ultralytics/utils/callbacks/platform.py +313 -0
  265. ultralytics/utils/callbacks/raytune.py +42 -0
  266. ultralytics/utils/callbacks/tensorboard.py +123 -0
  267. ultralytics/utils/callbacks/wb.py +188 -0
  268. ultralytics/utils/checks.py +1006 -0
  269. ultralytics/utils/cpu.py +85 -0
  270. ultralytics/utils/dist.py +123 -0
  271. ultralytics/utils/downloads.py +529 -0
  272. ultralytics/utils/errors.py +35 -0
  273. ultralytics/utils/events.py +113 -0
  274. ultralytics/utils/export/__init__.py +7 -0
  275. ultralytics/utils/export/engine.py +237 -0
  276. ultralytics/utils/export/imx.py +315 -0
  277. ultralytics/utils/export/tensorflow.py +231 -0
  278. ultralytics/utils/files.py +219 -0
  279. ultralytics/utils/git.py +137 -0
  280. ultralytics/utils/instance.py +484 -0
  281. ultralytics/utils/logger.py +501 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1563 -0
  284. ultralytics/utils/nms.py +337 -0
  285. ultralytics/utils/ops.py +664 -0
  286. ultralytics/utils/patches.py +201 -0
  287. ultralytics/utils/plotting.py +1045 -0
  288. ultralytics/utils/tal.py +403 -0
  289. ultralytics/utils/torch_utils.py +984 -0
  290. ultralytics/utils/tqdm.py +440 -0
  291. ultralytics/utils/triton.py +112 -0
  292. ultralytics/utils/tuner.py +160 -0
  293. ultralytics_opencv_headless-8.3.246.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.246.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.246.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.246.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.246.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.246.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1026 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+ from types import SimpleNamespace
11
+ from typing import Any
12
+
13
+ from ultralytics import __version__
14
+ from ultralytics.utils import (
15
+ ASSETS,
16
+ DEFAULT_CFG,
17
+ DEFAULT_CFG_DICT,
18
+ DEFAULT_CFG_PATH,
19
+ FLOAT_OR_INT,
20
+ IS_VSCODE,
21
+ LOGGER,
22
+ RANK,
23
+ ROOT,
24
+ RUNS_DIR,
25
+ SETTINGS,
26
+ SETTINGS_FILE,
27
+ STR_OR_PATH,
28
+ TESTS_RUNNING,
29
+ YAML,
30
+ IterableSimpleNamespace,
31
+ checks,
32
+ colorstr,
33
+ deprecation_warn,
34
+ vscode_msg,
35
+ )
36
+
37
+ # Define valid solutions
38
+ SOLUTION_MAP = {
39
+ "count": "ObjectCounter",
40
+ "crop": "ObjectCropper",
41
+ "blur": "ObjectBlurrer",
42
+ "workout": "AIGym",
43
+ "heatmap": "Heatmap",
44
+ "isegment": "InstanceSegmentation",
45
+ "visioneye": "VisionEye",
46
+ "speed": "SpeedEstimator",
47
+ "queue": "QueueManager",
48
+ "analytics": "Analytics",
49
+ "inference": "Inference",
50
+ "trackzone": "TrackZone",
51
+ "help": None,
52
+ }
53
+
54
+ # Define valid tasks and modes
55
+ MODES = frozenset({"train", "val", "predict", "export", "track", "benchmark"})
56
+ TASKS = frozenset({"detect", "segment", "classify", "pose", "obb"})
57
+ TASK2DATA = {
58
+ "detect": "coco8.yaml",
59
+ "segment": "coco8-seg.yaml",
60
+ "classify": "imagenet10",
61
+ "pose": "coco8-pose.yaml",
62
+ "obb": "dota8.yaml",
63
+ }
64
+ TASK2MODEL = {
65
+ "detect": "yolo11n.pt",
66
+ "segment": "yolo11n-seg.pt",
67
+ "classify": "yolo11n-cls.pt",
68
+ "pose": "yolo11n-pose.pt",
69
+ "obb": "yolo11n-obb.pt",
70
+ }
71
+ TASK2METRIC = {
72
+ "detect": "metrics/mAP50-95(B)",
73
+ "segment": "metrics/mAP50-95(M)",
74
+ "classify": "metrics/accuracy_top1",
75
+ "pose": "metrics/mAP50-95(P)",
76
+ "obb": "metrics/mAP50-95(B)",
77
+ }
78
+
79
+ ARGV = sys.argv or ["", ""] # sometimes sys.argv = []
80
+ SOLUTIONS_HELP_MSG = f"""
81
+ Arguments received: {["yolo", *ARGV[1:]]!s}. Ultralytics 'yolo solutions' usage overview:
82
+
83
+ yolo solutions SOLUTION ARGS
84
+
85
+ Where SOLUTION (optional) is one of {list(SOLUTION_MAP.keys())[:-1]}
86
+ ARGS (optional) are any number of custom 'arg=value' pairs like 'show_in=True' that override defaults
87
+ at https://docs.ultralytics.com/usage/cfg
88
+
89
+ 1. Call object counting solution
90
+ yolo solutions count source="path/to/video.mp4" region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]"
91
+
92
+ 2. Call heatmap solution
93
+ yolo solutions heatmap colormap=cv2.COLORMAP_PARULA model=yolo11n.pt
94
+
95
+ 3. Call queue management solution
96
+ yolo solutions queue region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]" model=yolo11n.pt
97
+
98
+ 4. Call workout monitoring solution for push-ups
99
+ yolo solutions workout model=yolo11n-pose.pt kpts=[6, 8, 10]
100
+
101
+ 5. Generate analytical graphs
102
+ yolo solutions analytics analytics_type="pie"
103
+
104
+ 6. Track objects within specific zones
105
+ yolo solutions trackzone source="path/to/video.mp4" region="[(150, 150), (1130, 150), (1130, 570), (150, 570)]"
106
+
107
+ 7. Streamlit real-time webcam inference GUI
108
+ yolo streamlit-predict
109
+ """
110
+ CLI_HELP_MSG = f"""
111
+ Arguments received: {["yolo", *ARGV[1:]]!s}. Ultralytics 'yolo' commands use the following syntax:
112
+
113
+ yolo TASK MODE ARGS
114
+
115
+ Where TASK (optional) is one of {list(TASKS)}
116
+ MODE (required) is one of {list(MODES)}
117
+ ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.
118
+ See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'
119
+
120
+ 1. Train a detection model for 10 epochs with an initial learning_rate of 0.01
121
+ yolo train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01
122
+
123
+ 2. Predict a YouTube video using a pretrained segmentation model at image size 320:
124
+ yolo predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320
125
+
126
+ 3. Validate a pretrained detection model at batch-size 1 and image size 640:
127
+ yolo val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640
128
+
129
+ 4. Export a YOLO11n classification model to ONNX format at image size 224 by 128 (no TASK required)
130
+ yolo export model=yolo11n-cls.pt format=onnx imgsz=224,128
131
+
132
+ 5. Ultralytics solutions usage
133
+ yolo solutions count or any of {list(SOLUTION_MAP.keys())[1:-1]} source="path/to/video.mp4"
134
+
135
+ 6. Run special commands:
136
+ yolo help
137
+ yolo checks
138
+ yolo version
139
+ yolo settings
140
+ yolo copy-cfg
141
+ yolo cfg
142
+ yolo solutions help
143
+
144
+ Docs: https://docs.ultralytics.com
145
+ Solutions: https://docs.ultralytics.com/solutions/
146
+ Community: https://community.ultralytics.com
147
+ GitHub: https://github.com/ultralytics/ultralytics
148
+ """
149
+
150
+ # Define keys for arg type checks
151
+ CFG_FLOAT_KEYS = frozenset(
152
+ { # integer or float arguments, i.e. x=2 and x=2.0
153
+ "warmup_epochs",
154
+ "box",
155
+ "cls",
156
+ "dfl",
157
+ "degrees",
158
+ "shear",
159
+ "time",
160
+ "workspace",
161
+ "batch",
162
+ }
163
+ )
164
+ CFG_FRACTION_KEYS = frozenset(
165
+ { # fractional float arguments with 0.0<=values<=1.0
166
+ "dropout",
167
+ "lr0",
168
+ "lrf",
169
+ "momentum",
170
+ "weight_decay",
171
+ "warmup_momentum",
172
+ "warmup_bias_lr",
173
+ "hsv_h",
174
+ "hsv_s",
175
+ "hsv_v",
176
+ "translate",
177
+ "scale",
178
+ "perspective",
179
+ "flipud",
180
+ "fliplr",
181
+ "bgr",
182
+ "mosaic",
183
+ "mixup",
184
+ "cutmix",
185
+ "copy_paste",
186
+ "conf",
187
+ "iou",
188
+ "fraction",
189
+ }
190
+ )
191
+ CFG_INT_KEYS = frozenset(
192
+ { # integer-only arguments
193
+ "epochs",
194
+ "patience",
195
+ "workers",
196
+ "seed",
197
+ "close_mosaic",
198
+ "mask_ratio",
199
+ "max_det",
200
+ "vid_stride",
201
+ "line_width",
202
+ "nbs",
203
+ "save_period",
204
+ }
205
+ )
206
+ CFG_BOOL_KEYS = frozenset(
207
+ { # boolean-only arguments
208
+ "save",
209
+ "exist_ok",
210
+ "verbose",
211
+ "deterministic",
212
+ "single_cls",
213
+ "rect",
214
+ "cos_lr",
215
+ "overlap_mask",
216
+ "val",
217
+ "save_json",
218
+ "half",
219
+ "dnn",
220
+ "plots",
221
+ "show",
222
+ "save_txt",
223
+ "save_conf",
224
+ "save_crop",
225
+ "save_frames",
226
+ "show_labels",
227
+ "show_conf",
228
+ "visualize",
229
+ "augment",
230
+ "agnostic_nms",
231
+ "retina_masks",
232
+ "show_boxes",
233
+ "keras",
234
+ "optimize",
235
+ "int8",
236
+ "dynamic",
237
+ "simplify",
238
+ "nms",
239
+ "profile",
240
+ "multi_scale",
241
+ }
242
+ )
243
+
244
+
245
+ def cfg2dict(cfg: str | Path | dict | SimpleNamespace) -> dict:
246
+ """Convert a configuration object to a dictionary.
247
+
248
+ Args:
249
+ cfg (str | Path | dict | SimpleNamespace): Configuration object to be converted. Can be a file path, a string, a
250
+ dictionary, or a SimpleNamespace object.
251
+
252
+ Returns:
253
+ (dict): Configuration object in dictionary format.
254
+
255
+ Examples:
256
+ Convert a YAML file path to a dictionary:
257
+ >>> config_dict = cfg2dict("config.yaml")
258
+
259
+ Convert a SimpleNamespace to a dictionary:
260
+ >>> from types import SimpleNamespace
261
+ >>> config_sn = SimpleNamespace(param1="value1", param2="value2")
262
+ >>> config_dict = cfg2dict(config_sn)
263
+
264
+ Pass through an already existing dictionary:
265
+ >>> config_dict = cfg2dict({"param1": "value1", "param2": "value2"})
266
+
267
+ Notes:
268
+ - If cfg is a path or string, it's loaded as YAML and converted to a dictionary.
269
+ - If cfg is a SimpleNamespace object, it's converted to a dictionary using vars().
270
+ - If cfg is already a dictionary, it's returned unchanged.
271
+ """
272
+ if isinstance(cfg, STR_OR_PATH):
273
+ cfg = YAML.load(cfg) # load dict
274
+ elif isinstance(cfg, SimpleNamespace):
275
+ cfg = vars(cfg) # convert to dict
276
+ return cfg
277
+
278
+
279
+ def get_cfg(
280
+ cfg: str | Path | dict | SimpleNamespace = DEFAULT_CFG_DICT, overrides: dict | None = None
281
+ ) -> SimpleNamespace:
282
+ """Load and merge configuration data from a file or dictionary, with optional overrides.
283
+
284
+ Args:
285
+ cfg (str | Path | dict | SimpleNamespace): Configuration data source. Can be a file path, dictionary, or
286
+ SimpleNamespace object.
287
+ overrides (dict | None): Dictionary containing key-value pairs to override the base configuration.
288
+
289
+ Returns:
290
+ (SimpleNamespace): Namespace containing the merged configuration arguments.
291
+
292
+ Examples:
293
+ >>> from ultralytics.cfg import get_cfg
294
+ >>> config = get_cfg() # Load default configuration
295
+ >>> config_with_overrides = get_cfg("path/to/config.yaml", overrides={"epochs": 50, "batch_size": 16})
296
+
297
+ Notes:
298
+ - If both `cfg` and `overrides` are provided, the values in `overrides` will take precedence.
299
+ - Special handling ensures alignment and correctness of the configuration, such as converting numeric
300
+ `project` and `name` to strings and validating configuration keys and values.
301
+ - The function performs type and value checks on the configuration data.
302
+ """
303
+ cfg = cfg2dict(cfg)
304
+
305
+ # Merge overrides
306
+ if overrides:
307
+ overrides = cfg2dict(overrides)
308
+ if "save_dir" not in cfg:
309
+ overrides.pop("save_dir", None) # special override keys to ignore
310
+ check_dict_alignment(cfg, overrides)
311
+ cfg = {**cfg, **overrides} # merge cfg and overrides dicts (prefer overrides)
312
+
313
+ # Special handling for numeric project/name
314
+ for k in "project", "name":
315
+ if k in cfg and isinstance(cfg[k], FLOAT_OR_INT):
316
+ cfg[k] = str(cfg[k])
317
+ if cfg.get("name") == "model": # assign model to 'name' arg
318
+ cfg["name"] = str(cfg.get("model", "")).partition(".")[0]
319
+ LOGGER.warning(f"'name=model' automatically updated to 'name={cfg['name']}'.")
320
+
321
+ # Type and Value checks
322
+ check_cfg(cfg)
323
+
324
+ # Return instance
325
+ return IterableSimpleNamespace(**cfg)
326
+
327
+
328
+ def check_cfg(cfg: dict, hard: bool = True) -> None:
329
+ """Check configuration argument types and values for the Ultralytics library.
330
+
331
+ This function validates the types and values of configuration arguments, ensuring correctness and converting them if
332
+ necessary. It checks for specific key types defined in global variables such as `CFG_FLOAT_KEYS`,
333
+ `CFG_FRACTION_KEYS`, `CFG_INT_KEYS`, and `CFG_BOOL_KEYS`.
334
+
335
+ Args:
336
+ cfg (dict): Configuration dictionary to validate.
337
+ hard (bool): If True, raises exceptions for invalid types and values; if False, attempts to convert them.
338
+
339
+ Examples:
340
+ >>> config = {
341
+ ... "epochs": 50, # valid integer
342
+ ... "lr0": 0.01, # valid float
343
+ ... "momentum": 1.2, # invalid float (out of 0.0-1.0 range)
344
+ ... "save": "true", # invalid bool
345
+ ... }
346
+ >>> check_cfg(config, hard=False)
347
+ >>> print(config)
348
+ {'epochs': 50, 'lr0': 0.01, 'momentum': 1.2, 'save': False} # corrected 'save' key
349
+
350
+ Notes:
351
+ - The function modifies the input dictionary in-place.
352
+ - None values are ignored as they may be from optional arguments.
353
+ - Fraction keys are checked to be within the range [0.0, 1.0].
354
+ """
355
+ for k, v in cfg.items():
356
+ if v is not None: # None values may be from optional args
357
+ if k in CFG_FLOAT_KEYS and not isinstance(v, FLOAT_OR_INT):
358
+ if hard:
359
+ raise TypeError(
360
+ f"'{k}={v}' is of invalid type {type(v).__name__}. "
361
+ f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')"
362
+ )
363
+ cfg[k] = float(v)
364
+ elif k in CFG_FRACTION_KEYS:
365
+ if not isinstance(v, FLOAT_OR_INT):
366
+ if hard:
367
+ raise TypeError(
368
+ f"'{k}={v}' is of invalid type {type(v).__name__}. "
369
+ f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')"
370
+ )
371
+ cfg[k] = v = float(v)
372
+ if not (0.0 <= v <= 1.0):
373
+ raise ValueError(f"'{k}={v}' is an invalid value. Valid '{k}' values are between 0.0 and 1.0.")
374
+ elif k in CFG_INT_KEYS and not isinstance(v, int):
375
+ if hard:
376
+ raise TypeError(
377
+ f"'{k}={v}' is of invalid type {type(v).__name__}. '{k}' must be an int (i.e. '{k}=8')"
378
+ )
379
+ cfg[k] = int(v)
380
+ elif k in CFG_BOOL_KEYS and not isinstance(v, bool):
381
+ if hard:
382
+ raise TypeError(
383
+ f"'{k}={v}' is of invalid type {type(v).__name__}. "
384
+ f"'{k}' must be a bool (i.e. '{k}=True' or '{k}=False')"
385
+ )
386
+ cfg[k] = bool(v)
387
+
388
+
389
+ def get_save_dir(args: SimpleNamespace, name: str | None = None) -> Path:
390
+ """Return the directory path for saving outputs, derived from arguments or default settings.
391
+
392
+ Args:
393
+ args (SimpleNamespace): Namespace object containing configurations such as 'project', 'name', 'task', 'mode',
394
+ and 'save_dir'.
395
+ name (str | None): Optional name for the output directory. If not provided, it defaults to 'args.name' or the
396
+ 'args.mode'.
397
+
398
+ Returns:
399
+ (Path): Directory path where outputs should be saved.
400
+
401
+ Examples:
402
+ >>> from types import SimpleNamespace
403
+ >>> args = SimpleNamespace(project="my_project", task="detect", mode="train", exist_ok=True)
404
+ >>> save_dir = get_save_dir(args)
405
+ >>> print(save_dir)
406
+ my_project/detect/train
407
+ """
408
+ if getattr(args, "save_dir", None):
409
+ save_dir = args.save_dir
410
+ else:
411
+ from ultralytics.utils.files import increment_path
412
+
413
+ project = args.project or (ROOT.parent / "tests/tmp/runs" if TESTS_RUNNING else RUNS_DIR) / args.task
414
+ name = name or args.name or f"{args.mode}"
415
+ save_dir = increment_path(Path(project) / name, exist_ok=args.exist_ok if RANK in {-1, 0} else True)
416
+
417
+ return Path(save_dir).resolve() # resolve to display full path in console
418
+
419
+
420
+ def _handle_deprecation(custom: dict) -> dict:
421
+ """Handle deprecated configuration keys by mapping them to current equivalents with deprecation warnings.
422
+
423
+ Args:
424
+ custom (dict): Configuration dictionary potentially containing deprecated keys.
425
+
426
+ Returns:
427
+ (dict): Updated configuration dictionary with deprecated keys replaced.
428
+
429
+ Examples:
430
+ >>> custom_config = {"boxes": True, "hide_labels": "False", "line_thickness": 2}
431
+ >>> _handle_deprecation(custom_config)
432
+ >>> print(custom_config)
433
+ {'show_boxes': True, 'show_labels': True, 'line_width': 2}
434
+
435
+ Notes:
436
+ This function modifies the input dictionary in-place, replacing deprecated keys with their current
437
+ equivalents. It also handles value conversions where necessary, such as inverting boolean values for
438
+ 'hide_labels' and 'hide_conf'.
439
+ """
440
+ deprecated_mappings = {
441
+ "boxes": ("show_boxes", lambda v: v),
442
+ "hide_labels": ("show_labels", lambda v: not bool(v)),
443
+ "hide_conf": ("show_conf", lambda v: not bool(v)),
444
+ "line_thickness": ("line_width", lambda v: v),
445
+ }
446
+ removed_keys = {"label_smoothing", "save_hybrid", "crop_fraction"}
447
+
448
+ for old_key, (new_key, transform) in deprecated_mappings.items():
449
+ if old_key not in custom:
450
+ continue
451
+ deprecation_warn(old_key, new_key)
452
+ custom[new_key] = transform(custom.pop(old_key))
453
+
454
+ for key in removed_keys:
455
+ if key not in custom:
456
+ continue
457
+ deprecation_warn(key)
458
+ custom.pop(key)
459
+
460
+ return custom
461
+
462
+
463
+ def check_dict_alignment(
464
+ base: dict, custom: dict, e: Exception | None = None, allowed_custom_keys: set | None = None
465
+ ) -> None:
466
+ """Check alignment between custom and base configuration dictionaries, handling deprecated keys and providing error
467
+ messages for mismatched keys.
468
+
469
+ Args:
470
+ base (dict): The base configuration dictionary containing valid keys.
471
+ custom (dict): The custom configuration dictionary to be checked for alignment.
472
+ e (Exception | None): Optional error instance passed by the calling function.
473
+ allowed_custom_keys (set | None): Optional set of additional keys that are allowed in the custom dictionary.
474
+
475
+ Raises:
476
+ SystemExit: If mismatched keys are found between the custom and base dictionaries.
477
+
478
+ Examples:
479
+ >>> base_cfg = {"epochs": 50, "lr0": 0.01, "batch_size": 16}
480
+ >>> custom_cfg = {"epoch": 100, "lr": 0.02, "batch_size": 32}
481
+ >>> try:
482
+ ... check_dict_alignment(base_cfg, custom_cfg)
483
+ ... except SystemExit:
484
+ ... print("Mismatched keys found")
485
+
486
+ Notes:
487
+ - Suggests corrections for mismatched keys based on similarity to valid keys.
488
+ - Automatically replaces deprecated keys in the custom configuration with updated equivalents.
489
+ - Prints detailed error messages for each mismatched key to help users correct their configurations.
490
+ """
491
+ custom = _handle_deprecation(custom)
492
+ base_keys, custom_keys = (frozenset(x.keys()) for x in (base, custom))
493
+ # Allow 'augmentations' as a valid custom parameter for custom Albumentations transforms
494
+ if allowed_custom_keys is None:
495
+ allowed_custom_keys = {"augmentations"}
496
+ if mismatched := [k for k in custom_keys if k not in base_keys and k not in allowed_custom_keys]:
497
+ from difflib import get_close_matches
498
+
499
+ string = ""
500
+ for x in mismatched:
501
+ matches = get_close_matches(x, base_keys) # key list
502
+ matches = [f"{k}={base[k]}" if base.get(k) is not None else k for k in matches]
503
+ match_str = f"Similar arguments are i.e. {matches}." if matches else ""
504
+ string += f"'{colorstr('red', 'bold', x)}' is not a valid YOLO argument. {match_str}\n"
505
+ raise SyntaxError(string + CLI_HELP_MSG) from e
506
+
507
+
508
+ def merge_equals_args(args: list[str]) -> list[str]:
509
+ """Merge arguments around isolated '=' in a list of strings and join fragments with brackets.
510
+
511
+ This function handles the following cases:
512
+ 1. ['arg', '=', 'val'] becomes ['arg=val']
513
+ 2. ['arg=', 'val'] becomes ['arg=val']
514
+ 3. ['arg', '=val'] becomes ['arg=val']
515
+ 4. Joins fragments with brackets, e.g., ['imgsz=[3,', '640,', '640]'] becomes ['imgsz=[3,640,640]']
516
+
517
+ Args:
518
+ args (list[str]): A list of strings where each element represents an argument or fragment.
519
+
520
+ Returns:
521
+ (list[str]): A list of strings where the arguments around isolated '=' are merged and fragments with brackets
522
+ are joined.
523
+
524
+ Examples:
525
+ >>> args = ["arg1", "=", "value", "arg2=", "value2", "arg3", "=value3", "imgsz=[3,", "640,", "640]"]
526
+ >>> merge_equals_args(args)
527
+ ['arg1=value', 'arg2=value2', 'arg3=value3', 'imgsz=[3,640,640]']
528
+ """
529
+ new_args = []
530
+ current = ""
531
+ depth = 0
532
+
533
+ i = 0
534
+ while i < len(args):
535
+ arg = args[i]
536
+
537
+ # Handle equals sign merging
538
+ if arg == "=" and 0 < i < len(args) - 1: # merge ['arg', '=', 'val']
539
+ new_args[-1] += f"={args[i + 1]}"
540
+ i += 2
541
+ continue
542
+ elif arg.endswith("=") and i < len(args) - 1 and "=" not in args[i + 1]: # merge ['arg=', 'val']
543
+ new_args.append(f"{arg}{args[i + 1]}")
544
+ i += 2
545
+ continue
546
+ elif arg.startswith("=") and i > 0: # merge ['arg', '=val']
547
+ new_args[-1] += arg
548
+ i += 1
549
+ continue
550
+
551
+ # Handle bracket joining
552
+ depth += arg.count("[") - arg.count("]")
553
+ current += arg
554
+ if depth == 0:
555
+ new_args.append(current)
556
+ current = ""
557
+
558
+ i += 1
559
+
560
+ # Append any remaining current string
561
+ if current:
562
+ new_args.append(current)
563
+
564
+ return new_args
565
+
566
+
567
+ def handle_yolo_hub(args: list[str]) -> None:
568
+ """Handle Ultralytics HUB command-line interface (CLI) commands for authentication.
569
+
570
+ This function processes Ultralytics HUB CLI commands such as login and logout. It should be called when executing a
571
+ script with arguments related to HUB authentication.
572
+
573
+ Args:
574
+ args (list[str]): A list of command line arguments. The first argument should be either 'login' or 'logout'. For
575
+ 'login', an optional second argument can be the API key.
576
+
577
+ Examples:
578
+ $ yolo login YOUR_API_KEY
579
+
580
+ Notes:
581
+ - The function imports the 'hub' module from ultralytics to perform login and logout operations.
582
+ - For the 'login' command, if no API key is provided, an empty string is passed to the login function.
583
+ - The 'logout' command does not require any additional arguments.
584
+ """
585
+ from ultralytics import hub
586
+
587
+ if args[0] == "login":
588
+ key = args[1] if len(args) > 1 else ""
589
+ # Log in to Ultralytics HUB using the provided API key
590
+ hub.login(key)
591
+ elif args[0] == "logout":
592
+ # Log out from Ultralytics HUB
593
+ hub.logout()
594
+
595
+
596
+ def handle_yolo_settings(args: list[str]) -> None:
597
+ """Handle YOLO settings command-line interface (CLI) commands.
598
+
599
+ This function processes YOLO settings CLI commands such as reset and updating individual settings. It should be
600
+ called when executing a script with arguments related to YOLO settings management.
601
+
602
+ Args:
603
+ args (list[str]): A list of command line arguments for YOLO settings management.
604
+
605
+ Examples:
606
+ >>> handle_yolo_settings(["reset"]) # Reset YOLO settings
607
+ >>> handle_yolo_settings(["default_cfg_path=yolo11n.yaml"]) # Update a specific setting
608
+
609
+ Notes:
610
+ - If no arguments are provided, the function will display the current settings.
611
+ - The 'reset' command will delete the existing settings file and create new default settings.
612
+ - Other arguments are treated as key-value pairs to update specific settings.
613
+ - The function will check for alignment between the provided settings and the existing ones.
614
+ - After processing, the updated settings will be displayed.
615
+ - For more information on handling YOLO settings, visit:
616
+ https://docs.ultralytics.com/quickstart/#ultralytics-settings
617
+ """
618
+ url = "https://docs.ultralytics.com/quickstart/#ultralytics-settings" # help URL
619
+ try:
620
+ if any(args):
621
+ if args[0] == "reset":
622
+ SETTINGS_FILE.unlink() # delete the settings file
623
+ SETTINGS.reset() # create new settings
624
+ LOGGER.info("Settings reset successfully") # inform the user that settings have been reset
625
+ else: # save a new setting
626
+ new = dict(parse_key_value_pair(a) for a in args)
627
+ check_dict_alignment(SETTINGS, new)
628
+ SETTINGS.update(new)
629
+ for k, v in new.items():
630
+ LOGGER.info(f"✅ Updated '{k}={v}'")
631
+
632
+ LOGGER.info(SETTINGS) # print the current settings
633
+ LOGGER.info(f"💡 Learn more about Ultralytics Settings at {url}")
634
+ except Exception as e:
635
+ LOGGER.warning(f"settings error: '{e}'. Please see {url} for help.")
636
+
637
+
638
+ def handle_yolo_solutions(args: list[str]) -> None:
639
+ """Process YOLO solutions arguments and run the specified computer vision solutions pipeline.
640
+
641
+ Args:
642
+ args (list[str]): Command-line arguments for configuring and running the Ultralytics YOLO solutions.
643
+
644
+ Examples:
645
+ Run people counting solution with default settings:
646
+ >>> handle_yolo_solutions(["count"])
647
+
648
+ Run analytics with custom configuration:
649
+ >>> handle_yolo_solutions(["analytics", "conf=0.25", "source=path/to/video.mp4"])
650
+
651
+ Run inference with custom configuration, requires Streamlit version 1.29.0 or higher.
652
+ >>> handle_yolo_solutions(["inference", "model=yolo11n.pt"])
653
+
654
+ Notes:
655
+ - Arguments can be provided in the format 'key=value' or as boolean flags
656
+ - Available solutions are defined in SOLUTION_MAP with their respective classes and methods
657
+ - If an invalid solution is provided, defaults to 'count' solution
658
+ - Output videos are saved in 'runs/solution/{solution_name}' directory
659
+ - For 'analytics' solution, frame numbers are tracked for generating analytical graphs
660
+ - Video processing can be interrupted by pressing 'q'
661
+ - Processes video frames sequentially and saves output in .avi format
662
+ - If no source is specified, downloads and uses a default sample video
663
+ - The inference solution will be launched using the 'streamlit run' command.
664
+ - The Streamlit app file is located in the Ultralytics package directory.
665
+ """
666
+ from ultralytics.solutions.config import SolutionConfig
667
+
668
+ full_args_dict = vars(SolutionConfig()) # arguments dictionary
669
+ overrides = {}
670
+
671
+ # check dictionary alignment
672
+ for arg in merge_equals_args(args):
673
+ arg = arg.lstrip("-").rstrip(",")
674
+ if "=" in arg:
675
+ try:
676
+ k, v = parse_key_value_pair(arg)
677
+ overrides[k] = v
678
+ except (NameError, SyntaxError, ValueError, AssertionError) as e:
679
+ check_dict_alignment(full_args_dict, {arg: ""}, e)
680
+ elif arg in full_args_dict and isinstance(full_args_dict.get(arg), bool):
681
+ overrides[arg] = True
682
+ check_dict_alignment(full_args_dict, overrides) # dict alignment
683
+
684
+ # Get solution name
685
+ if not args:
686
+ LOGGER.warning("No solution name provided. i.e `yolo solutions count`. Defaulting to 'count'.")
687
+ args = ["count"]
688
+ if args[0] == "help":
689
+ LOGGER.info(SOLUTIONS_HELP_MSG)
690
+ return # Early return for 'help' case
691
+ elif args[0] in SOLUTION_MAP:
692
+ solution_name = args.pop(0) # Extract the solution name directly
693
+ else:
694
+ LOGGER.warning(
695
+ f"❌ '{args[0]}' is not a valid solution. 💡 Defaulting to 'count'.\n"
696
+ f"🚀 Available solutions: {', '.join(list(SOLUTION_MAP.keys())[:-1])}\n"
697
+ )
698
+ solution_name = "count" # Default for invalid solution
699
+
700
+ if solution_name == "inference":
701
+ checks.check_requirements("streamlit>=1.29.0")
702
+ LOGGER.info("💡 Loading Ultralytics live inference app...")
703
+ subprocess.run(
704
+ [ # Run subprocess with Streamlit custom argument
705
+ "streamlit",
706
+ "run",
707
+ str(ROOT / "solutions/streamlit_inference.py"),
708
+ "--server.headless",
709
+ "true",
710
+ overrides.pop("model", "yolo11n.pt"),
711
+ ]
712
+ )
713
+ else:
714
+ import cv2 # Only needed for cap and vw functionality
715
+
716
+ from ultralytics import solutions
717
+
718
+ solution = getattr(solutions, SOLUTION_MAP[solution_name])(is_cli=True, **overrides) # class i.e. ObjectCounter
719
+
720
+ cap = cv2.VideoCapture(solution.CFG["source"]) # read the video file
721
+ if solution_name != "crop":
722
+ # extract width, height and fps of the video file, create save directory and initialize video writer
723
+ w, h, fps = (
724
+ int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS)
725
+ )
726
+ if solution_name == "analytics": # analytical graphs follow fixed shape for output i.e w=1920, h=1080
727
+ w, h = 1280, 720
728
+ save_dir = get_save_dir(SimpleNamespace(project="runs/solutions", name="exp", exist_ok=False))
729
+ save_dir.mkdir(parents=True) # create the output directory i.e. runs/solutions/exp
730
+ vw = cv2.VideoWriter(str(save_dir / f"{solution_name}.avi"), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
731
+
732
+ try: # Process video frames
733
+ f_n = 0 # frame number, required for analytical graphs
734
+ while cap.isOpened():
735
+ success, frame = cap.read()
736
+ if not success:
737
+ break
738
+ results = solution(frame, f_n := f_n + 1) if solution_name == "analytics" else solution(frame)
739
+ if solution_name != "crop":
740
+ vw.write(results.plot_im)
741
+ if solution.CFG["show"] and cv2.waitKey(1) & 0xFF == ord("q"):
742
+ break
743
+ finally:
744
+ cap.release()
745
+
746
+
747
+ def parse_key_value_pair(pair: str = "key=value") -> tuple:
748
+ """Parse a key-value pair string into separate key and value components.
749
+
750
+ Args:
751
+ pair (str): A string containing a key-value pair in the format "key=value".
752
+
753
+ Returns:
754
+ key (str): The parsed key.
755
+ value (str): The parsed value.
756
+
757
+ Raises:
758
+ AssertionError: If the value is missing or empty.
759
+
760
+ Examples:
761
+ >>> key, value = parse_key_value_pair("model=yolo11n.pt")
762
+ >>> print(f"Key: {key}, Value: {value}")
763
+ Key: model, Value: yolo11n.pt
764
+
765
+ >>> key, value = parse_key_value_pair("epochs=100")
766
+ >>> print(f"Key: {key}, Value: {value}")
767
+ Key: epochs, Value: 100
768
+
769
+ Notes:
770
+ - The function splits the input string on the first '=' character.
771
+ - Leading and trailing whitespace is removed from both key and value.
772
+ - An assertion error is raised if the value is empty after stripping.
773
+ """
774
+ k, v = pair.split("=", 1) # split on first '=' sign
775
+ k, v = k.strip(), v.strip() # remove spaces
776
+ assert v, f"missing '{k}' value"
777
+ return k, smart_value(v)
778
+
779
+
780
+ def smart_value(v: str) -> Any:
781
+ """Convert a string representation of a value to its appropriate Python type.
782
+
783
+ This function attempts to convert a given string into a Python object of the most appropriate type. It handles
784
+ conversions to None, bool, int, float, and other types that can be evaluated safely.
785
+
786
+ Args:
787
+ v (str): The string representation of the value to be converted.
788
+
789
+ Returns:
790
+ (Any): The converted value. The type can be None, bool, int, float, or the original string if no conversion is
791
+ applicable.
792
+
793
+ Examples:
794
+ >>> smart_value("42")
795
+ 42
796
+ >>> smart_value("3.14")
797
+ 3.14
798
+ >>> smart_value("True")
799
+ True
800
+ >>> smart_value("None")
801
+ None
802
+ >>> smart_value("some_string")
803
+ 'some_string'
804
+
805
+ Notes:
806
+ - The function uses a case-insensitive comparison for boolean and None values.
807
+ - For other types, it attempts to use Python's ast.literal_eval() function for safe evaluation.
808
+ - If no conversion is possible, the original string is returned.
809
+ """
810
+ v_lower = v.lower()
811
+ if v_lower == "none":
812
+ return None
813
+ elif v_lower == "true":
814
+ return True
815
+ elif v_lower == "false":
816
+ return False
817
+ else:
818
+ try:
819
+ return ast.literal_eval(v)
820
+ except Exception:
821
+ return v
822
+
823
+
824
+ def entrypoint(debug: str = "") -> None:
825
+ """Ultralytics entrypoint function for parsing and executing command-line arguments.
826
+
827
+ This function serves as the main entry point for the Ultralytics CLI, parsing command-line arguments and executing
828
+ the corresponding tasks such as training, validation, prediction, exporting models, and more.
829
+
830
+ Args:
831
+ debug (str): Space-separated string of command-line arguments for debugging purposes.
832
+
833
+ Examples:
834
+ Train a detection model for 10 epochs with an initial learning_rate of 0.01:
835
+ >>> entrypoint("train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01")
836
+
837
+ Predict a YouTube video using a pretrained segmentation model at image size 320:
838
+ >>> entrypoint("predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320")
839
+
840
+ Validate a pretrained detection model at batch-size 1 and image size 640:
841
+ >>> entrypoint("val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640")
842
+
843
+ Notes:
844
+ - If no arguments are passed, the function will display the usage help message.
845
+ - For a list of all available commands and their arguments, see the provided help messages and the
846
+ Ultralytics documentation at https://docs.ultralytics.com.
847
+ """
848
+ args = (debug.split(" ") if debug else ARGV)[1:]
849
+ if not args: # no arguments passed
850
+ LOGGER.info(CLI_HELP_MSG)
851
+ return
852
+
853
+ special = {
854
+ "checks": checks.collect_system_info,
855
+ "version": lambda: LOGGER.info(__version__),
856
+ "settings": lambda: handle_yolo_settings(args[1:]),
857
+ "cfg": lambda: YAML.print(DEFAULT_CFG_PATH),
858
+ "hub": lambda: handle_yolo_hub(args[1:]),
859
+ "login": lambda: handle_yolo_hub(args),
860
+ "logout": lambda: handle_yolo_hub(args),
861
+ "copy-cfg": copy_default_cfg,
862
+ "solutions": lambda: handle_yolo_solutions(args[1:]),
863
+ "help": lambda: LOGGER.info(CLI_HELP_MSG), # help below hub for -h flag precedence
864
+ }
865
+ full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}
866
+
867
+ # Define common misuses of special commands, i.e. -h, -help, --help
868
+ special.update({k[0]: v for k, v in special.items()}) # singular
869
+ special.update({k[:-1]: v for k, v in special.items() if len(k) > 1 and k.endswith("s")}) # singular
870
+ special = {**special, **{f"-{k}": v for k, v in special.items()}, **{f"--{k}": v for k, v in special.items()}}
871
+
872
+ overrides = {} # basic overrides, i.e. imgsz=320
873
+ for a in merge_equals_args(args): # merge spaces around '=' sign
874
+ if a.startswith("--"):
875
+ LOGGER.warning(f"argument '{a}' does not require leading dashes '--', updating to '{a[2:]}'.")
876
+ a = a[2:]
877
+ if a.endswith(","):
878
+ LOGGER.warning(f"argument '{a}' does not require trailing comma ',', updating to '{a[:-1]}'.")
879
+ a = a[:-1]
880
+ if "=" in a:
881
+ try:
882
+ k, v = parse_key_value_pair(a)
883
+ if k == "cfg" and v is not None: # custom.yaml passed
884
+ LOGGER.info(f"Overriding {DEFAULT_CFG_PATH} with {v}")
885
+ overrides = {k: val for k, val in YAML.load(checks.check_yaml(v)).items() if k != "cfg"}
886
+ else:
887
+ overrides[k] = v
888
+ except (NameError, SyntaxError, ValueError, AssertionError) as e:
889
+ check_dict_alignment(full_args_dict, {a: ""}, e)
890
+
891
+ elif a in TASKS:
892
+ overrides["task"] = a
893
+ elif a in MODES:
894
+ overrides["mode"] = a
895
+ elif a.lower() in special:
896
+ special[a.lower()]()
897
+ return
898
+ elif a in DEFAULT_CFG_DICT and isinstance(DEFAULT_CFG_DICT[a], bool):
899
+ overrides[a] = True # auto-True for default bool args, i.e. 'yolo show' sets show=True
900
+ elif a in DEFAULT_CFG_DICT:
901
+ raise SyntaxError(
902
+ f"'{colorstr('red', 'bold', a)}' is a valid YOLO argument but is missing an '=' sign "
903
+ f"to set its value, i.e. try '{a}={DEFAULT_CFG_DICT[a]}'\n{CLI_HELP_MSG}"
904
+ )
905
+ else:
906
+ check_dict_alignment(full_args_dict, {a: ""})
907
+
908
+ # Check keys
909
+ check_dict_alignment(full_args_dict, overrides)
910
+
911
+ # Mode
912
+ mode = overrides.get("mode")
913
+ if mode is None:
914
+ mode = DEFAULT_CFG.mode or "predict"
915
+ LOGGER.warning(f"'mode' argument is missing. Valid modes are {list(MODES)}. Using default 'mode={mode}'.")
916
+ elif mode not in MODES:
917
+ raise ValueError(f"Invalid 'mode={mode}'. Valid modes are {list(MODES)}.\n{CLI_HELP_MSG}")
918
+
919
+ # Task
920
+ task = overrides.pop("task", None)
921
+ if task:
922
+ if task not in TASKS:
923
+ if task == "track":
924
+ LOGGER.warning(
925
+ f"invalid 'task=track', setting 'task=detect' and 'mode=track'. Valid tasks are {list(TASKS)}.\n{CLI_HELP_MSG}."
926
+ )
927
+ task, mode = "detect", "track"
928
+ else:
929
+ raise ValueError(f"Invalid 'task={task}'. Valid tasks are {list(TASKS)}.\n{CLI_HELP_MSG}")
930
+ if "model" not in overrides:
931
+ overrides["model"] = TASK2MODEL[task]
932
+
933
+ # Model
934
+ model = overrides.pop("model", DEFAULT_CFG.model)
935
+ if model is None:
936
+ model = "yolo11n.pt"
937
+ LOGGER.warning(f"'model' argument is missing. Using default 'model={model}'.")
938
+ overrides["model"] = model
939
+ stem = Path(model).stem.lower()
940
+ if "rtdetr" in stem: # guess architecture
941
+ from ultralytics import RTDETR
942
+
943
+ model = RTDETR(model) # no task argument
944
+ elif "fastsam" in stem:
945
+ from ultralytics import FastSAM
946
+
947
+ model = FastSAM(model)
948
+ elif "sam_" in stem or "sam2_" in stem or "sam2.1_" in stem:
949
+ from ultralytics import SAM
950
+
951
+ model = SAM(model)
952
+ else:
953
+ from ultralytics import YOLO
954
+
955
+ model = YOLO(model, task=task)
956
+ if "yoloe" in stem or "world" in stem:
957
+ cls_list = overrides.pop("classes", DEFAULT_CFG.classes)
958
+ if cls_list is not None and isinstance(cls_list, str):
959
+ model.set_classes(cls_list.split(",")) # convert "person, bus" -> ['person', ' bus'].
960
+ # Task Update
961
+ if task != model.task:
962
+ if task:
963
+ LOGGER.warning(
964
+ f"conflicting 'task={task}' passed with 'task={model.task}' model. "
965
+ f"Ignoring 'task={task}' and updating to 'task={model.task}' to match model."
966
+ )
967
+ task = model.task
968
+
969
+ # Mode
970
+ if mode in {"predict", "track"} and "source" not in overrides:
971
+ overrides["source"] = (
972
+ "https://ultralytics.com/images/boats.jpg" if task == "obb" else DEFAULT_CFG.source or ASSETS
973
+ )
974
+ LOGGER.warning(f"'source' argument is missing. Using default 'source={overrides['source']}'.")
975
+ elif mode in {"train", "val"}:
976
+ if "data" not in overrides and "resume" not in overrides:
977
+ overrides["data"] = DEFAULT_CFG.data or TASK2DATA.get(task or DEFAULT_CFG.task, DEFAULT_CFG.data)
978
+ LOGGER.warning(f"'data' argument is missing. Using default 'data={overrides['data']}'.")
979
+ elif mode == "export":
980
+ if "format" not in overrides:
981
+ overrides["format"] = DEFAULT_CFG.format or "torchscript"
982
+ LOGGER.warning(f"'format' argument is missing. Using default 'format={overrides['format']}'.")
983
+
984
+ # Run command in python
985
+ getattr(model, mode)(**overrides) # default args from model
986
+
987
+ # Show help
988
+ LOGGER.info(f"💡 Learn more at https://docs.ultralytics.com/modes/{mode}")
989
+
990
+ # Recommend VS Code extension
991
+ if IS_VSCODE and SETTINGS.get("vscode_msg", True):
992
+ LOGGER.info(vscode_msg())
993
+
994
+
995
+ # Special modes --------------------------------------------------------------------------------------------------------
996
+ def copy_default_cfg() -> None:
997
+ """Copy the default configuration file and create a new one with '_copy' appended to its name.
998
+
999
+ This function duplicates the existing default configuration file (DEFAULT_CFG_PATH) and saves it with '_copy'
1000
+ appended to its name in the current working directory. It provides a convenient way to create a custom configuration
1001
+ file based on the default settings.
1002
+
1003
+ Examples:
1004
+ >>> copy_default_cfg()
1005
+ # Output: default.yaml copied to /path/to/current/directory/default_copy.yaml
1006
+ # Example YOLO command with this new custom cfg:
1007
+ # yolo cfg='/path/to/current/directory/default_copy.yaml' imgsz=320 batch=8
1008
+
1009
+ Notes:
1010
+ - The new configuration file is created in the current working directory.
1011
+ - After copying, the function prints a message with the new file's location and an example
1012
+ YOLO command demonstrating how to use the new configuration file.
1013
+ - This function is useful for users who want to modify the default configuration without
1014
+ altering the original file.
1015
+ """
1016
+ new_file = Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml")
1017
+ shutil.copy2(DEFAULT_CFG_PATH, new_file)
1018
+ LOGGER.info(
1019
+ f"{DEFAULT_CFG_PATH} copied to {new_file}\n"
1020
+ f"Example YOLO command with this new custom cfg:\n yolo cfg='{new_file}' imgsz=320 batch=8"
1021
+ )
1022
+
1023
+
1024
+ if __name__ == "__main__":
1025
+ # Example: entrypoint(debug='yolo predict model=yolo11n.pt')
1026
+ entrypoint(debug="")