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,119 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import os
4
+ import shutil
5
+ import sys
6
+ import tempfile
7
+
8
+ from . import USER_CONFIG_DIR
9
+ from .torch_utils import TORCH_1_9
10
+
11
+
12
+ def find_free_network_port() -> int:
13
+ """
14
+ Find a free port on localhost.
15
+
16
+ It is useful in single-node training when we don't want to connect to a real main node but have to set the
17
+ `MASTER_PORT` environment variable.
18
+
19
+ Returns:
20
+ (int): The available network port number.
21
+ """
22
+ import socket
23
+
24
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
25
+ s.bind(("127.0.0.1", 0))
26
+ return s.getsockname()[1] # port
27
+
28
+
29
+ def generate_ddp_file(trainer):
30
+ """
31
+ Generate a DDP (Distributed Data Parallel) file for multi-GPU training.
32
+
33
+ This function creates a temporary Python file that enables distributed training across multiple GPUs.
34
+ The file contains the necessary configuration to initialize the trainer in a distributed environment.
35
+
36
+ Args:
37
+ trainer (object): The trainer object containing training configuration and arguments.
38
+ Must have args attribute and be a class instance.
39
+
40
+ Returns:
41
+ (str): Path to the generated temporary DDP file.
42
+
43
+ Notes:
44
+ The generated file is saved in the USER_CONFIG_DIR/DDP directory and includes:
45
+ - Trainer class import
46
+ - Configuration overrides from the trainer arguments
47
+ - Model path configuration
48
+ - Training initialization code
49
+ """
50
+ module, name = f"{trainer.__class__.__module__}.{trainer.__class__.__name__}".rsplit(".", 1)
51
+
52
+ content = f"""
53
+ # Ultralytics Multi-GPU training temp file (should be automatically deleted after use)
54
+ overrides = {vars(trainer.args)}
55
+
56
+ if __name__ == "__main__":
57
+ from {module} import {name}
58
+ from ultralytics.utils import DEFAULT_CFG_DICT
59
+
60
+ cfg = DEFAULT_CFG_DICT.copy()
61
+ cfg.update(save_dir='') # handle the extra key 'save_dir'
62
+ trainer = {name}(cfg=cfg, overrides=overrides)
63
+ trainer.args.model = "{getattr(trainer.hub_session, "model_url", trainer.args.model)}"
64
+ results = trainer.train()
65
+ """
66
+ (USER_CONFIG_DIR / "DDP").mkdir(exist_ok=True)
67
+ with tempfile.NamedTemporaryFile(
68
+ prefix="_temp_",
69
+ suffix=f"{id(trainer)}.py",
70
+ mode="w+",
71
+ encoding="utf-8",
72
+ dir=USER_CONFIG_DIR / "DDP",
73
+ delete=False,
74
+ ) as file:
75
+ file.write(content)
76
+ return file.name
77
+
78
+
79
+ def generate_ddp_command(world_size, trainer):
80
+ """
81
+ Generate command for distributed training.
82
+
83
+ Args:
84
+ world_size (int): Number of processes to spawn for distributed training.
85
+ trainer (object): The trainer object containing configuration for distributed training.
86
+
87
+ Returns:
88
+ cmd (List[str]): The command to execute for distributed training.
89
+ file (str): Path to the temporary file created for DDP training.
90
+ """
91
+ import __main__ # noqa local import to avoid https://github.com/Lightning-AI/pytorch-lightning/issues/15218
92
+
93
+ if not trainer.resume:
94
+ shutil.rmtree(trainer.save_dir) # remove the save_dir
95
+ file = generate_ddp_file(trainer)
96
+ dist_cmd = "torch.distributed.run" if TORCH_1_9 else "torch.distributed.launch"
97
+ port = find_free_network_port()
98
+ cmd = [sys.executable, "-m", dist_cmd, "--nproc_per_node", f"{world_size}", "--master_port", f"{port}", file]
99
+ return cmd, file
100
+
101
+
102
+ def ddp_cleanup(trainer, file):
103
+ """
104
+ Delete temporary file if created during distributed data parallel (DDP) training.
105
+
106
+ This function checks if the provided file contains the trainer's ID in its name, indicating it was created
107
+ as a temporary file for DDP training, and deletes it if so.
108
+
109
+ Args:
110
+ trainer (object): The trainer object used for distributed training.
111
+ file (str): Path to the file that might need to be deleted.
112
+
113
+ Examples:
114
+ >>> trainer = YOLOTrainer()
115
+ >>> file = "/tmp/ddp_temp_123456789.py"
116
+ >>> ddp_cleanup(trainer, file)
117
+ """
118
+ if f"{id(trainer)}.py" in file: # if temp_file suffix in file
119
+ os.remove(file)
@@ -0,0 +1,499 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import re
4
+ import shutil
5
+ import subprocess
6
+ from itertools import repeat
7
+ from multiprocessing.pool import ThreadPool
8
+ from pathlib import Path
9
+ from urllib import parse, request
10
+
11
+ import torch
12
+
13
+ from ultralytics.utils import LOGGER, TQDM, checks, clean_url, emojis, is_online, url2file
14
+
15
+ # Define Ultralytics GitHub assets maintained at https://github.com/ultralytics/assets
16
+ GITHUB_ASSETS_REPO = "ultralytics/assets"
17
+ GITHUB_ASSETS_NAMES = frozenset(
18
+ [f"yolov8{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose", "-obb", "-oiv7")]
19
+ + [f"yolo11{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose", "-obb")]
20
+ + [f"yolo12{k}{suffix}.pt" for k in "nsmlx" for suffix in ("",)] # detect models only currently
21
+ + [f"yolov5{k}{resolution}u.pt" for k in "nsmlx" for resolution in ("", "6")]
22
+ + [f"yolov3{k}u.pt" for k in ("", "-spp", "-tiny")]
23
+ + [f"yolov8{k}-world.pt" for k in "smlx"]
24
+ + [f"yolov8{k}-worldv2.pt" for k in "smlx"]
25
+ + [f"yoloe-v8{k}{suffix}.pt" for k in "sml" for suffix in ("-seg", "-seg-pf")]
26
+ + [f"yoloe-11{k}{suffix}.pt" for k in "sml" for suffix in ("-seg", "-seg-pf")]
27
+ + [f"yolov9{k}.pt" for k in "tsmce"]
28
+ + [f"yolov10{k}.pt" for k in "nsmblx"]
29
+ + [f"yolo_nas_{k}.pt" for k in "sml"]
30
+ + [f"sam_{k}.pt" for k in "bl"]
31
+ + [f"sam2_{k}.pt" for k in "blst"]
32
+ + [f"sam2.1_{k}.pt" for k in "blst"]
33
+ + [f"FastSAM-{k}.pt" for k in "sx"]
34
+ + [f"rtdetr-{k}.pt" for k in "lx"]
35
+ + ["mobile_sam.pt"]
36
+ + ["mobileclip_blt.ts"]
37
+ + ["calibration_image_sample_data_20x128x128x3_float32.npy.zip"]
38
+ )
39
+ GITHUB_ASSETS_STEMS = frozenset(k.rsplit(".", 1)[0] for k in GITHUB_ASSETS_NAMES)
40
+
41
+
42
+ def is_url(url, check=False):
43
+ """
44
+ Validates if the given string is a URL and optionally checks if the URL exists online.
45
+
46
+ Args:
47
+ url (str): The string to be validated as a URL.
48
+ check (bool, optional): If True, performs an additional check to see if the URL exists online.
49
+ Defaults to False.
50
+
51
+ Returns:
52
+ (bool): Returns True for a valid URL. If 'check' is True, also returns True if the URL exists online.
53
+ Returns False otherwise.
54
+
55
+ Examples:
56
+ >>> valid = is_url("https://www.example.com")
57
+ """
58
+ try:
59
+ url = str(url)
60
+ result = parse.urlparse(url)
61
+ assert all([result.scheme, result.netloc]) # check if is url
62
+ if check:
63
+ with request.urlopen(url) as response:
64
+ return response.getcode() == 200 # check if exists online
65
+ return True
66
+ except Exception:
67
+ return False
68
+
69
+
70
+ def delete_dsstore(path, files_to_delete=(".DS_Store", "__MACOSX")):
71
+ """
72
+ Delete all ".DS_store" files in a specified directory.
73
+
74
+ Args:
75
+ path (str, optional): The directory path where the ".DS_store" files should be deleted.
76
+ files_to_delete (tuple): The files to be deleted.
77
+
78
+ Examples:
79
+ >>> from ultralytics.utils.downloads import delete_dsstore
80
+ >>> delete_dsstore("path/to/dir")
81
+
82
+ Notes:
83
+ ".DS_store" files are created by the Apple operating system and contain metadata about folders and files. They
84
+ are hidden system files and can cause issues when transferring files between different operating systems.
85
+ """
86
+ for file in files_to_delete:
87
+ matches = list(Path(path).rglob(file))
88
+ LOGGER.info(f"Deleting {file} files: {matches}")
89
+ for f in matches:
90
+ f.unlink()
91
+
92
+
93
+ def zip_directory(directory, compress=True, exclude=(".DS_Store", "__MACOSX"), progress=True):
94
+ """
95
+ Zips the contents of a directory, excluding files containing strings in the exclude list. The resulting zip file is
96
+ named after the directory and placed alongside it.
97
+
98
+ Args:
99
+ directory (str | Path): The path to the directory to be zipped.
100
+ compress (bool): Whether to compress the files while zipping. Default is True.
101
+ exclude (tuple, optional): A tuple of filename strings to be excluded. Defaults to ('.DS_Store', '__MACOSX').
102
+ progress (bool, optional): Whether to display a progress bar. Defaults to True.
103
+
104
+ Returns:
105
+ (Path): The path to the resulting zip file.
106
+
107
+ Examples:
108
+ >>> from ultralytics.utils.downloads import zip_directory
109
+ >>> file = zip_directory("path/to/dir")
110
+ """
111
+ from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
112
+
113
+ delete_dsstore(directory)
114
+ directory = Path(directory)
115
+ if not directory.is_dir():
116
+ raise FileNotFoundError(f"Directory '{directory}' does not exist.")
117
+
118
+ # Unzip with progress bar
119
+ files_to_zip = [f for f in directory.rglob("*") if f.is_file() and all(x not in f.name for x in exclude)]
120
+ zip_file = directory.with_suffix(".zip")
121
+ compression = ZIP_DEFLATED if compress else ZIP_STORED
122
+ with ZipFile(zip_file, "w", compression) as f:
123
+ for file in TQDM(files_to_zip, desc=f"Zipping {directory} to {zip_file}...", unit="file", disable=not progress):
124
+ f.write(file, file.relative_to(directory))
125
+
126
+ return zip_file # return path to zip file
127
+
128
+
129
+ def unzip_file(file, path=None, exclude=(".DS_Store", "__MACOSX"), exist_ok=False, progress=True):
130
+ """
131
+ Unzips a *.zip file to the specified path, excluding files containing strings in the exclude list.
132
+
133
+ If the zipfile does not contain a single top-level directory, the function will create a new
134
+ directory with the same name as the zipfile (without the extension) to extract its contents.
135
+ If a path is not provided, the function will use the parent directory of the zipfile as the default path.
136
+
137
+ Args:
138
+ file (str | Path): The path to the zipfile to be extracted.
139
+ path (str | Path, optional): The path to extract the zipfile to. Defaults to None.
140
+ exclude (tuple, optional): A tuple of filename strings to be excluded. Defaults to ('.DS_Store', '__MACOSX').
141
+ exist_ok (bool, optional): Whether to overwrite existing contents if they exist. Defaults to False.
142
+ progress (bool, optional): Whether to display a progress bar. Defaults to True.
143
+
144
+ Raises:
145
+ BadZipFile: If the provided file does not exist or is not a valid zipfile.
146
+
147
+ Returns:
148
+ (Path): The path to the directory where the zipfile was extracted.
149
+
150
+ Examples:
151
+ >>> from ultralytics.utils.downloads import unzip_file
152
+ >>> directory = unzip_file("path/to/file.zip")
153
+ """
154
+ from zipfile import BadZipFile, ZipFile, is_zipfile
155
+
156
+ if not (Path(file).exists() and is_zipfile(file)):
157
+ raise BadZipFile(f"File '{file}' does not exist or is a bad zip file.")
158
+ if path is None:
159
+ path = Path(file).parent # default path
160
+
161
+ # Unzip the file contents
162
+ with ZipFile(file) as zipObj:
163
+ files = [f for f in zipObj.namelist() if all(x not in f for x in exclude)]
164
+ top_level_dirs = {Path(f).parts[0] for f in files}
165
+
166
+ # Decide to unzip directly or unzip into a directory
167
+ unzip_as_dir = len(top_level_dirs) == 1 # (len(files) > 1 and not files[0].endswith("/"))
168
+ if unzip_as_dir:
169
+ # Zip has 1 top-level directory
170
+ extract_path = path # i.e. ../datasets
171
+ path = Path(path) / list(top_level_dirs)[0] # i.e. extract coco8/ dir to ../datasets/
172
+ else:
173
+ # Zip has multiple files at top level
174
+ path = extract_path = Path(path) / Path(file).stem # i.e. extract multiple files to ../datasets/coco8/
175
+
176
+ # Check if destination directory already exists and contains files
177
+ if path.exists() and any(path.iterdir()) and not exist_ok:
178
+ # If it exists and is not empty, return the path without unzipping
179
+ LOGGER.warning(f"Skipping {file} unzip as destination directory {path} is not empty.")
180
+ return path
181
+
182
+ for f in TQDM(files, desc=f"Unzipping {file} to {Path(path).resolve()}...", unit="file", disable=not progress):
183
+ # Ensure the file is within the extract_path to avoid path traversal security vulnerability
184
+ if ".." in Path(f).parts:
185
+ LOGGER.warning(f"Potentially insecure file path: {f}, skipping extraction.")
186
+ continue
187
+ zipObj.extract(f, extract_path)
188
+
189
+ return path # return unzip dir
190
+
191
+
192
+ def check_disk_space(url="https://ultralytics.com/assets/coco8.zip", path=Path.cwd(), sf=1.5, hard=True):
193
+ """
194
+ Check if there is sufficient disk space to download and store a file.
195
+
196
+ Args:
197
+ url (str, optional): The URL to the file. Defaults to 'https://ultralytics.com/assets/coco8.zip'.
198
+ path (str | Path, optional): The path or drive to check the available free space on.
199
+ sf (float, optional): Safety factor, the multiplier for the required free space. Defaults to 1.5.
200
+ hard (bool, optional): Whether to throw an error or not on insufficient disk space. Defaults to True.
201
+
202
+ Returns:
203
+ (bool): True if there is sufficient disk space, False otherwise.
204
+ """
205
+ import requests # slow import
206
+
207
+ try:
208
+ r = requests.head(url) # response
209
+ assert r.status_code < 400, f"URL error for {url}: {r.status_code} {r.reason}" # check response
210
+ except Exception:
211
+ return True # requests issue, default to True
212
+
213
+ # Check file size
214
+ gib = 1 << 30 # bytes per GiB
215
+ data = int(r.headers.get("Content-Length", 0)) / gib # file size (GB)
216
+ total, used, free = (x / gib for x in shutil.disk_usage(path)) # bytes
217
+
218
+ if data * sf < free:
219
+ return True # sufficient space
220
+
221
+ # Insufficient space
222
+ text = (
223
+ f"Insufficient free disk space {free:.1f} GB < {data * sf:.3f} GB required, "
224
+ f"Please free {data * sf - free:.1f} GB additional disk space and try again."
225
+ )
226
+ if hard:
227
+ raise MemoryError(text)
228
+ LOGGER.warning(text)
229
+ return False
230
+
231
+
232
+ def get_google_drive_file_info(link):
233
+ """
234
+ Retrieves the direct download link and filename for a shareable Google Drive file link.
235
+
236
+ Args:
237
+ link (str): The shareable link of the Google Drive file.
238
+
239
+ Returns:
240
+ (str): Direct download URL for the Google Drive file.
241
+ (str): Original filename of the Google Drive file. If filename extraction fails, returns None.
242
+
243
+ Examples:
244
+ >>> from ultralytics.utils.downloads import get_google_drive_file_info
245
+ >>> link = "https://drive.google.com/file/d/1cqT-cJgANNrhIHCrEufUYhQ4RqiWG_lJ/view?usp=drive_link"
246
+ >>> url, filename = get_google_drive_file_info(link)
247
+ """
248
+ import requests # slow import
249
+
250
+ file_id = link.split("/d/")[1].split("/view")[0]
251
+ drive_url = f"https://drive.google.com/uc?export=download&id={file_id}"
252
+ filename = None
253
+
254
+ # Start session
255
+ with requests.Session() as session:
256
+ response = session.get(drive_url, stream=True)
257
+ if "quota exceeded" in str(response.content.lower()):
258
+ raise ConnectionError(
259
+ emojis(
260
+ f"❌ Google Drive file download quota exceeded. "
261
+ f"Please try again later or download this file manually at {link}."
262
+ )
263
+ )
264
+ for k, v in response.cookies.items():
265
+ if k.startswith("download_warning"):
266
+ drive_url += f"&confirm={v}" # v is token
267
+ if cd := response.headers.get("content-disposition"):
268
+ filename = re.findall('filename="(.+)"', cd)[0]
269
+ return drive_url, filename
270
+
271
+
272
+ def safe_download(
273
+ url,
274
+ file=None,
275
+ dir=None,
276
+ unzip=True,
277
+ delete=False,
278
+ curl=False,
279
+ retry=3,
280
+ min_bytes=1e0,
281
+ exist_ok=False,
282
+ progress=True,
283
+ ):
284
+ """
285
+ Downloads files from a URL, with options for retrying, unzipping, and deleting the downloaded file.
286
+
287
+ Args:
288
+ url (str): The URL of the file to be downloaded.
289
+ file (str, optional): The filename of the downloaded file.
290
+ If not provided, the file will be saved with the same name as the URL.
291
+ dir (str | Path, optional): The directory to save the downloaded file.
292
+ If not provided, the file will be saved in the current working directory.
293
+ unzip (bool, optional): Whether to unzip the downloaded file. Default: True.
294
+ delete (bool, optional): Whether to delete the downloaded file after unzipping. Default: False.
295
+ curl (bool, optional): Whether to use curl command line tool for downloading. Default: False.
296
+ retry (int, optional): The number of times to retry the download in case of failure. Default: 3.
297
+ min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered
298
+ a successful download. Default: 1E0.
299
+ exist_ok (bool, optional): Whether to overwrite existing contents during unzipping. Defaults to False.
300
+ progress (bool, optional): Whether to display a progress bar during the download. Default: True.
301
+
302
+ Returns:
303
+ (Path | str): The path to the downloaded file or extracted directory.
304
+
305
+ Examples:
306
+ >>> from ultralytics.utils.downloads import safe_download
307
+ >>> link = "https://ultralytics.com/assets/bus.jpg"
308
+ >>> path = safe_download(link)
309
+ """
310
+ gdrive = url.startswith("https://drive.google.com/") # check if the URL is a Google Drive link
311
+ if gdrive:
312
+ url, file = get_google_drive_file_info(url)
313
+
314
+ f = Path(dir or ".") / (file or url2file(url)) # URL converted to filename
315
+ if "://" not in str(url) and Path(url).is_file(): # URL exists ('://' check required in Windows Python<3.10)
316
+ f = Path(url) # filename
317
+ elif not f.is_file(): # URL and file do not exist
318
+ uri = (url if gdrive else clean_url(url)).replace( # cleaned and aliased url
319
+ "https://github.com/ultralytics/assets/releases/download/v0.0.0/",
320
+ "https://ultralytics.com/assets/", # assets alias
321
+ )
322
+ desc = f"Downloading {uri} to '{f}'"
323
+ LOGGER.info(f"{desc}...")
324
+ f.parent.mkdir(parents=True, exist_ok=True) # make directory if missing
325
+ check_disk_space(url, path=f.parent)
326
+ curl_installed = shutil.which("curl")
327
+ for i in range(retry + 1):
328
+ try:
329
+ if (curl or i > 0) and curl_installed: # curl download with retry, continue
330
+ s = "sS" * (not progress) # silent
331
+ r = subprocess.run(["curl", "-#", f"-{s}L", url, "-o", f, "--retry", "3", "-C", "-"]).returncode
332
+ assert r == 0, f"Curl return value {r}"
333
+ else: # urllib download
334
+ method = "torch"
335
+ if method == "torch":
336
+ torch.hub.download_url_to_file(url, f, progress=progress)
337
+ else:
338
+ with request.urlopen(url) as response, TQDM(
339
+ total=int(response.getheader("Content-Length", 0)),
340
+ desc=desc,
341
+ disable=not progress,
342
+ unit="B",
343
+ unit_scale=True,
344
+ unit_divisor=1024,
345
+ ) as pbar:
346
+ with open(f, "wb") as f_opened:
347
+ for data in response:
348
+ f_opened.write(data)
349
+ pbar.update(len(data))
350
+
351
+ if f.exists():
352
+ if f.stat().st_size > min_bytes:
353
+ break # success
354
+ f.unlink() # remove partial downloads
355
+ except Exception as e:
356
+ if i == 0 and not is_online():
357
+ raise ConnectionError(emojis(f"❌ Download failure for {uri}. Environment is not online.")) from e
358
+ elif i >= retry:
359
+ raise ConnectionError(emojis(f"❌ Download failure for {uri}. Retry limit reached.")) from e
360
+ LOGGER.warning(f"Download failure, retrying {i + 1}/{retry} {uri}...")
361
+
362
+ if unzip and f.exists() and f.suffix in {"", ".zip", ".tar", ".gz"}:
363
+ from zipfile import is_zipfile
364
+
365
+ unzip_dir = (dir or f.parent).resolve() # unzip to dir if provided else unzip in place
366
+ if is_zipfile(f):
367
+ unzip_dir = unzip_file(file=f, path=unzip_dir, exist_ok=exist_ok, progress=progress) # unzip
368
+ elif f.suffix in {".tar", ".gz"}:
369
+ LOGGER.info(f"Unzipping {f} to {unzip_dir}...")
370
+ subprocess.run(["tar", "xf" if f.suffix == ".tar" else "xfz", f, "--directory", unzip_dir], check=True)
371
+ if delete:
372
+ f.unlink() # remove zip
373
+ return unzip_dir
374
+ return f
375
+
376
+
377
+ def get_github_assets(repo="ultralytics/assets", version="latest", retry=False):
378
+ """
379
+ Retrieve the specified version's tag and assets from a GitHub repository. If the version is not specified, the
380
+ function fetches the latest release assets.
381
+
382
+ Args:
383
+ repo (str, optional): The GitHub repository in the format 'owner/repo'. Defaults to 'ultralytics/assets'.
384
+ version (str, optional): The release version to fetch assets from. Defaults to 'latest'.
385
+ retry (bool, optional): Flag to retry the request in case of a failure. Defaults to False.
386
+
387
+ Returns:
388
+ (str): The release tag.
389
+ (List[str]): A list of asset names.
390
+
391
+ Examples:
392
+ >>> tag, assets = get_github_assets(repo="ultralytics/assets", version="latest")
393
+ """
394
+ import requests # slow import
395
+
396
+ if version != "latest":
397
+ version = f"tags/{version}" # i.e. tags/v6.2
398
+ url = f"https://api.github.com/repos/{repo}/releases/{version}"
399
+ r = requests.get(url) # github api
400
+ if r.status_code != 200 and r.reason != "rate limit exceeded" and retry: # failed and not 403 rate limit exceeded
401
+ r = requests.get(url) # try again
402
+ if r.status_code != 200:
403
+ LOGGER.warning(f"GitHub assets check failure for {url}: {r.status_code} {r.reason}")
404
+ return "", []
405
+ data = r.json()
406
+ return data["tag_name"], [x["name"] for x in data["assets"]] # tag, assets i.e. ['yolo11n.pt', 'yolov8s.pt', ...]
407
+
408
+
409
+ def attempt_download_asset(file, repo="ultralytics/assets", release="v8.3.0", **kwargs):
410
+ """
411
+ Attempt to download a file from GitHub release assets if it is not found locally.
412
+
413
+ Args:
414
+ file (str | Path): The filename or file path to be downloaded.
415
+ repo (str, optional): The GitHub repository in the format 'owner/repo'. Defaults to 'ultralytics/assets'.
416
+ release (str, optional): The specific release version to be downloaded. Defaults to 'v8.3.0'.
417
+ **kwargs (Any): Additional keyword arguments for the download process.
418
+
419
+ Returns:
420
+ (str): The path to the downloaded file.
421
+
422
+ Examples:
423
+ >>> file_path = attempt_download_asset("yolo11n.pt", repo="ultralytics/assets", release="latest")
424
+ """
425
+ from ultralytics.utils import SETTINGS # scoped for circular import
426
+
427
+ # YOLOv3/5u updates
428
+ file = str(file)
429
+ file = checks.check_yolov5u_filename(file)
430
+ file = Path(file.strip().replace("'", ""))
431
+ if file.exists():
432
+ return str(file)
433
+ elif (SETTINGS["weights_dir"] / file).exists():
434
+ return str(SETTINGS["weights_dir"] / file)
435
+ else:
436
+ # URL specified
437
+ name = Path(parse.unquote(str(file))).name # decode '%2F' to '/' etc.
438
+ download_url = f"https://github.com/{repo}/releases/download"
439
+ if str(file).startswith(("http:/", "https:/")): # download
440
+ url = str(file).replace(":/", "://") # Pathlib turns :// -> :/
441
+ file = url2file(name) # parse authentication https://url.com/file.txt?auth...
442
+ if Path(file).is_file():
443
+ LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists
444
+ else:
445
+ safe_download(url=url, file=file, min_bytes=1e5, **kwargs)
446
+
447
+ elif repo == GITHUB_ASSETS_REPO and name in GITHUB_ASSETS_NAMES:
448
+ safe_download(url=f"{download_url}/{release}/{name}", file=file, min_bytes=1e5, **kwargs)
449
+
450
+ else:
451
+ tag, assets = get_github_assets(repo, release)
452
+ if not assets:
453
+ tag, assets = get_github_assets(repo) # latest release
454
+ if name in assets:
455
+ safe_download(url=f"{download_url}/{tag}/{name}", file=file, min_bytes=1e5, **kwargs)
456
+
457
+ return str(file)
458
+
459
+
460
+ def download(url, dir=Path.cwd(), unzip=True, delete=False, curl=False, threads=1, retry=3, exist_ok=False):
461
+ """
462
+ Downloads files from specified URLs to a given directory. Supports concurrent downloads if multiple threads are
463
+ specified.
464
+
465
+ Args:
466
+ url (str | List[str]): The URL or list of URLs of the files to be downloaded.
467
+ dir (Path, optional): The directory where the files will be saved. Defaults to the current working directory.
468
+ unzip (bool, optional): Flag to unzip the files after downloading. Defaults to True.
469
+ delete (bool, optional): Flag to delete the zip files after extraction. Defaults to False.
470
+ curl (bool, optional): Flag to use curl for downloading. Defaults to False.
471
+ threads (int, optional): Number of threads to use for concurrent downloads. Defaults to 1.
472
+ retry (int, optional): Number of retries in case of download failure. Defaults to 3.
473
+ exist_ok (bool, optional): Whether to overwrite existing contents during unzipping. Defaults to False.
474
+
475
+ Examples:
476
+ >>> download("https://ultralytics.com/assets/example.zip", dir="path/to/dir", unzip=True)
477
+ """
478
+ dir = Path(dir)
479
+ dir.mkdir(parents=True, exist_ok=True) # make directory
480
+ if threads > 1:
481
+ with ThreadPool(threads) as pool:
482
+ pool.map(
483
+ lambda x: safe_download(
484
+ url=x[0],
485
+ dir=x[1],
486
+ unzip=unzip,
487
+ delete=delete,
488
+ curl=curl,
489
+ retry=retry,
490
+ exist_ok=exist_ok,
491
+ progress=threads <= 1,
492
+ ),
493
+ zip(url, repeat(dir)),
494
+ )
495
+ pool.close()
496
+ pool.join()
497
+ else:
498
+ for u in [url] if isinstance(url, (str, Path)) else url:
499
+ safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry, exist_ok=exist_ok)
@@ -0,0 +1,43 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from ultralytics.utils import emojis
4
+
5
+
6
+ class HUBModelError(Exception):
7
+ """
8
+ Exception raised when a model cannot be found or retrieved from Ultralytics HUB.
9
+
10
+ This custom exception is used specifically for handling errors related to model fetching in Ultralytics YOLO.
11
+ The error message is processed to include emojis for better user experience.
12
+
13
+ Attributes:
14
+ message (str): The error message displayed when the exception is raised.
15
+
16
+ Methods:
17
+ __init__: Initialize the HUBModelError with a custom message.
18
+
19
+ Examples:
20
+ >>> try:
21
+ >>> # Code that might fail to find a model
22
+ >>> raise HUBModelError("Custom model not found message")
23
+ >>> except HUBModelError as e:
24
+ >>> print(e) # Displays the emoji-enhanced error message
25
+ """
26
+
27
+ def __init__(self, message="Model not found. Please check model URL and try again."):
28
+ """
29
+ Initialize a HUBModelError exception.
30
+
31
+ This exception is raised when a requested model is not found or cannot be retrieved from Ultralytics HUB.
32
+ The message is processed to include emojis for better user experience.
33
+
34
+ Args:
35
+ message (str, optional): The error message to display when the exception is raised.
36
+
37
+ Examples:
38
+ >>> try:
39
+ ... raise HUBModelError("Custom model error message")
40
+ ... except HUBModelError as e:
41
+ ... print(e)
42
+ """
43
+ super().__init__(emojis(message))